Search code examples
phpmysqlispecial-charactersmysql-real-escape-string

Php mysqli gives no results


Basically my problem is that mysql in php in some cases returns an empty array with no error.

I am getting all products from table 'newproducts' where the name is the same as it was in the url that was called.

So when I call: http://domain.com:9090/db/product/3-Acetyl-5-bromopyridine

the query that is being called is (after url_decode):

SELECT * FROM `newproducts` WHERE `name` = '3-Acetyl-5-bromopyridine' LIMIT 1

which returns all products correctly.

But if I call: http://domain.com:9090/db/product/%5B3aa,4a%28E%29,5b,6aa%5D-4-%5B4-%283-Chlorophenoxy%29-3-oxo-1-butenyl%5Dhexahydro-5-hydroxy-2H-cyclopenta%5Bb%5Dfuran-2-one after I do urldecode the query is this (using var_dump in browser):

SELECT * FROM `newproducts` WHERE `name` = '[3aa,4a(E),5b,6aa]-4-[4-(3-Chlorophenoxy)-3-oxo-1-butenyl]hexahydro-5-hydroxy-2H-cyclopenta[b]furan-2-one' LIMIT 1

which returns NO results (empty array) with no error.

Also the above exact query in phpmyadmin correctly gives back the result.

Lastly, I have tried using the below lines before I run the query with no luck:

mysqli_set_charset($con, "utf8");
mysqli_real_escape_string($con, $name);

Thanks in advance!

the code of the query:

function getOneResFromDB($con, $text) {
    mysqli_set_charset($con, "utf8");
    mysqli_real_escape_string($con, $text);

    $query = "SELECT * FROM `newproducts` WHERE `name` = '" . $text . "' LIMIT 1";

    $result = mysqli_query($con, $query) or die(mysqli_error($con));

    $array = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $array[] = $row;
    }

    return $array;
}

Solution

  • I had to use html_entity_decode as well. The result seemed the same but it wasnt even with var_dump as some characters were automatically converted by the web browser. html_entity_decode solved it.