Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pdo in php with stored procedure

I have a simple stored procedure in MySQL database:

DELIMITER $$
CREATE DEFINER=`vidhu`@`%` PROCEDURE `test`(var_datain TEXT)
BEGIN
    SELECT var_datain;
END

When calling this procedure in mysql-workbench it returns the data I put in:

Screenshot form mysql work bench

Now when I call it from PHP using pdo I get an error:

Fatal error: Cannot pass parameter 2 by reference in C:/apache......(3rd line)

Here is my php code:

$db = new PDO(DSN, DBUSER, DBPASS);
$stmt = $db->prepare("CALL test(?)");
$stmt->bindParam(1, 'hai!', PDO::PARAM_STR);
$rs = $stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $result[0];
like image 721
Krimson Avatar asked Aug 07 '12 00:08

Krimson


People also ask

Can I use stored procedure in PHP?

To call a stored procedure from a PHP application, you prepare and execute an SQL CALL statement. The procedure that you call can include input parameters (IN), output parameters (OUT), and input and output parameters (INOUT).

Is PHP PDO deprecated?

PDO (PHP Data Objects) Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.

How does PDO work in PHP?

The PDO represents a connection between PHP and a database server. The PDOStatement represents a prepared statement and, after the statement is executed, an associated result set. The PDOException represents an error raised by PDO.


1 Answers

You need to use bindValue instead of bindParam.

When you use bindParam, it binds the variable provided to the parameter, not the value of the variable.

So, if you do:

$x = 5;
$stmt->bindParam(1, $x, PDO::PARAM_INT);
$x = 6;
$stmt->execute(); //executes with 6 instead of 5

It's actually executed with 6 rather than 5. To do this, the method must have a reference to the variable. You cannot have a reference to a literal, so this means that bindParam cannot be used with literals (or anything you can't have a reference to).

$x = 5;
$stmt->bindValue(1, $x, PDO::PARAM_INT);
$x = 6;
$stmt->execute(); //executes with 5 instead of 6

Then:

$stmt->bindParam(1, 1, PDO::PARAM_INT); 
//invalid because there's no way to pass a literal 1 by reference
$stmt->bindValue(1, 1, PDO::PARAM_INT);
//valid
like image 115
Corbin Avatar answered Oct 20 '22 12:10

Corbin