1

I´m trying to do the following query in PHP

            $sqlstr = mysql_query("SELECT * FROM sales where passport = $row['passport']");
            if (mysql_numrows($sqlstr) != 0) {
            while ($row = mysql_fetch_array($sqlstr)) {
            echo $row['firstname']; 
            }}

How can I incorporate the value of $row['passport'] into my query?

1
  • It looks like you have?! What's the printed output of your SQL query? Commented Jul 6, 2010 at 8:16

3 Answers 3

7

First of all you forgot the single-quotes. sAc corrected this already in his answer. But I would consider to also use an escaping function due to security-issues:

$sqlstr = mysql_query("
SELECT
    *
FROM
    sales
WHERE
    passport = '" . mysql_real_escape_string($row['passport']) . "'");
Sign up to request clarification or add additional context in comments.

1 Comment

It's not only for security reasons: you don't want data corruption or program crashing.
5

You are missing quotes:

$sqlstr = mysql_query("SELECT * FROM sales where passport = '{$row['passport']}'");

Comments

5

I would avoid manually escaping/sanitizing your variables and just use prepared statements. This was something I didn't learn until much later in my web development career, and I wish I'd known about it sooner. It will save you a lot of trouble and is just safer all around.

You can use the mysqli_stmt class to perform MySQL queries using prepared statements, or you could use the PHP Data Objects (PDO) extension, which works with MySQL, PostgreSQL and other RDBMSes.

Just to show you what it looks like, here's the first example from the PDOStatement->bindParam doc page:

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Comments

Your Answer

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