0

I have been trying to get this for hours, and I know there are other topics similar to this but I'm still stuck... basically I'm trying to list all the customers with last names that start with the letter A:

I'm passing a variable called lname in the URL like this:

Then I grab the variable in the PHP like:

$lname = $_GET['lname'];
$lname = mysql_real_escape_string($lname);

// HERE'S THE PROBLEM AREA:  then I try to put a simple query together like this:

$query = 'SELECT * FROM customers WHERE customers.lname LIKE "$lname%"';

// then I want to make sure $query and $lname have values in them, so I echo them out:

echo $query;
echo ' $lname = '.$lname;

// and the output is:

SELECT * FROM customers WHERE customers.lname LIKE "$lname%" 
$lname = A
Unknown column '$lname' in 'where clause'

So you can see that in the query, after the LIKE, it should say LIKE 'A', but it is parsing to LIKE $lname. I've tried all kinds of variations such as:

$query = 'SELECT * FROM customers WHERE customers.lname LIKE ".$lname."'; $query = 'SELECT * FROM customers WHERE customers.lname LIKE {$lname}%'; etc, etc, etc

Strange, but the column lname is DEFINITELY there in the customers table, and so I'mk not sure why it's reporting that error of 'Unknown column '$lname' in 'where clause''

And for the record, when I manually just change the query to include the value I want, it outputs the list of customer names perfectly:

$query = 'SELECT * FROM customers WHERE customers.lname LIKE "A%"';

... so the query works, but I can't get the $lname to be interpolated.

THANK YOU for any help. How can I get that variable $lname to pass the VALUE that's inside of $lname in my mysql query?

2

2 Answers 2

1

$query = "SELECT * FROM customers WHERE customers.lname LIKE '$lname%'";

Interchange your single quotes and double quotes in the above line.

Sign up to request clarification or add additional context in comments.

1 Comment

THANKS man!! Gosh I tried so many variations. It works! I didn't know interchanging the quotes would have that effect but THANKS!! Peace!
1

You should really think about using parameterized queries. For instance,

$sql = "SELECT * FROM customers WHERE customers.lname LIKE ?";
$stm = $pdo->prepare($sql);
$stm->execute(array($lname));

This would help with many problems you are likely experiencing, and is much more secure.

1 Comment

Brian thank you! Great point there. I am, as you can prob tell, a novice coder, so I need to get up to speed on those security methods. Thank you for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.