mysql SELECT不工作显示错误

时间:2013-08-09 04:19:04

标签: php mysql mysql-select-db

我收到以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'testing order by id'

这是主页..

echo "<div ><a href='secondpage.php?title=".urlencode($row['title'])."'>".wordwrap($row['title'], 35, "<br />\n", true)."</a></div>";

这是出现错误的第二页。地址栏显示http://localhost/secondpage.php?title=more+testing

 <?php
   $mydb = new mysqli('localhost', 'root', '', 'test');
   $sql = "SELECT * FROM test where urlencode(title) =".$_GET['title']" order by id ";
     $result = $mydb->query($sql);
  if (!$result) {
  echo $mydb->error;
 }


 ?> 
 <div>
 <?php
 while( $row = $result->fetch_assoc() ){

 echo $row['firstname'];
 }
 $mydb->close ();
 ?>
 </div>

5 个答案:

答案 0 :(得分:1)

您希望使用urldecode解码查询中的已编码字符串:

$title = urldecode($_GET['title']);
$sql = "SELECT * FROM test where title = '$title' order by id";

我假设您的title表中有一个名为test的列。我不认为MySQL有urlencode函数,除非你有一个名称与PHP的urlencode完全相同的程序。

<强>更新

感谢@GeorgeLund,他指出了SQL注入的重点。在回答您的问题时我之前错过的重要主题。请查看:https://www.owasp.org/index.php/SQL_Injection

至少请将您的代码更新为以下内容:

$title = urldecode($_GET['title']);
$title = mysqli_real_escape_string($title); // Addition
$sql = "SELECT * FROM test where title = '$title' order by id";

答案 1 :(得分:1)

$sql = "SELECT * FROM test where urlencode(title) ='".$_GET['title']."' order by id ";

答案 2 :(得分:0)

尝试

$sql = "SELECT * FROM test WHERE urlencode(title) = ".$_GET['title']." ORDER BY id ";

您错过了.引导语法消失。

答案 3 :(得分:0)

据我所知,SQL没有函数urlencode,为什么你甚至想要urlencode列名呢?

同样要存储从最后一页接收的编码标题字符串,您应解码编码标题

所以这就是我认为你的意思。

$sql = "SELECT * FROM test WHERE title = ".urldecode($_GET['title'])." order by id ";

答案 4 :(得分:-1)

请使用urldecode

尝试此代码
$sql = "SELECT * FROM test where title =".urldecode($_GET['title'])" order by id ";