0

This has annoyed me for a while now. I am trying this query in phpmyadmin.

select `id` from `users` where `fb_id` = 507292797 limit 1

This returns the value 13, so why doesn't this work:

                $sql =  "select `id` from `users` " .
                        "where `fb_id` = :fb_id " .
                        "limit 1";
                try 
                {
                    $stmt = $this->db->prepare($sql); 
                    $stmt->bindParam(':fb_id', $fb_id2, PDO::PARAM_INT);

                    $user = $stmt->fetch(PDO::FETCH_ASSOC); 
                    $result = $stmt->execute();

                    $stmt->closeCursor(); 
                }       
                catch (Exception $e)
                {
                die ($e->getMessage() ); 
                }

                echo "id: " . $fb_id2 . " var_dump: " . var_dump($user); 
                exit(); 

This returns:

id: 507292797 var_dump: bool(false)

When var_dump should return $user['id'] = 13

Can somebody see what I am doing wrong here?

ps. here is my db connection function if that matter

        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
        $driver_options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8' );

        try
        {
            $this->db = new PDO($dsn, DB_USER, DB_PASS, $driver_options);

2 Answers 2

5

You are doing things in this order :

  • Preparing the statement
  • Binding the variables
  • Trying to fetch data from the statement
  • Executing the statement

The two last steps should be in the inverse order : you must execute the statement before you can fetch data (that's obtained by executing it).


Basically, instead of using this :

// fetch, then execute ???
$user = $stmt->fetch(PDO::FETCH_ASSOC); 
$result = $stmt->execute();

You should use that :

// Execute, **then** fetch
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC); 
Sign up to request clarification or add additional context in comments.

Comments

1

Looks like you are fetching before executing?

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.