I think its something obvious but I can't see it. Not really worked with PDO before so its a little bit of a step up from the old style queries but here's my code: $sth = $dbconn->prepare("SELECT id, username, useremail FROM users WHERE username = '$_POST[username]'"); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); if ($username != '$result[username]' || $useremail != '$result[useremail]'){ print ("Usernames/Password is the same"); // Do stuff }else { print ("User is new!"); //Do stuff } PHP: The user is always new...
Solved: $sth = $dbconn->prepare("SELECT * FROM users WHERE username = :username AND password = :password"); $params = array("username" => $_POST["username"], "password" => $encryptedpassword); $sth->execute($params); while ($row = $sth->fetch()) { //do stuff } PHP:
imho dont use prepare/execute use just query instead $sth = $dhconn->query('SELECT * FROM users WHERE username = "'.$_POST['username'].'" AND password = "'.$encryptedpassword.'"'); while ($row = $sth->fetch(PDO::FETCH_ASSOC,PDO::FETCH_ORI_NEXT)) { //do stuff } PHP: it is much shorter
You shouldn't do it like that, espacially don't put POST parameters directly into a query. A hacker will need a minutes to hack your website like that. You might want to look into "sql injection" on google
but prepare doesnt protect u against sql injection using "'.$_POST['foo'].'" is better however far from being perfect. I usually embed $_POST/$_GET into custom function that checks data or just add (int) for numbers.
bullocks... prepare function is being used to make the input save to use for the database read the manual http://www.php.net/manual/en/pdo.prepare.php
Just to update the code for this thread: $sth = $dbconn->prepare("SELECT * FROM users WHERE username = :username AND password = :password"); $params = array("username" => $_POST["username"], "password" => $encryptedpassword); $sth->execute($params); while ($row = $sth->fetch()) { if ($row[active] == 1){ // user is active proceed to account session_start(); $_SESSION['userName'] ="$row[username]"; header("Location:/account/"); } else { // user is inactive show error } PHP: As pointed out earlier, posting the variables directly into the query is dangerous. There's various other methods to bind them such as the example above as PDO only protects against injections if the parameters are binded.
please read a little more that this one manual page. How about PDO::ATTR_EMULATE_PREPARES ?? in order to prevent sql injection you would need to use not only prepare but also set PDO::ATTR_EMULATE_PREPARES to false and/or use bindParam, bindValue Simple prepare and then execute is NOT preventing You against sql injection. If You dont belive please do reaserch and see Yourself.