PHP MySQL Use The WHERE Clause

Using the WHERE clause in MySQL using PHP involves executing a SQL query that selects rows from a table based on a specified condition. Here’s an example of how to use the WHERE clause in MySQL using 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 with a condition
$sql = "SELECT * FROM users WHERE lastname='Doe'";
$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

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” where the value of the “lastname” column is “Doe”.

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. The WHERE clause allows us to filter the results of the query to only include rows that meet a specific condition.