Selecting data where value is equal to a variable MySQL

1k views Asked by At

I'm trying to create a system that selects all the rows where username2 is equal to a variable, and don't understand why this wouldn't work. I'm fairly new to MySQL.

This does not work:

$sql = "SELECT username2, petbreed, petcost, pettype FROM pets WHERE username2 
= " + $first_name;

Neither does this:

$sql = "SELECT username2, petbreed, petcost, pettype FROM pets WHERE 
username2 = '" + $first_name + "'";

But this does:

$sql = "SELECT username2, petbreed, petcost, pettype FROM pets WHERE 
username2 = 'JohnDoe'";

Thank you for taking the time to read this.

2

There are 2 answers

0
Ognjen Stefanovic On BEST ANSWER

You can write it like this: $sql = "SELECT username2, petbreed, petcost, pettype FROM pets WHERE username2 = '$first_name'".

Use double quote around the whole expression and single quote around the variable.

+ is not concatenation sign in PHP. The dot . is.

0
man0v On

In PHP string concatenation happens through the "." (dot) operator - you cannot use "+" (plus) sign to concatenat strings.

If you replaces the pluses in your second example, you are good to go

$sql = "SELECT username2, petbreed, petcost, pettype FROM pets WHERE username2 = '".$first_name."'";

or even

$sql = "SELECT username2, petbreed, petcost, pettype FROM pets WHERE username2 = '$first_name'";

However, it's highly advisable to sanitize $first_name first(to avoid SQL injections)