PDO PHP bindValue doesn't work

后端 未结 4 408
小鲜肉
小鲜肉 2021-01-12 16:09

I know this has been asked 1000 times, but for some reason I continue to bang my head agains the wall..

This works:

$sql = \'SELECT a.eventCode, a.ev         


        
4条回答
  •  感情败类
    2021-01-12 16:32

    As others have state you can only bind a single scalar value to a placeholder. So this means you actually need a placeholder for each value in your IN statement. I normally do something like the following. It should be noted though that i never use bindValue so if it has rules about things having to be references like Mysqli then the below may need to be modified:

    $regGUIDPlaceholders = array();
    
    // prepare the placeholders
    // assume regGUID is an array - if its a string then explode on whatever to make it an array
    foreach($regGUID as $k => $v) {
       $placeholder = ':regGUID' . $k;
       $regGUIDPlaceholders[$key] = $value;
    }
    
    // prepare the IN statememnt
    $in = sprintf('IN (%s)', implode(',', array_keys($regGUIDPlaceholders)));
    
    $sql = 'SELECT a.eventCode, a.eventTime, a.teamCode, a.playerCode, b.lastName, b.firstName, b.number, a.xCoord, a.yCoord, a.id ';
    $sql = $sql . 'FROM events a, players b ';
    
    // USE the IN statement dynamically prepared above
    $sql = $sql . 'WHERE a.regGUID '. $in . ' and ';
    
    $sql = $sql . 'a.playerCode=b.playerCode and a.gameCode = :game order by a.eventTime desc, a.actionCode asc'; 
    
    $stmt = $db->prepare($sql);
    
    // bind each GUID to its placeholder
    foreach($regGUIDPlaceholders as $placeholder => $value) {
       $stmt->bindValue($placeholder, $value, PDO::PARAM_STR);
    }
    
    $stmt->bindValue(':game', $game, PDO::PARAM_STR);
    $results = $stmt->execute();
    

提交回复
热议问题