0

I could not retrieve information from mysql database. I got an error saying

Array\n(\n [0] => 42000\n [1] => 1064\n [2] => on the client side

However, when I replace the variable $city with regular string like "san francisco" it works fine. I even tested that whether $city is a string and it is a string

$sth just failed to execute even though the query was successful

 <?php

    if (isset($_GET)) {

        $servername = "localhost";
        $username = "XXXXX";
        $password = "XXXXX";
        $dbname = "CALIFORNIA";
        $city = $_GET['userinput'] . "";


        // Create connection
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
        $sql = "SELECT State FROM  CITY WHERE City_name = $city";   // When I replace the $city with string like "San Francisco", it works but not with variable $city

        if (($sth = $conn->prepare($sql))) {
            if ($sth->execute()) {            // $sth failed even though the query was successful 
                $result = $sth->fetchAll();
                $json = json_encode($result);
                echo $json;
            }
            else
                echo print_r($sth->errorInfo()); // Error print out on client side

        }
        else
            echo  $conn->errorCode();

        }
tuyenle
  • 79
  • 8
  • 1
    `"San Francisco"` is quoted, `$city` is not. You also are using prepared statements incorrectly (opens you to SQL injections and is the cause of your breakage). Try `SELECT State FROM CITY WHERE City_name = ?` as the query then `$sth->execute(array($city))`. This is using placeholders and allowing the driver to bind. – chris85 Oct 25 '16 at 02:37
  • 1
    I can get behind that close dupe target @chris85 , it certainly is where the solution would reside for peer review. Never use user-supplied data like that. – Drew Oct 25 '16 at 02:41
  • sorry for duplication. It works now – tuyenle Oct 25 '16 at 03:00

0 Answers0