简体   繁体   中英

Determine if PHP mysqli fetch returns data or not

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\n", 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\n", $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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM