📜  php pdo fetch from db - PHP (1)

📅  最后修改于: 2023-12-03 15:33:30.830000             🧑  作者: Mango

PHP PDO Fetch From DB

This tutorial will explain how to fetch data from a database using PHP and PDO. It assumes that you are familiar with PHP and that you have a database already set up.

Setting Up PDO

PDO stands for PHP Data Objects and it provides a consistent interface for working with databases. The first step is to create a new PDO object with the database connection details. It is recommended to put the database details in a separate file and include it in your PHP script.

<?php
//include database details
include 'db_details.php';

//create new PDO object
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
}
catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>
Executing SQL Statements

To fetch data from a database, you will need to execute a SQL statement. The PDO object has a method called query() that can be used to execute SQL statements. The query() method returns a PDOStatement object that can be used to fetch the data.

<?php
//execute sql statement
$sql = "SELECT * FROM users";
$stmt = $pdo->query($sql);

//fetch data
while ($row = $stmt->fetch()) {
    echo $row['user_id'] . " " . $row['username'] . "<br>";
}
?>

In the code above, we execute a SQL SELECT statement to fetch all the data from the users table. We then use the fetch() method of the PDOStatement object to fetch each row of data. We loop through each row and print the user_id and username.

Fetching Data

There are several methods that can be used to fetch data from a PDOStatement object:

  • fetch() - fetches the next row of data and returns it as an associative array, a numbered array, or an object.
  • fetchAll() - fetches all the rows of data and returns them as an array of associative arrays, numbered arrays, or objects.
  • fetchColumn() - fetches a single column from the next row of data.
<?php
//execute sql statement
$sql = "SELECT * FROM users";
$stmt = $pdo->query($sql);

//fetch data as associative array
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['user_id'] . " " . $row['username'] . "<br>";
}

//fetch all data as numbered array
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
foreach ($rows as $row) {
    echo $row[0] . " " . $row[1] . "<br>";
}

//fetch single column
$name = $stmt->fetchColumn(1);
echo $name;
?>

In the example above, we fetch data as an associative array using fetch(PDO::FETCH_ASSOC). We then fetch all the data as a numbered array using fetchAll(PDO::FETCH_NUM). Finally, we fetch a single column using fetchColumn(1).

Conclusion

In this tutorial, we have learned how to use PDO in PHP to fetch data from a database. We have covered how to set up PDO, execute SQL statements, and fetch data using various methods. PDO provides a convenient and secure way to work with databases in PHP.