user1253538
user1253538

Reputation:

Doing an SQL query in PHP that depends on a variable

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?

Upvotes: 1

Views: 184

Answers (3)

Lèse majesté
Lèse majesté

Reputation: 8045

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();
?>

Upvotes: 5

Fidi
Fidi

Reputation: 5834

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']) . "'");

Upvotes: 7

Sarfraz
Sarfraz

Reputation: 382696

You are missing quotes:

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

Upvotes: 5

Related Questions