2017-01-03 115 views
0

我會在前言中說我已經堅持了幾天,我明顯是新的,並且知道我錯過了簡單的事情。我嘗試了很多方法。安全性還沒有問題,我只是想在我自己的服務器上學習。檢查數據庫中是否存在值?

即使當我知道該值不存在時,我總能得到'找到的東西'。我試圖在輸入字段中輸入一個短語,按提交併查看錶中的值是否已經存在

對不起,這個愚蠢的問題。

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 
// error_reporting(0); 
// ini_set('display_errors', 0); 
// exit(); 
//echo '<pre>'; print_r($user_info); echo '</pre>'; 

if ((isset($_POST['lookup'])) && ($_REQUEST['lookup'] =='1')) { 
    echo 'you\'ve entered a keyword, lets see if it exsists!'; 
    $looksql = "SELECT * FROM `crm3`.`keywords` WHERE `KW0` LIKE '".$_POST['lookup']."' ORDER BY `ID` ASC "; 
    if ($result = mysqli_query($db, $looksql)) { 
     echo '<br>someting found'; 
    } else { echo '<br>nothing found'; } 
} else { 
    echo '<br>please enter a keyword to start the search'; 
} 
?> 

<br><br><br> 
<form method="POST" action="./?action=kwcheck"> 
    <input type="hidden" name="lookup" value="1" /> 
    keyword lookup: <input type="text" name="keyword" /><br> 
    <input type="submit" value="SEARCH" /> 

回答

2

你已經做幾乎一切權利,除非條件。你的病情總是給出真實值。它應該是:

// Query the MySQL server. 
$result = mysqli_query($db, $looksql); 
if (mysqli_num_rows($result)) { 
    // Rows are there. 
    echo '<br>someting found'; 
} else { 
    // No rows are there. 
    echo '<br>nothing found'; 
} 

如果你想它的功能,你可以創建一個返回一個布爾值的函數:true,如果找到的項目,false,如果不是。

function recordsCount($looksql) { 
    // Get the connection from global scope. 
    global $db; 
    // Query the MySQL server. 
    $result = mysqli_query($db, $looksql); 
    // Return if the count is greater than 0 or not. 
    return (mysqli_num_rows($result) > 0); 
} 

安全問題:使用參數化查詢。在查詢中輸入$_POST(或任何用戶輸入$_GET,$_COOKIE等)將打開SQL注入。此外,如果您想要完全匹配,請使用=,而不是LIKELIKE應該用於部分匹配並使用通配符(%)。感謝chris85

+1

謝謝,它現在的作品! –

+0

我仍然得到一個錯誤,因爲我的查詢是錯誤的,它應該是: 'code'的$ _ POST [「關鍵字」]代替$ _ POST [「查找」]'code' 也許我可以藉此一步進一步讓它顯示結果的行ID? –

+0

@DavidWatson是的,你是對的... –

0

你已經做錯了

if ($result = mysqli_query($db, $looksql)){// this is always true as query will be executed always  
    echo '<br>someting found';  
} 

上面始終執行代碼,因爲它是一樣,如果查詢執行則使回聲消息,所以如果條件永遠是真試試下面的代碼

$result = mysqli_query($db, $looksql);  
if (mysqli_num_rows($result)) { 
    echo '<br>someting found'; 
} 
+0

這與我的回答有什麼不同?只是好奇。 –

+0

@PraveenKumar我還沒有說過你的答案是錯的或其他任何東西 – user1234

+0

你至少可以格式化或縮進代碼。 –

-1

你可以試試這樣的:

$looksql = "SELECT * FROM `crm3`.`keywords` WHERE `KW0` LIKE '%".$_POST['lookup']."%' ORDER BY `ID` ASC "; 

使用%後210

+1

這並不能解釋爲什麼OP正在獲得結果。如果OP沒有得到結果,這可能是答案。 – chris85

+0

是的!並且謝謝我錯過$ result = mysqli_query($ db,$ lookql)只是返回一個結果對象 –