11

I'm trying to make the following code work but I can't reach the execute() line.

$mysqli = $this->ConnectLowPrivileges();
echo 'Connected<br>';
$stmt = $mysqli->prepare("SELECT `name`, `lastname` FROM `tblStudents` WHERE `idStudent`=?");
echo 'Prepared and binding parameters<br>';
$stmt->bind_param('i', 2 );
echo 'Ready to execute<br>'
if ($stmt->execute()){
    echo 'Executing..';
    }
} else {
    echo 'Error executing!';
}
mysqli_close($mysqli);

The output that I get is:

Connected
Prepared and binding parameters

So the problem should be at line 5, but checking the manual of bind_param() I can't find any syntax error there.

Lucio
  • 4,753
  • 3
  • 48
  • 77
  • 3
    Why not echo the error received to help debug it? I think echoing `$stmt->error` will get you the exact error mysql is complaining about. – Todd Apr 01 '13 at 17:33
  • I updated my question, because now I can't even run the following line after `bind_param()`! @Todd That is useful, important to have in mind. – Lucio Apr 01 '13 at 17:40

3 Answers3

13

When binding parameters you need to pass a variable that is used as a reference:

$var = 1;

$stmt->bind_param('i', $var);

See the manual: http://php.net/manual/en/mysqli-stmt.bind-param.php

Note that $var doesn't actually have to be defined to bind it. The following is perfectly valid:

$stmt->bind_param('i', $var);

foreach ($array as $element)
{

    $var = $element['foo'];

    $stmt->execute();

}
Michael
  • 11,912
  • 6
  • 49
  • 64
0

here it is just a simple explaination
declare a variable to be bind

    $var="email";
$mysqli = $this->ConnectLowPrivileges();
echo 'Connected<br>';

$var="email";
$stmt = $mysqli->prepare("SELECT name, lastname FROM tablename WHERE idStudent=?" LIMIT=1);
echo 'Prepared and binding parameters<br>';
$stmt->bindparam(1,$var); 
Pokechu22
  • 4,984
  • 9
  • 37
  • 62
x00
  • 11
-7

Your actual problem is not at line 5 but rather at line 1.
You are trying to use unusable driver.
While PDO does exactly what you want.

$sql = "SELECT `name`, `lastname` FROM `tblStudents` WHERE `idStudent`=?"
$stm = $this->pdo->prepare($sql);
$stm->execute(array(2));
return $stm->fetch();

After all the years passed since this answer has been written, a new PHP feature emerged, called "argument unpacking". So, since version 5.6 you can pass a value into bind_param:

$stmt->bind_param('i', ...[2]);

But still you have a trouble with getting your data back out of a prepared statement :)

Community
  • 1
  • 1
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345