简体   繁体   中英

What's wrong with my SQL query?

I have a bunch of database calls in my code.

One of them is like this:

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

All of the other database calls works perfectly, but this one simply doesn't write any data onto the table. What's wrong with it?

Check the return from mysql query.

$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());
}

If there is something wrong with the query it will tell you what it was.

mysql_query() returns true on success and false on error for queries that don't return something.

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

When using mysql_query() in production, you should check the return value, and exit gracefully on error, and preferably log it so that it can help you fix any issues.

Also when performing a query that uses user input ensure you use mysql_real_escape_string() to avoid SQL injection, and will protect input that contains a single quote, which would break your current query.

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

Check the return value from the query to find out what is happening -

$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() );
}

You can just write this as 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());

If you don't get an error it means it succeeded. If you get an error, you'll an error straight from mySQL (so it should be pretty detailed).

Another way to locate your problem: logging your sql query, to see what the query looks like at run-time.

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

echo $str;

Then try that query to your database directly, you will get the things that doesn't right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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