简体   繁体   English

Mysql Query在特定情况下不起作用

[英]Mysql Query not working in particular case

Have a table with two columns 'ques' and 'ans'. 有一个包含两列'ques'和'ans'的表格。 After comparing through this query I calculate the number of rows fetched by mysql_nuum_rows($result). 通过此查询进行比较后,我计算了mysql_nuum_rows($ result)获取的行数。 I am getting error in certain cases like if I am choosing same option (last option in each case ie D of radio button) for all questions. 在某些情况下我会收到错误,例如我选择相同的选项(每种情况下的最后一个选项,即单选按钮的D)。 The rest is working perfectly. 其余的工作完美。

What am I doing wrong? 我究竟做错了什么?

//  (Values are coming from html form consisting of 4 sets of 4 radio buttons)
$q1=$_POST['q1'];
$q2=$_POST['q2'];
$q3=$_POST['q3'];
$q4=$_POST['q4'];
$result = mysql_query("SELECT * FROM Test  
               WHERE (ques='q1' AND ans='$q1') 
               OR (ques='q2' AND ans='$q2') 
               OR (ques='q3' AND ans='$q3') 
               OR (ques='q4' AND ans='$q4')");

Expected Output: 预期产出:
You got 3 right answers out of 4 (3 comes from mysql_num_rows() ) 你有4个正确的答案(3来自mysql_num_rows()

Error Coming: 错误来了:
You have an error in your SQL syntax; 您的SQL语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'q2' AND ans='4') OR (ques='q3' AND ans='4') OR (ques='q4' AND ans='4')' at line 1 检查与MySQL服务器版本对应的手册,以便在'q2'和ans ='4'附近使用正确的语法。或者(问题='q3'和ans ='4')或者(问题='q4'和ans第1行='4')'

What you are doing wrong: 你做错了什么:

a) you're not using prepared statements. a)你没有使用准备好的陈述。 That means that user-supplied input will end up in your SQL statement, exposing you to unforseen risks (SQL injection). 这意味着用户提供的输入将最终出现在SQL语句中,从而使您面临无法预料的风险(SQL注入)。 This might also be the cause for the SQL error. 这也可能是SQL错误的原因。 You could either assign the SQL statement to a variable and dump it somewhere so you can see what you actually are trying to do. 您可以将SQL语句分配给变量并将其转储到某个位置,以便您可以看到实际尝试执行的操作。 Or (better) you could use prepared statements. 或者(更好)你可以使用预备语句。

b) the SQL statement looks like you have a problem if your form will be extended to 25 questions plus answers. b)如果您的表单将扩展到25个问题加上答案,那么SQL语句看起来就像您有问题。 If not - why are you using an SQL back end for this? 如果没有 - 为什么你使用SQL后端呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM