MySQL Where Clause in PHP

Introduction

I will describe in this article how to use the MySQL "where" clause in PHP. The Where clause is a conditional clause in MySQL. The where clause fetches the records and allows you to filter the results from a MySQL statement.

Syntax Of a Simple Where Cause

SELECT * FROM table name
WHERE name = 'name';

 

Example

 

In  this example, I am doing a simple fetch of records from the table. Here I execute the Mysql_Query() function.

 

<?php

$con = mysql_connect("localhost","root","");

if (!$con)

  {

  die('Could not connect: ' . mysql_error());

  }

 

mysql_select_db("smart", $con);

 

$result = mysql_query("SELECT * FROM form

WHERE name='ram'");

echo "<table border='1'>

<tr>

<th>ID</th>

<th>name</th>

<th>Mobile</th>

<th>email</th>

</tr>";

while($row = mysql_fetch_array($result))

  {

  echo "<tr>";

  echo "<td>"  . $row['Id'] . "</td>";

  echo "<td>" .$row['name'] . "</td>";

  echo "<td>" . $row['Mobile'] ."</td>";

  echo "<td>" . $row['email'] . "</td>";

  echo "</tr>";

  }

  echo "</table>";

?>

Output

mysql-where-clause- in-php.jpg

Here, I am using a Where Clause with a logical operator such as "and", "or", and "Joining" the table with a where clause. Joining is for joining the two tables, such as:

Logical "and"

<?php

SELECT * FROM table name

WHERE name = 'shyam' and Id='2';

?>

Output

mysql-where-clause- in-php with and.jpg

Logical "or"

<?php

SELECT * FROM table name

WHERE Id = '1' and Id='2';

?>

Output

mysql-where-clause- in-php with or.jpg

Joining Table

<?php

SELECT * FROM form,emp

WHERE form.Id = ep.Id;

?>

Output

 mysql-where-clause- in-php-with-Join.jpg


Similar Articles