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?

5
  • Is that space meant to be there? Or is that formatting error? Commented Aug 6, 2015 at 1:43
  • @Script47 Which space? Commented Aug 6, 2015 at 1:44
  • $stmt -> bindParam(':tname', 'John'); $stmt -> bindParam(':tname2', 'Smith'); $stmt -> execute() I see that, a bunch of spaces after the $stmt variable. Commented Aug 6, 2015 at 1: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. Commented Aug 6, 2015 at 1:47
  • Check my answer. Oh and this image wll show you what I mean about the spaces. i.imgur.com/bcm4uMk.png Commented Aug 6, 2015 at 1:48

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

3 Comments

I just learn't something new.
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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.