0

SQL newb here...

$db_result = mysql_query("SELECT first_name FROM gamers WHERE comp_id = 'myid'"); works the way I want.

$compid1 = 'myid';
$db_result = mysql_query("SELECT first_name FROM gamers WHERE comp_id = @compid1");

does not yield the same results.

I have also tried $compid1 and various other things, but without success.

Sorry for the simple question, but the answer is still eluding me. Thanks!

UPDATE: Oh yea...the question. How can I use a prestored variable for my WHERE check?

1
  • 1
    No it won't work, a MySQL variable (prefixed with @) isn't automagically linked with a PHP variable of the same name Commented Nov 8, 2014 at 20:22

2 Answers 2

2

You need to use $ before a variable, not @. And you need to put quotes around it since it's a string:

$db_result = mysql_query("SELECT first_name FROM gamers WHERE comp_id = '$compid1'");

However, it would be best if you stopped using the mysql extension. Use PDO or mysqli, and use prepared statements with parameters. E.g. in PDO it would be:

$stmt = $conn->prepare("SELECT first_name FROM gamers WHERE comp_id = :compid");
$stmt->bindParam(':compid', $compid1);
$stmt->execute();
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! if I run the PDO version, how would i grab $db_result?
You use $stmt->fetch() to get the results. It's all in the PDO documentation.
1

Enclose the string variable inside a pair of quotes.

$compid1 = 'myid';
$db_result = mysql_query("SELECT first_name FROM gamers WHERE comp_id = '$compid1'");

1 Comment

Thanks! I'd give you a green checkmark too if I had an extra, but Barmar beat ya to it.

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.