0

I'm trying to create a login page using php and sql. This is my php code that gets the username and password data from mysql and checks if they are right so the user gets logged in. I'm getting this error:

Call to a member function fetch() on a non-object

on the line:

$row = $result->fetch(PDO::FETCH_ASSOC);

Here is my code:

<?php session_start();

$db = new PDO("mysql:host=localhost;dbname=database","user","pass");
  if(mysqli_connect_errno())
  {
    echo "fail!". mysqli_connect_errnor();
  }

$first =$_POST['username'];
$last=$_POST['password'];

$sql="SELECT count(user_id) as records FROM table WHERE username='$first' AND password='$last'";
$result = $db->query($sql);
$row = $result->fetch(PDO::FETCH_ASSOC);
if ($row['records'] == 1);
{
    $_SESSION['loggedIN'] =true;
    header("Location:logged.php");
    die();

}
else {

    $_SESSION['loggedIN'] = null;
    header("Location:home.php");
    die();

}


?>
5
  • 3
    table is a reserved word,are you sure your table name is table?Use backticks if so `table`.Also google prepared statements. Commented Jan 14, 2014 at 15:39
  • 4
    So you're attempting to use PDO, but you're still placing $_POST data directly into the query? Nice... Commented Jan 14, 2014 at 15:39
  • You can't just assume your query worked, you need to check for errors before fetch()ing. if($result === FALSE){ var_dump($db->errorInfo()); die; }. P.S. PDO doesn't magically make your queries injection-free, you need to be using prepared statements. P.P.S. mysqli_connect_errno won't help you here. You're using PDO not MySQLi. Commented Jan 14, 2014 at 15:41
  • 2
    Apart from the sql injection problem and the table name, you are using PDO but checking for mysqli errors... Commented Jan 14, 2014 at 15:41
  • 1
    And a plain-text password... Commented Jan 14, 2014 at 15:42

1 Answer 1

1

try it with

$db = new PDO("mysql:host=localhost;dbname=database","user","pass");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

makes it harder to miss errors that might occur.
And then as - Stanyer pointed out - don't put the parameters directly into your query but pass them as ..parameters.

$stmt = $db->prepare('SELECT count(user_id) as records FROM `table` WHERE username=? AND password=?');
$stmt->execute( array($_POST['username'], $_POST['password']) );
$row = $result->fetch(PDO::FETCH_ASSOC);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.