PHP MySQL Where Clause
To select only data that matches a specified criteria, add a WHERE
clause to the SELECT
statement.
The following example creates and populates a Customers
table using the following SQL commands:
1 | CREATE TABLE Customers ( |
2 | ID INT AUTO_INCREMENT PRIMARY KEY , |
3 | name VARCHAR (16) NOT NULL ); |
5 | INSERT INTO Customers ( name ) VALUES ( 'Ben' ), ( 'Bart' ), ( 'Mandy' ), ( 'Ella' ); |
|
and selects customers using the
BETWEEN ... AND
operator:
1 | SELECT * FROM Customers WHERE ID BETWEEN $low AND $high; |
|
|
|
if ( $action == "Drop" ) {
// Drop table Customers.
$conn->query( "DROP TABLE Customers" );
echo "Table Customers dropped";
}
|
elseif ( $action == "Create & populate" ) {
// Create table Customers.
$sql = "CREATE TABLE Customers (
ID INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(16) NOT NULL )";
$conn->query( $sql );
echo "Table Customers created";
// Insert customers.
$sql = "INSERT INTO Customers (name) VALUES
('Ben'), ('Bart'), ('Mandy'), ('Ella')";
$conn->query( $sql );
echo " Table Customers populated"
}
|
elseif ( $action == "Select" ) {
// Select customers.
$sql = "SELECT * FROM Customers WHERE ID BETWEEN $low AND $high";
$result = $conn->query( $sql );
while ( $row = $result->fetch_assoc( ) )
echo $row['ID'] . ", " . $row['name'];
}
$conn->close( );
?>
</body></html>
|
|