PHP MySQL SELECT QUERY


To perform a SELECT query in PHP using MySQLi in procedural style, follow these steps:

1. Establish a Database Connection

Connect to the MySQL database using mysqli_connect().

$conn = mysqli_connect('localhost', 'username', 'password', 'database');
if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }

2. Prepare the SELECT Query

Construct the SQL SELECT query string. For example, if you want to retrieve all records from a table named users, your query might look like this:

$sql = "SELECT * FROM users";

3. Execute the Query

Use mysqli_query() to execute the SELECT query.

$result = mysqli_query($conn, $sql);

4. Process the Results

The result returned by mysqli_query() is a result set that you can iterate over. Use functions like mysqli_fetch_assoc() to fetch rows from the result set.

if ($result) {
// Fetch each row and display it while ($row = mysqli_fetch_assoc($result)) { echo "Username: " . $row['username'] . " - Email: " . $row['email'] . "<br>"; } // Free result set mysqli_free_result($result); } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); }

5. Close the Database Connection

After processing the results, close the connection using mysqli_close().

mysqli_close($conn);

Full Example

Here is a complete example of a SELECT query using MySQLi in procedural style:

<?php
// Step 1: Connect to the database $conn = mysqli_connect('localhost', 'username', 'password', 'database'); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Step 2: Prepare the SELECT query $sql = "SELECT * FROM users"; // Step 3: Execute the query $result = mysqli_query($conn, $sql); // Step 4: Process the results if ($result) { // Fetch each row and display it while ($row = mysqli_fetch_assoc($result)) { echo "Username: " . $row['username'] . " - Email: " . $row['email'] . "<br>"; } // Free result set mysqli_free_result($result); } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // Step 5: Close the connection mysqli_close($conn); ?>

Notes

  • Error Handling: Always check if mysqli_query() returns false to handle potential errors in the query execution.
  • Fetching Data: mysqli_fetch_assoc() fetches a row as an associative array where the keys are the column names. Other fetching functions include mysqli_fetch_row() (numeric array) and mysqli_fetch_array() (both associative and numeric).
  • Freeing Result Set: Use mysqli_free_result() to free the memory associated with the result set when done.