我试图从PHP网站上获取以下代码,如果返回我的SQL数据为空,则重写以回显。
<?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();
?>
我遇到了解决这个问题的正确条件的问题。只是想了解如何进一步优化此代码的想法。
答案 0 :(得分:2)
$rows = $stmt->rowCount();
echo $rows;
答案 1 :(得分:0)
如果您在执行SQL查询后试图找出$ district变量是否为null,则可以尝试:
if(!empty($district)){
//code if there is a value
}
else{
//code if it is null
}
如果您确定数据库在未找到时返回null,则可以使用!is_null($ district)而不是!empty($ district)。