[英]Call to DB to check if a value exists
I'm trying to run a query to check if what is entered into a textfield matches that of what is stored in a database. 我试图运行查询以检查输入到文本字段中的内容是否与数据库中存储的内容匹配。
The current code: 当前代码:
</form>
<br />
<h2>Discount Code</h2>
<br />
<form method="POST" action=''>
<input type="text" name="discount" />
<input type="submit" name="discountSubmit" value="Apply" />
<?php
if(isset($_POST['discountSubmit'])){
$discountCode = $_POST['discount'];
$codeCheck = mysqli_query("SELECT code FROM discount WHERE code = $discountCode");
var_dump($codeCheck);
}
?>
</form>
However, upon clicking discountSubmit the var_dump returns NULL so it would lead me to assume $codeCheck is wrong, however it looks right to me. 但是,在单击DiscountSubmit时,var_dump返回NULL,因此将导致我假设$ codeCheck错误,但是对我来说似乎正确。
I connect through the database through another page so the issue doesnt lie there 我通过另一个页面连接数据库,所以问题不就在那里
Database Structure: 数据库结构:
id code discount expire
1 WEB10 10.00 2013-06-01
Expire isn't relevant just at the moment. 目前,到期并不重要。
Here, code is not an integer value. 此处,代码不是整数值。 Hence, enclose it by single quotes. 因此,将其用单引号引起来。 You should also include the $conn
(connection variable) while using mysqli_query()
statement - mysqli_query() 使用mysqli_query()
语句时,还应包括$conn
(连接变量) -mysqli_query()
$codeCheck = mysqli_query($conn, "SELECT code FROM discount WHERE code = '$discountCode'");
[EDIT] If you are including the connection page inside this page, try doing these: [编辑]如果要在此页面中包括连接页面,请尝试执行以下操作:
connect.php connect.php
function connect(){
$conn = mysqli_connect($host, $un, $pw, $db);
return $conn;
}
Now, call this function from the current page and get the connection variable: 现在,从当前页面调用此函数并获取连接变量:
$conn = connect();
Now, use $conn
for the mysqli_query()
function. 现在,将$conn
用于mysqli_query()
函数。
Change the if condition as follows: 更改if条件,如下所示:
if(isset($_POST['discount']))
A better version for your code, courtesy of safeMysql which works the natural way you expect from mysqli_query but don't get it. 由safeMysql提供的一种更好的代码版本,可以正常使用mysqli_query期望的方式,但是没有得到。
<?php
$check = NULL;
if(isset($_POST['discountSubmit']))
{
$sql = "SELECT code FROM discount WHERE code = ?i";
$check = $db->getOne($sql, $_POST['discount']);
}
?>
<h2>Discount Code</h2>
<br />
<form method="POST" action=''>
<input type="text" name="discount" />
<input type="submit" name="discountSubmit" value="Apply" />
</form>
<?php var_dump($check); ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.