my pdo connection doesn't work

2019-08-11 04:10发布

Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.

For that I want to replace my old code with the new:

Here is the old

$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
            die('Error: ' . mysql_error());

    mysql_select_db("bookshop");

    $SQL = "select * from productcomment where ProductId='" . $input . "'";
    $result = mysql_query($SQL) or die('Error: ' . mysql_error());

    $row = mysql_fetch_array($result);
    if ($row['ProductId']) {
        echo "Product:" . $row['ProductId'] . "<br>";
        echo "Annotation:" . $row['Comment'] . "<br>";
        echo "TestOK!<br>";
    } else
        echo "No Record!";

    mysql_free_result($result);
    mysql_close();

And here is the new:

$input = $_GET['input'];

if ($input) {
    $user= 'sec';
      $pass = 'dubbelgeheim';
    try {
        $dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
    $escaper = $db->real_escape_string($input);
    $statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
    $statement->bind_param("s", $escaper);
    $statement->execute();
    $result = $statement->get_result();
    $statement->close();
    $count = $result->num_rows;
    if ($count > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "Product:" . $row['ProductId'] . "<br>";
            echo "Annotation:" . $row['Comment'] . "<br>";
            echo "TestOK!<br>";
        }
    } 
    else {
        echo 'No record!';
    }
    $result->free();
    $db->close();
}

When I tried this new code.. It gives the following error:

Error!: SQLSTATE[HY000] [1045] Access denied for user 'sec'@'localhost' (using password: YES)

I also tried to replace localhost with 127.0.0.1.

My goal is to make my page secure for SQL-injection.

May anyone have a great solution!

1条回答
别忘想泡老子
2楼-- · 2019-08-11 04:52

The code looks ok at first glance. Try this solution. It looks like this anonymus user might be the problem.

EDIT: (as suggedted in comments)

In summary: The recommended solution is to drop this anonymous user. By executing

DROP USER ''@'localhost';
查看更多
登录 后发表回答