我的php查询的任何问题


Any problems of my php query?

下面是我的代码。

<?php
$a = bacon;
$b = 20;
$c = 30;
$link = mysql_connect('localhost','root',''); 
mysql_select_db("test", $link);
$sql = "UPDATE share SET price=".
         PrepSQL($b) . ", place=" .
         PrepSQL($c) . ", time=CURRENT_TIMESTAMP where num=1 and RID=(select IID from ingredient where Ingredient='" . PrepSQL($a) . "')";
mysql_query($sql);
function PrepSQL($value)
{
    // Stripslashes
    if(get_magic_quotes_gpc())
    {
        $value = stripslashes($value);
    }
    // Quote
    $value = "'" . mysql_real_escape_string($value) . "'";
    return($value);
}
?>

我发现上面的代码不能更新DB表。但是,如果我把where条件改成where num=1 and RID=(select IID from ingredient where ingredient ='bacon')"然后,一切都很好。那么,我的代码有什么问题吗?非常感谢!

您的子查询

"[...] (select IID from ingredient where Ingredient='" . PrepSQL($a) . "')"

应该是

"[...] (select IID from ingredient where Ingredient=" . PrepSQL($a) . ")"

因为对PrepSQL的调用已经为您添加了单引号。

另外,请避免使用mysql_* php函数,因为它们现在已被弃用!更多选项请参见:http://www.php.net/manual/en/mysqlinfo.api.choosing.php

编辑:

还有,你可能有一个未定义的bacon常数,应该是"bacon"

如果它应该是一个字符串,那么它需要用引号括起来。

$a = 'bacon';

你应该使用:

<?php
$a = "bacon";
$b = 20;
$c = 30;
$link = mysql_connect('localhost','root',''); 
mysql_select_db("test", $link);
$sql = "UPDATE share SET price=".
         PrepSQL($b) . ", place=" .
         PrepSQL($c) . ", time=CURRENT_TIMESTAMP where num=1 and RID=(select IID from ingredient where Ingredient='" . PrepSQL($a) . "')";
mysql_query($sql);
function PrepSQL($value)
{
    // Stripslashes
    if(get_magic_quotes_gpc())
    {
        $value = stripslashes($value);
    }
    // Quote
    $value = "'" . mysql_real_escape_string($value) . "'";
    return($value);
}
?>