PHP MySQL Select Data

Selecting data from a MySQL table using PHP involves executing a SQL query that retrieves data from the table. Here’s an example of how to select data from a MySQL table using PHP:

<?php
// MySQL server configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
// Select data from the table
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
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"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}
// Close the connection
mysqli_close($conn);
?>

In this example, we first define the configuration for the MySQL server by specifying the server name, username, and password. We also specify the name of the database we want to work with in the $dbname variable. We then create a connection to the server and select the appropriate database using the mysqli_connect() function.

Next, we define the data we want to retrieve from the table in the $sql variable using SQL syntax. In this example, we select all columns from a table called “users”.

We then execute the SQL query using the mysqli_query() function and store the result in a variable called $result. We check if there are any rows returned using the mysqli_num_rows() function. If there are rows, we iterate through each row using the mysqli_fetch_assoc() function and print the values of the columns.

Finally, we close the connection using the mysqli_close() function.