0
$f_name="Tom";
$select_user="SELECT * from users where f_name=$f_name";

The code above does not work but when I run the code below it works perfectly when not stored in a variable.

My problem is that I need to store the first name in a variable before using it.

$select_user="SELECT * from users where f_name='Tom'";

I tried the code below and expected it to select tom but it returns nothing

$f_name="Tom";
$select_user="SELECT * from users where f_name=$f_name";
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • 1
    P.S. It should be generating an error rather than just returning nothing, because it will cause a SQL syntax error due to not using quotes round the name, or not using parameters. Make sure you have error reporting switched for your database library (e.g. mysqli and PDO have specific ways to enable it) – ADyson Feb 24 '23 at 16:58
  • As well as the above, https://phpdelusions.net also contains good examples of writing safe SQL using mysqli and PDO (assuming you're using one of those...there's documentation on how to do this properly with other libraries too if you look online). Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use that resource again. – ADyson Feb 24 '23 at 17:00

1 Answers1

-1

Welcome to Stack Overflow!

The example code you show is vulnerable to SQL injection, which can destroy your site (or worse, allow intruders to steal data and impersonate users).

What you want are prepared statements / parameterized queries:

https://www.php.net/manual/en/pdo.prepared-statements.php

Hopefully this will point you in the right direction. Have fun!