I'm trying to take the following code from the PHP website and rewrite to echo out if the returns my SQL data is null.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s
", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
I'm having issues figuring out the right conditional to do this. Just looking for idea's on how to further optimize this code.
$rows = $stmt->rowCount();
echo $rows;
If you are trying to find out whether $district variable is null after the execution of the SQL query, you can try:
if(!empty($district)){
//code if there is a value
}
else{
//code if it is null
}
If you are sure that the database returns null if not found, you can use !is_null($district) instead of !empty($district).