Query works in phpmyadmin but not in PHP script

2019-03-01 13:51发布

问题:

I found similar questions but can't solve my problem yet. Here is the relevant code:

$query = "SELECT * FROM conceptos WHERE descripcion = '$descripcion'";
if ($result = mysql_query($query,$connection)){
    if (mysql_num_rows($result) > 0){
        //Do something
    } else {
        die($query);
        exit;
    }
} else {
    die(mysql_errno() . ' - ' . mysql_error());
    exit;
}

I don't have problems with the connection or the permissions, because this code snippet is inside a loop and the other queries enter the "Do something" section. But when I take the echoed query and execute it in phpMyAdmin, it returns 1 value as expected. Why? What reasons can lead to this behavior? Thanks in advance for any advice.

回答1:

I had this problem and found that it was because I junked up my database by copy/pasting directly to the database from MS Word. Pasting had inserted special slanted apostrophes that PHPMYADMIN could apparently parse but my php code could not. Once I replaced those with a standard single quote, all was well.



回答2:

Try this "SELECT * FROM conceptos". If it's worked, you have bad query in "WHERE ..."



回答3:

Are you sure your query is searching for the right description? The double quotes should expand all internal variables, but you do have single quotes as well in case there is a copying to stackoverflow issue.

This will ensure that the description is expanded in case.

$query = "SELECT * FROM conceptos WHERE descripcion = '" . $descripcion . "'";

Secondly, have you validated the variable contents you are using, as suggested by @crotos?

The mysql_ are also deprecated, so you should use PDO, or at the least, mysqli_.



回答4:

You can try to setup the general query log of your mysql server and see what queries are really executed. See http://dev.mysql.com/doc/refman/5.1/en/query-log.html

Also, check your encodings. Maybe your mysql connection is in ISO8859-1 and your table fields are in UTF-8 (or the opposite). Do you have any accents or special characters in your data?



回答5:

i also faced this problem and got it solved using:

mysqli_query($con,$query);

instead of

mysql_query($query);

coz its depreciated

source:

File Downloading error from database php