将两个输入与数据库数据进行比较:错误 [英] Comparing two inputs with database data: error
问题描述
我正在尝试将两个输入值与MySQL表中SAME ROW中的两个值进行比较. 但是我总是收到错误消息.这段代码有什么问题? (仅需一个输入就可以正常工作)
I'm trying to compare two input values with two values from a SAME ROW, from a MySQL table. But I always get an error message. What is wrong in this code? (It worked fine with just one input)
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$numero_cedula = mysqli_real_escape_string($con, $_POST['numero_cedula']);
$codigo= mysqli_real_escape_string($con, $_POST['codigo']);
$sql1 = " SELECT Numero Cedula FROM Teste WHERE Numero Cedula=$numero_cedula
AND Chave=$codigo";
$objGet = mysqli_query($con, $sql1);
if( mysqli_num_rows($objGet) > 0 ) {
echo "Duplicate";
} else {
echo "Not a duplicate";
}
推荐答案
尽管SQL中允许在列名中使用空格,但这样做的原因(在您的情况下为 )是因为列名
Although spaces in column names are allowed in SQL, the reason for this (in your case) is because the column name Numero Cedula
contains a space:
v -- space v -- space
$sql1 = "SELECT Numero Cedula FROM Teste WHERE Numero Cedula=$numero_cedula
AND Chave=$codigo";
将列名称包装在反引号中时,将其更改为以下内容:
Change it to the following while wrapping the column name in backticks:
$sql1 = "SELECT `Numero Cedula` FROM Teste WHERE `Numero Cedula`=$numero_cedula
AND Chave=$codigo";
此外,请确保$numero_cedula
和$codigo
都是整数,并且您的列也是int
类型.
Plus, make sure that both $numero_cedula
and $codigo
are integers, and that your columns are also int
types.
如果没有,则两者都需要用引号引起来.
If they are not, then both will need to be wrapped in quotes.
即:
$sql1 = "SELECT `Numero Cedula` FROM Teste WHERE `Numero Cedula`='$numero_cedula'
AND Chave='$codigo'";
在mysqli_query()
中添加or die(mysqli_error($con))
,这将向您显示SQL错误.
Add or die(mysqli_error($con))
to mysqli_query()
which will show you the error in SQL.
- 您还可以使用下划线将数据库中的列重命名为
Numero_Cedula
.
边注:
Sidenote:
您写道:仅一次输入就可以正常工作"..
您需要对此进行详细说明,并且您的表中是否包含两个单独的列,例如Numero
和 Cedula
还是一个Numero Cedula
.
You will need to elaborate on that and whether your table contains two seperate columns such as Numero
and Cedula
or one Numero Cedula
.
但是,使用此方法必须遵守 SQL注入 .使用 准备好的声明 ,或 带有准备好的语句的PDO .
However, using this method is subject to SQL injection. Use prepared statements, or PDO with prepared statements.
见解:
An insight:
还要确保您的表单元素已命名.
Also make sure that your form elements are named.
即:name="numero_cedula"
和name="codigo"
在文件顶部添加错误报告,这将有助于发现错误.
Add error reporting to the top of your file(s) which will help find errors.
error_reporting(E_ALL);
ini_set('display_errors', 1);
边注:错误报告仅应在登台中进行,决不能用于生产.
Sidenote: Error reporting should only be done in staging, and never for production.
这篇关于将两个输入与数据库数据进行比较:错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!