2012-02-02 41 views
0
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>";} 

它可以檢查行是否存在?有沒有更優雅的方式來做到這一點?謝謝使用mysqli檢索只有1行記錄

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

糾正後,它是正確的嗎?因爲它只是落入名單中已存在

+0

好滴滴計數只是搶id,否則其標準。 – 2012-02-02 18:28:33

+0

這是什麼意思的ID?謝謝 – user782104 2012-02-02 18:59:27

回答

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

還有一些問題,請看看 – user782104 2012-02-02 18:56:00

+0

'$ listName ='$ _POST [lname]';' - >'$ listName = $ _POST ['lname'];' 改爲'SELECT COUNT(*)FROM list WHERE listName =? LIMIT 1'使用'SELECT * FROM list WHERE listName =?' – cetver 2012-02-02 18:59:09

+0

仍然存在問題。請參閱我的修改代碼。謝謝很多 – user782104 2012-02-02 19:03:59