0

I use js to get user "name" and send it to result.php by ajax.

in result.php

$name = $_POST['name'] //name contain string

// Then I want to select information from that user "name"
$result2 = $db->query('SELECT story FROM `user_story` WHERE name='.$name) or error('failed', __FILE__, __LINE__, $db->error());

But why doesn't it work?

Can anybody explain this to me and provide a solution?

Thanks in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    If you'd checked for errors/actually read the error, you'd probably get a syntax error. Strings need to be quoted. Use prepared statements with parameter binding so you don't need to worry about quoting issues. – aynber May 08 '17 at 15:08
  • yes, the error was same with the code I've wrote above to handle error condition (failed). Can you give me some example? – Larasati Habibi May 08 '17 at 15:13
  • You previously had mysqli tagged, so I'd suggest [starting here](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). – aynber May 08 '17 at 15:14
  • OK thanks, I'll check it out – Larasati Habibi May 08 '17 at 15:16
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) prepared statements with bound parameters as described in [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Alex Howansky May 08 '17 at 15:17

1 Answers1

2

Try this with quotes:

//ADDED semicolon
$name = $_POST['name']; //name contain string 
// Then I want to select information from that user "name"
$result2 = $db->query('SELECT story FROM `user_story` WHERE name= "'.$name .  '"') or error('failed', __FILE__, __LINE__, $db->error());

note: The best way is to use PDO prepared statements.

$name = $_POST['name'];

$result2 = $db->prepare("SELECT story FROM user_story WHERE (name = ?)");

$result2->execute(array($name));

Look at PDO and Prepared statements

nekiala
  • 450
  • 9
  • 21