使用mysqli只检索1行记录

时间:2012-02-02 18:13:36

标签: php mysqli

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();
}

纠正后,是否正确?因为它只是存在于列表名称中

1 个答案:

答案 0 :(得分:1)

$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>');
}