开发者

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?


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


You are missing quotes:

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜