0

I have a code to insert into mysql database. Which is

schname is something like = St. Thame's College

$schname = $_GET['schname'];
$sql= "INSERT INTO `school` (id, schname, place) VALUES (' ',  $schname, 'place',)";

But after the 's in $schname the query wont run. Can I get to know how to solve that, as all most all school names have 's after their name.

Ruch1234
  • 111
  • 1
  • 11

2 Answers2

5
$schname = addslashes($_GET['schname']);  

Use variable with addslashes function

Nikul
  • 1,025
  • 1
  • 13
  • 33
  • +1 for the correct answer but either your code and op code's are vulnerable to mysql injections – Fabio Sep 17 '14 at 17:58
  • This code will not work; a string such as `St. Thame's College` will need to be escaped and quoted in single quotes. – user1477388 Sep 17 '14 at 17:59
  • will have to use values (' ','$schname','place') after doing addslashes as answered by @nikul – nitigyan Sep 17 '14 at 18:00
  • 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 '\'s College , 'UK' at line 1 .. i got this error – Ruch1234 Sep 17 '14 at 18:02
  • If you will use addslashes("St. Thame's College"). it will take that variable as "St. Thame\'s College". – Nikul Sep 17 '14 at 18:04
  • It worked. Thank You. @Fabio what do you mean these are vulnerable to mysql injections? – Ruch1234 Sep 17 '14 at 18:09
  • @ruch1234 that's what i meant, check here http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?lq=1 – Fabio Sep 17 '14 at 18:56
-1

Need to wrap the variable in quotes.

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$schname = $mysqli->real_escape_string($_GET['schname']);
$sql= "INSERT INTO `school` (id, schname, place) VALUES (' ', '$schname', 'place')";

$mysqli->query($sql);

Ref. http://php.net/manual/en/mysqli.real-escape-string.php

user1477388
  • 20,790
  • 32
  • 144
  • 264