In PHP, you can retrieve the results of a SELECT query using MySQL functions. Below are some commonly used methods:
The mysql_fetch_array() function is used to fetch one row of a SELECT result and store it in an array.
$query = "SELECT * FROM table_name";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
// Process the result
}
In the example above, $query is the SELECT statement, and $result is the result set returned after executing the query. A while loop is used to iterate through each row of results. The $row variable represents the current row, and the field values can be accessed via array indexes or field names.
mysql_fetch_assoc() is similar to mysql_fetch_array(), but it returns an associative array with field names as keys.
$query = "SELECT * FROM table_name";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
// Process the result
}
mysql_fetch_object() converts the SELECT result into an object.
$query = "SELECT * FROM table_name";
$result = mysql_query($query);
while ($row = mysql_fetch_object($result)) {
// Process the result
}
PDO (PHP Data Objects) is a unified database access interface in PHP that allows you to work with different databases. Below is an example of retrieving SELECT results using PDO:
$query = "SELECT * FROM table_name";
$stmt = $pdo->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
// Process the result
}
mysqli is an enhanced version of PHP's MySQL extension, offering more features and an object-oriented interface. Below is an example of retrieving SELECT results using mysqli:
$query = "SELECT * FROM table_name";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
// Process the result
}
ORM (Object-Relational Mapping) frameworks map database operations to object-oriented operations. In Laravel, retrieving SELECT results can be done as follows:
$result = DB::table('table_name')->get();
foreach ($result as $row) {
// Process the result
}
This article covered several methods to retrieve SELECT query results from MySQL in PHP, including using mysql functions, PDO, mysqli, and ORM frameworks. These methods allow you to efficiently fetch and process SELECT results, and each is suitable for different development needs.