2017-01-03 112 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)只是返回一个结果对象 –