如何将参数传递给PDO prepare语句

时间:2019-02-10 18:10:34

标签: php pdo

我是PHP PDO的新手,我想将param传递给prepare语句中的查询,但我一次又一次失败,尽管它在mysqli语句中工作正常,但是在这里它没有显示记录未显示任何错误。问题在于传递参数,请有人指导我...

这是我的代码。

if($_GET['title']!="" && isset($_GET['cities']) && isset($_GET['categories'])){

    $title = trim($_GET['title']);
    $cities = $_GET['cities'];
    $categories = $_GET['categories'];
    foreach($cities as $city) {
      $recordcities .= $city."|";
    }
    foreach($categories as $category){
      $recordCat .= $category."|";
    }

    $select = $pdo->prepare("select * from selectcities WHERE CONCAT(',', `cities`, ',') REGEXP ',(:cities),' and CONCAT(',', `category`, ',') REGEXP ',(:categories),' ");
    $select->bindParam(':cities',$recordCities,PDO::PARAM_STR);
    $select->bindParam(':categories',$recordCat,PDO::PARAM_STR);
    $select->execute();
    echo $select->rowCount();
    while($result = $select->fetch(PDO::FETCH_ASSOC)){
       //echo $result['Title'].'<br>';
       print_r($result);
    }
  }

1 个答案:

答案 0 :(得分:1)

我认为您必须使绑定变量包含任何额外的标记,而不是尝试将其包含在SQL中,因此您的绑定变为',('.$recordCities.'),',而SQL只是REGEXP :cities ...

$select = $pdo->prepare("select * from selectcities 
            WHERE CONCAT(',', `cities`, ',') REGEXP :cities 
              and CONCAT(',', `category`, ',') REGEXP :categories ");
$recordCities = ',('.$recordCities.'),';
$recordCat = ',('.$recordCat.'),';
$select->bindParam(':cities',$recordCities,PDO::PARAM_STR);
$select->bindParam(':categories',$recordCat,PDO::PARAM_STR);