PHP Tutorial
PHP Flow Control
PHP Functions
PHP String
PHP Array
PHP Date Time
PHP Object Oriented
Regular Expression
PHP Cookie & Session
PHP Error & Exception handling
MySQL in PHP
PHP File Directory
PHP Image Processing
Getting SQL query results in PHP is a common task when working with a database. In this tutorial, we will use MySQLi, a PHP extension designed to work with MySQL databases.
Firstly, you'll need to establish a connection to your MySQL database using mysqli_connect()
:
// Database credentials $db_host = 'localhost'; $db_user = 'username'; $db_pass = 'password'; $db_name = 'database_name'; // Create connection $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }
Next, you can use a SELECT query to get data from your database:
// SQL query $sql = "SELECT * FROM table_name"; // Execute query and get result $result = mysqli_query($conn, $sql); if ($result) { // Fetch all rows as an associative array while($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>"; } } else { echo "Error: " . mysqli_error($conn); }
In this example, mysqli_query()
executes the SQL query and returns a result set. Then, mysqli_fetch_assoc()
is used in a while loop to fetch each row from the result set as an associative array. The array keys are the column names and the array values are the data in each row.
Finally, don't forget to close the connection when you're done:
// Close connection mysqli_close($conn);
This is a simple example. Depending on your needs, you may want to handle errors more gracefully, escape your SQL queries to prevent SQL injection, fetch rows as objects instead of arrays, or use prepared statements for better performance and security.
Note: While MySQLi is a powerful extension, many developers prefer to use the PDO (PHP Data Objects) extension instead because it provides a more consistent interface for working with different types of databases.
Retrieving data from MySQL database in PHP:
mysqli_query()
to execute SQL queries and retrieve data.<?php $mysqli = new mysqli('localhost', 'username', 'password', 'database'); // Check connection if ($mysqli->connect_error) { die('Connection failed: ' . $mysqli->connect_error); } // Execute a SELECT query $result = $mysqli->query('SELECT * FROM users'); // Process the result set // ... // Close the connection $mysqli->close();
Using mysqli_query() in PHP to execute SQL queries:
mysqli_query()
.<?php // Execute a SELECT query $result = $mysqli->query('SELECT * FROM products'); // Execute an INSERT query $insertResult = $mysqli->query('INSERT INTO orders (product_id, quantity) VALUES (1, 10)');
Fetching and displaying SQL query results in PHP:
<?php $result = $mysqli->query('SELECT * FROM customers'); while ($row = $result->fetch_assoc()) { echo "Name: {$row['name']}, Email: {$row['email']}<br>"; }
Handling SELECT queries with PHP and MySQL:
<?php $result = $mysqli->query('SELECT * FROM orders'); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { // Process each row } } else { echo "No results found."; }
Error handling when getting SQL query results in PHP:
<?php $result = $mysqli->query('SELECT * FROM customers'); if ($result === false) { die('Query failed: ' . $mysqli->error); }
Binding parameters and executing prepared statements in PHP:
<?php $stmt = $mysqli->prepare('SELECT * FROM products WHERE category = ?'); $category = 'Electronics'; $stmt->bind_param('s', $category); $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) { // Process each row }
Converting SQL results to arrays or objects in PHP:
<?php // Convert to associative array $resultArray = $result->fetch_all(MYSQLI_ASSOC); // Convert to objects $resultObject = $result->fetch_object();
Processing and manipulating SQL query results in PHP:
<?php $result = $mysqli->query('SELECT * FROM products'); while ($row = $result->fetch_assoc()) { // Process each row $productName = $row['name']; // ... }