Prepared PDO query returns 0 affected rows

151 Views Asked by At

I've literally spent hours Googling and searching and I have no idea what I'm doing wrong. I'm using POST, and I tried the query myself in phpMyAdmin, and it worked, but it's not working in PDO, and I don't know why. It worked when I used mysql_query and what not, but I want to protect myself from SQL injection.

Here's the code I'm using:

<?php
    if(isset($_POST['user']) and isset($_POST['pass'])) {
        $name = $_POST['user'];
        $pass = $_POST['pass'];

        $db = new PDO('mysql:host=localhost;dbname=*****;charset=utf8', '*****', '*****');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $query = $db->prepare("SELECT * FROM stored WHERE _User LIKE :username AND _Pass LIKE :password");
        $query->bindValue(":username", $user, PDO::PARAM_STR);
        $query->bindValue(":password", $pass, PDO::PARAM_STR);

        $query->execute();

        echo $query->rowCount();
    }
?>
2

There are 2 best solutions below

3
On

Either you are using ancient version of PHP, or there are no rows in your database matching the criteria. Upgrade for the first and check your data and query for the second.

Also, as Holy Linus spake to us, "Talk Is Cheap, Show Me The Code".
Don't tell us "It worked when I used blah blah query". Run it. In the very same file, next to very this code. This way you will have a proof. Only such a proof matters, while your speculations aren't.

However, strictly speaking, you don't need this function at all, as well as most of your code

$stmt = $db->prepare("SELECT 1 FROM stored WHERE _User = ? AND _Pass = ?");
$stmt->execute(array($_POST['user'],$_POST['pass']));
echo $stmt->fetchColumn();

is enough.

2
On

It looks like you're naming the username variable $name in row 41, but when you bind the parameter on row 46, you call it $user.