繁体   English   中英

我的SQL查询有什么问题?

[英]What's wrong with my SQL query?

我的代码中有一堆数据库调用。

其中之一是这样的:

mysql_query("INSERT INTO coupons (id, retailerName, description, savingsDetails, pictureURL, rating, qrPicture, zipCode, dateAdded, dateExp) VALUES ('$newID', '$retailerName', '$description', '$savingsDetails', '$pictureURL', '0', '$qrPicture', '$zipCode', '$dateAdded', '$dateExp')");

所有其他数据库调用都可以正常运行,但是该数据库调用不会将任何数据写入表中。 它出什么问题了?

检查从mysql查询返回的信息。

$result = mysql_query($query);
if ($result === false) {
    // Prints the query and the mysql error to help you find the problem.
    die($query.'<br/>'.mysql_error());
}

如果查询有问题,它将告诉您它是什么。

对于不返回内容的查询, mysql_query()成功返回true,错误返回false。

http://php.net/manual/en/function.mysql-query.php

在生产环境中使用mysql_query()时,应检查返回值,并在错误时正常退出,最好将其记录下来,以便它可以帮助您解决任何问题。

同样,在执行使用用户输入的查询时,请确保使用mysql_real_escape_string()避免SQL注入,并且将保护包含单引号的输入,这会破坏当前查询。

http://php.net/manual/en/function.mysql-real-escape-string.php

检查查询的返回值以了解发生了什么-

$result = mysql_query("INSERT INTO coupons (id, retailerName, description, 
                savingsDetails, pictureURL, rating, qrPicture, zipCode, dateAdded, 
                dateExp) VALUES ('$newID', '$retailerName', '$description', 
                '$savingsDetails', '$pictureURL', '0', '$qrPicture', '$zipCode', 
                 '$dateAdded', '$dateExp')");

if($result)
{
    // Your query succeeded
}
else
{
    // Your query failed due to some error
    die( mysql_error() );
}

您可以将其写为mysql_query("INSERT INTO coupons (id, retailerName, description, savingsDetails, pictureURL, rating, qrPicture, zipCode, dateAdded, dateExp) VALUES ('$newID', '$retailerName', '$description', '$savingsDetails', '$pictureURL', '0', '$qrPicture', '$zipCode', '$dateAdded', '$dateExp')") or die(mysql_error());

如果没有收到错误,则表示成功。 如果收到错误,则直接来自mySQL的错误(因此应该非常详细)。

查找问题的另一种方法:记录sql查询,以查看查询在运行时的外观。

$str = "INSERT INTO coupons ...";

echo $str;

然后将查询直接尝试到您的数据库,您将得到不正确的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM