[英]Check if value exists in database?
首先,我会说我已经坚持了几天,显然我是新来的,并且知道我缺少一些简单的东西作为开头。 我已经尝试了很多方法。 安全性还不是问题,我只是想在自己的服务器上学习。
即使我知道该值不存在,我也总是得到“发现的东西”。 我正在尝试在输入字段中输入短语,按提交,然后查看表中是否已存在该值
很抱歉这个愚蠢的问题。
<?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" />
除条件外,您几乎已做对了所有事情。 您的病情总能带来真实的价值 。 它应该是:
// 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注入。 另外,如果您想要完全匹配,请使用=
,而不是LIKE
。 LIKE
应该用于部分匹配,并使用通配符( %
)。 感谢chris85 。
你做错了
if ($result = mysqli_query($db, $looksql)){// this is always true as query will be executed always
echo '<br>someting found';
}
上面的代码总是执行,因为就像执行查询一样,则回显消息,因此,如果条件始终为true,请尝试下面的代码
$result = mysqli_query($db, $looksql);
if (mysqli_num_rows($result)) {
echo '<br>someting found';
}
您可以尝试以下方法:
$looksql = "SELECT * FROM `crm3`.`keywords` WHERE `KW0` LIKE '%".$_POST['lookup']."%' ORDER BY `ID` ASC ";
like
后使用%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.