1 Short Answer
To get data from a database in PHP, use PDO to connect to MySQL, run a SELECT query, and read the result with fetch(), fetchAll(), or fetchColumn().
If your search query is php get data from database, the practical answer is: connect to MySQL, run a safe SELECT query, and choose the fetch method that matches the result shape.
Minimal workflow
- Prepare the MySQL DSN with host, database name, and charset.
- Create a
PDOconnection and enable exception mode. - Run the query with
prepare()andexecute(). - Choose
fetch(),fetchAll(), orfetchColumn()based on the result shape.
2 Example Table
The examples use a small users table to show the complete PHP get data from database flow.
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(200) NOT NULL UNIQUE,
status VARCHAR(20) NOT NULL DEFAULT 'active',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
3 Connect PHP to MySQL
To explain database connectivity in PHP with reference to MySQL, focus on the DSN, credentials, and PDO options. The DSN tells PHP which MySQL host and database to use, and which character set should be applied.
<?php
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=myapp;charset=utf8mb4';
$username = 'app_user';
$password = 'change_this_password';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
error_log('MySQL connection failed: ' . $e->getMessage());
exit('Database connection failed.');
}
DSN
Contains host, port, dbname, and charset. It defines the database target.
Error mode
ERRMODE_EXCEPTION throws exceptions when a connection or query fails.
Charset
utf8mb4 correctly supports multilingual text, emoji, and full Unicode data.
4 Fetch One Row, Many Rows, or One Value
One row: fetch()
$stmt = $pdo->prepare('SELECT id, name, email FROM users WHERE id = :id');
$stmt->execute(['id' => 1]);
$user = $stmt->fetch();
if ($user) {
echo $user['name'] . ' - ' . $user['email'];
}
Many rows: fetchAll()
$stmt = $pdo->prepare(
'SELECT id, name, email FROM users WHERE status = :status ORDER BY created_at DESC'
);
$stmt->execute(['status' => 'active']);
$users = $stmt->fetchAll();
foreach ($users as $user) {
echo "{$user['id']}: {$user['name']} ({$user['email']})\n";
}
One value: fetchColumn()
$stmt = $pdo->prepare('SELECT COUNT(*) FROM users WHERE status = :status');
$stmt->execute(['status' => 'active']);
$activeCount = (int) $stmt->fetchColumn();
echo "Active users: {$activeCount}";
5 Reusable Database Connection File
In a real project, do not repeat connection code on every page. Put it in one file and let application pages focus on queries.
<?php
// database.php
function db(): PDO
{
static $pdo = null;
if ($pdo === null) {
$pdo = new PDO(
'mysql:host=127.0.0.1;dbname=myapp;charset=utf8mb4',
'app_user',
'change_this_password',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
}
return $pdo;
}
<?php
// users.php
require __DIR__ . '/database.php';
$stmt = db()->prepare('SELECT id, name, email FROM users ORDER BY id DESC LIMIT 20');
$stmt->execute();
$users = $stmt->fetchAll();
6 Troubleshooting
could not find driver
The pdo_mysql extension is not installed or enabled. Check php -m and enable the MySQL PDO driver for the PHP runtime used by your web server.
Access denied for user
The username, password, or host permission is wrong. Confirm that the MySQL user has the minimum required privileges for the target database.
Broken characters or emoji insert failures
Use utf8mb4 in the DSN, database, tables, and columns. Do not rely only on HTML page encoding.
7 FAQ
What is the best way for PHP to get data from a database?
Use PDO with prepared statements. It is safer than concatenating SQL strings and easier to maintain than repeating connection code across pages.
What is the difference between fetch and fetchAll?
fetch() reads one row, which is useful for detail pages. fetchAll() reads every returned row, which is useful for lists but should be paired with pagination for large result sets.
Can mysqli connect PHP to MySQL?
Yes. However, PDO gives you a more consistent API and makes future changes to PostgreSQL or SQLite easier. New projects commonly choose PDO first.
Loading comments...