I have a login form, the username and password that the user enters are saved in session variables. When I try to echo them it works. The problem is when I try to use them in a SQL query.
This works:
$sql3 = "SELECT whatever FROM table WHERE username='any_username_that_I_want'";
But this doesn’t:
$sql3 = "SELECT whatever FROM table WHERE username=$_SESSION['username']";
good point but even if it wasn’t there, the echo should have displayed at least part of the query if in fact the script gets to the query with or without session_start()
That means you need to break out of the string, put in the variable, and then go back into the string. The . concatenates string’s.
The confusing issue here, is the mix of both PHP and SQL codes… blue parts are PHP bits red parts are SQL bits.
[COLOR="Navy"]$sql3 = "[/COLOR][COLOR="Red"]SELECT whatever FROM table WHERE username='[/COLOR][COLOR="Navy"]".$_SESSION['username']."[/COLOR][COLOR="Red"]'[/COLOR][COLOR="Navy"]";[/COLOR]
[COLOR="Navy"]echo $sql3;[/COLOR]
Do your self a favor, and echo the $sql3 variable, and see what it looks like when its parsed.
On a quick side note… if you have a simple variable, you don’t need to jump in and out of the SQL string…
$username = $_SESSION['username'];
$sql3 = "SELECT whatever FROM table WHERE username='$username'";
echo $sql3;
The result will be the same as before. but perhaps its a little bit easier to read.
Its not recommended, and wastes resources by adding more vairables… but if it helps you to understand what happens, then its ok to do it a few times like that.