Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO bindParam() with prepared statement isn't working

Tags:

php

mysql

pdo

Ok, this is the problem:

This works:

$STH = $DBH->prepare("SELECT * FROM juegos WHERE id = 1");
$STH->execute();

This doesn't:

$STH = $DBH->prepare("SELECT * FROM juegos WHERE id = :id");
$STH->bindParam(':id', '1', PDO::PARAM_STR);
$STH->execute();

What in the world am I doing wrong? It doesn't even throw an exception

Thank you everyone!

Also, this is the whole code

<?php
    try {
        $DBH = new PDO("everything is", "ok", "here");

        $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

        $STH = $DBH->prepare("SELECT * FROM juegos WHERE id = :id");
        $STH->bindParam(':id', '1', PDO::PARAM_STR);
        $STH->execute();

        $STH->setFetchMode(PDO::FETCH_ASSOC);

        while($row = $STH->fetch()) {
            echo $row['nombre']."<br/>";
        }

        $DBH = null;

        echo "Todo salió bien";

    } catch (PDOException $e) {
        echo "Error";
    }

?>
like image 744
arielnmz Avatar asked Nov 11 '13 08:11

arielnmz


People also ask

How does PDO prepared statements work?

In layman's terms, PDO prepared statements work like this: Prepare an SQL query with empty values as placeholders with either a question mark or a variable name with a colon preceding it for each value. Bind values or variables to the placeholders. Execute query simultaneously.

What is the difference between bindParam and bindValue?

bindParam is a PHP inbuilt function used to bind a parameter to the specified variable name in a sql statement for access the database record. bindValue, on the other hand, is again a PHP inbuilt function used to bind the value of parameter to the specified variable name in sql statement.

What is PDO :: PARAM_STR in PHP?

PDO::PARAM_STR. Represents SQL character data types. For an INOUT parameter, use the bitwise OR operator to append PDO::PARAM_INPUT_OUTPUT to the type of data being bound. Set the fourth parameter, length , to the maximum expected length of the output value.

What is a prepared statement in PHP?

The prepared statement is a special function embedded in PHP which allows programmers to write codes that can be executed multiple times in an efficient manner by our database. When communicating with your database, extra care is given to security, query time, and server request size.


1 Answers

Using bindParam() the variable is bound as a reference.

A string can't be passed by reference.

The following things can be passed by reference:

Variables, i.e. foo($a)

New statements, i.e. foo(new foobar())

References returned from functions

Try using bindValue()

$STH->bindValue(':id', '1', PDO::PARAM_STR);
like image 98
david strachan Avatar answered Oct 22 '22 02:10

david strachan