Domanda

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>
È stato utile?

Soluzione

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";

Altri suggerimenti

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

Try like

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

You missed . leads syntax go away.

As far as I know SQL does not have function urlencode and why would you even want to urlencode the column name?

Also to store the encoded title string which is received from the last page you should decode the encoded title

So here is what I think you meant to do.

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

Please try this code using urldecode

$sql = "SELECT * FROM test where title =".urldecode($_GET['title'])" order by id ";
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top