Use MySQL IF in PHP
In this article I explain MySQL if, function in PHP
MySQL IF Function
The MySQL IF function is used to test a condition and return a value if the condition is true or another value if the condition is false. In other words, the if function takes three arguments and if the first expression of the given condition is TRUE then it returns the second expression (the true expression) and if the given condition is FALSE then it returns the third expression (the false expression).
Syntax
IF (condition (means expression), if_true_expression, if_false_expression ); |
Parameters in IF function
It takes three parameters; they are:
Parameter |
Description |
condition |
It specifies a expression. |
if_true_expression, |
Return, when condition is true. |
if_false_expression, |
Return, when condition is false. |
Example of MySQL If function in PHP
<?php
$con=mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql", $con);
print "<h2>MySQL: Use of IF function</h2>";
$result = mysql_query("SELECT monger_name, IF(monger_country='france','Available','Notavailable') AS isCity_France FROM vendordtl");
echo "<table border='1'>
<tr>
<th>VendorName</th>
<th>IsCityFrance</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['monger_name'] . "</td>";
echo "<td>" . $row['isCity_France'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Output
