How can I use a variable in a MySQL select statement?
$serverid = $_SESSION['server_id'];
$sql = "SELECT * FROM servers WHERE server_id = '$serverid'";

2 Years
Discussion Span
Last Post by FarrisFahad

If i'm not blind i think your code is correct... Now you take that full sql query string and query it with @mysql_query() or @mysqli_query() or whatever extension you're using.

About string concatenation, there's others methods to do it too, the simpliest I think being this:

$sql = "SELECT * FROM servers WHERE server_id = '{$_SESSION['server_id']}'";

You can see other forms here: http://php.net/manual/en/language.types.string.php

And about MySQL Querys here: http://php.net/manual/en/function.mysql-query.php

Happy reading =)

Edited by AleMonteiro


I ran through the same problem when I was starting out. You need to understand this ...
If you want to add a number to the MySQL string just add the curly brackets around your variable
For example:

$sql = "SELECT * FROM servers WHERE server_id = {$integer}";

But in the above example the sql string have to be wrapped around double quotes, single quotes wont work
The example won't work:

$sql = 'SELECT * FROM servers WHERE server_id = $integer';

If you are passing a string rather than a number just add single quotes around the variable with curly brackets
For example:

$sql = "SELECT * FROM servers WHERE server_id = '{$string}'";
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.