使用 MySQLI 仅检索 1 行记录


using mysqli to retrieve only 1 row record

if ($stmt = $conn->prepare("SELECT COUNT(*) FROM list WHERE listName = ? LIMIT 1")) {
    $listName = '$_POST[lname]';
    $stmt->bind_param("s", $listName);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->close();
}
    if ($count>0)
{//do some insert}
else 
{echo "exist , <a href="">back</a>";}

它可以检查该行是否存在吗?有没有更优雅的方法可以做到这一点?谢谢

$stmt = $conn->prepare("SELECT COUNT(*) FROM list WHERE listName = ?");
$listName = $_POST['lname'];
$stmt->bind_param("s", $listName);
$stmt->execute();
$stmt->store_result();
try {
    if ($stmt->num_rows > 0 ) {
         throw new Exception('The list name is existed');
    }
} catch (Exception $e) {
   echo $e->getMessage();
   echo '<br />';
   exit('<a href="">back</a>');
   $stmt->close();
}

更正后,是否正确?因为它只是落入列表名称是存在的

$stmt->execute();
$stmt->store_result();
try {
    if ($stmt->num_rows == 0 ) {
         throw new Exception('There is no records');
    }
} catch (Exception $e) {
   echo $e->getMessage();
   echo '<br />';
   exit('<a href="">back</a>');
}