开发者

"Warning: PDO::prepare() expects parameter 2 to be array, string given" - when only one argument was specified

开发者 https://www.devze.com 2023-03-05 06:34 出处:网络
I\'m not very experienced with PDO and MySQL query.. Look at this function: function add($mynick, $friend) {

I'm not very experienced with PDO and MySQL query..

Look at this function:

function add($mynick, $friend) {
   $dbh = new PDO(DSN,USERNAME,PASSWORD);
   $sth = $dbh->prepare('UPDATE pinfo SET friends=concat_ws(',' , f开发者_运维知识库riends, $friend)  WHERE nick = :mynick');
   $sth->bindParam(':mynick', $mynick);
   //$sth->bindParam(':friend', $friend);
   $sth->execute(); 
}

This function is not working:

Warning: PDO::prepare() expects parameter 2 to be array, string given in /test5.php 
Fatal error: Call to a member function bindParam() on a non-object in /test5.php

I tried to blind also $fliend var, in the concat_ws, or removing all $var and bindParam; the db connection and the db table are ok.

Why is it wrong ?

If I try to use PDO with a simple UPDATE query, without concat_ws it works.


$sth = $dbh->prepare('
     UPDATE pinfo 
        SET friends=concat_ws(',' , friends, $friend) 
      WHERE nick = :mynick
');

I've reformatted your query to hopefully make the error more obvious.

Don't see it?

Check out the syntax highlighting provided by SO. See how the comma in the SET is black?

The problem is that you're enclosing your SQL statement in single-quotes, but want to use single-quotes inside the query. What's really happening is that you're breaking out of the quoted argument, passing PHP a comma, then opening the quote up again, resulting in two arguments passed to prepare: 'UPDATE pinfo SET friends=concat_ws(' and then ' , friends, $friend) WHERE nick = :mynick'. This is why PHP is whining about the second argument being invalid. You need to either escape the single quotes, or use double quotes to wrap the query.

Therefore you need to:

  1. Use double quotes here, to avoid escaping (backslashes can get overwhelmingly ugly), and
  2. Bind $friend properly rather than let PHP interpolate it, as noted by @Ian Wood, and as your commented out code originally suggested

Thus:

$sth = $dbh->prepare("UPDATE pinfo SET friends=concat_ws(',' , friends, :friend)  WHERE nick = :mynick");
$sth->bindParam(':mynick', $mynick);
$sth->bindParam(':friend', $friend);
$sth->execute(); 


concat_ws(',' , friends, $friend)

think thast should be

concat_ws(',' , friends, :friend)

I would however consider changing your architecture.

Just have a table of people and then a table of friends... Keep the persons details in the people table and in the friends table have two columns 'person_id' and 'friend_id' just store the ids of the connected people - you will end up with much more useful and manageable data.

as many people can have many friends you need a 'many-to-many' relationship there...

0

精彩评论

暂无评论...
验证码 换一张
取 消