Search code examples
phpmysqlmysql-select-db

mysql SELECT not working shows error


I am getting the below error:

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'

Here is the main page..

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

and here is the second page the error appearing on. the address bar reads 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>

Solution

  • You want to use urldecode to decode the encoded string in your query:

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

    I'm assuming you have a column named title in your test table. I don't think MySQL has urlencode function unless you have a procedure by that name which functions exactly like PHP's urlencode.

    Update:

    Thanks to @GeorgeLund, who pointed out the point of SQL Injection. Important topic which I missed earlier during answering your question. Please have a look at: https://www.owasp.org/index.php/SQL_Injection

    For the very least please update your code to following:

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