Thursday 2 January 2020

mysql - Properly escaping mysqli query in PHP




Uggh, I've had a few beers and I just can't seem to progress.



I'm teaching myself a bit of PHP with MySQL (just because) and this one line just has me stumped:



$user = $mysqli->query ("SELECT id FROM members WHERE username = " . $_SESSION['user_name'] . " LIMIT 1");


I'm sure it's something completely stupid but I need to have the '$_SESSION['user_name']' passed with quotes around it.




Look, I know its a stupid question, apologies in advanced but I can't even get the right Google terms to find what I'm after... sad I know!\



I've tried all combinations of slash escaping and single / double quotes... please help!


Answer



You should use prepared statements :)



$stmt = $mysqli->prepare("SELECT id FROM members WHERE username = ? LIMIT 1");
$stmt->bind_param('s', $_SESSION['user_name']);



http://es1.php.net/manual/en/mysqli-stmt.bind-param.php


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...