Google News
logo
Select data with MySQLi (Procedural) in PHP
In the following example of selecting data with MySQLi (Procedural) in PHP :
Program :
<?php
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdbname";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

// Select data
$sql = "SELECT id, firstname, lastname FROM users";
$result = mysqli_query($conn, $sql);

// Check if any rows were returned
if (mysqli_num_rows($result) > 0) {
  // Output data of each row
  while($row = mysqli_fetch_assoc($result)) {
    echo "ID: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
  }
} else {
  echo "0 results";
}

// Close connection
mysqli_close($conn);
?>
This example connects to a MySQL database, selects data from a table named "users", and outputs the ID, first name, and last name of each row that was returned by the query.

The `mysqli_query()` function is used to execute the SQL query, and the `mysqli_fetch_assoc()` function is used to fetch the result rows as associative arrays.

The `mysqli_num_rows()` function is used to check if any rows were returned by the query. Finally, the `mysqli_close()` function is used to close the database connection.