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

Recommended Answers

All 3 Replies

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 =)

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}'";
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.