0

I'm trying to insert values using prepared statements like this:

$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user_table (first_name, last_name) VALUES (:tname, :tname2)";
$stmt = $dbh->prepare($sql);
$stmt -> bindParam(':tname', 'John');
$stmt -> bindParam(':tname2', 'Smith');
$stmt -> execute();

However, this is throwing a fatal error: "PHP Fatal error: Cannot pass parameter 2 by reference in /Applications/MAMP/htdocs/live/test_create.php on line 53" This is referring to this line: $stmt -> bindParam(':tname', 'John');

What's causing this problem?

jonmrich
  • 4,233
  • 5
  • 42
  • 94
  • Is that space meant to be there? Or is that formatting error? – Script47 Aug 06 '15 at 01:43
  • @Script47 Which space? – jonmrich Aug 06 '15 at 01:44
  • `$stmt -> bindParam(':tname', 'John'); $stmt -> bindParam(':tname2', 'Smith'); $stmt -> execute()` I see that, a bunch of spaces after the `$stmt` variable. – Script47 Aug 06 '15 at 01:45
  • @Script47 Sorry, still not sure which spaces you're talking about. Before `'John'` or somewhere else? I tried the code above as you have it and that yielded the same error. – jonmrich Aug 06 '15 at 01:47
  • Check my answer. Oh and this image wll show you what I mean about the spaces. http://i.imgur.com/bcm4uMk.png – Script47 Aug 06 '15 at 01:48

1 Answers1

2

When using bindParam it must be passed by reference.

Use bindValue instead, for the way you are trying to use it here.

More about bindValue vs bindParam here

If you are insistent about using bindParam, it must be supplied as a variable. So you would use $var1="John" and then $stmt->bindParam(':tname',$var1);

Community
  • 1
  • 1
Just Lucky Really
  • 1,341
  • 1
  • 15
  • 38
  • 1
    I just learn't something new. – Script47 Aug 06 '15 at 01:57
  • I actually am planning to use variables like `$thisthing`, but was doing the other as a test to make it simpler (which didn't work). Your solution was just what I needed. Thanks for the extra information about `bindParam` and `bindValue`. – jonmrich Aug 06 '15 at 01:58
  • No worries ... Take a read on that link though, as it shows that if you use `bindParam` you can actually change the value of the variable (after the bind, but before the execute), without it effecting the executed query. – Just Lucky Really Aug 06 '15 at 02:01