是否存在与mysqli语法$ stmt-> bind_param()相当的PDO?

时间:2016-07-20 13:18:06

标签: php mysql pdo

编辑代码
我在一个工作查询中有一行mysqli代码:$stmt->bind_param("ss", $_POST['skills'], $_POST['city']);

我发现需要更改为PDO并使用过:
$stmt->bindValue(':skill', $skills, PDO::PARAM_STR); $stmt->bindValue(':city', $city, PDO::PARAM_STR);

我没有得到任何结果,除了回应的“没有找到结果。你进入了一个城市吗?”虽然存在与数据库的连接,但在搜索表单中已加载“城市”的选择列表,但也没有错误消息。完整查询:

  try {
     global $pdo;
    if(isset($_POST['search'])) {
     $skills = htmlspecialchars($_POST['skills']);
     $city = htmlspecialchars($_POST['city']);
$stmt = $pdo->prepare('SELECT skill.skill_name, team.city FROM skill JOIN team ON skill.skill_id=team.skill WHERE skill.skill_name LIKE :skills AND team.city LIKE :city');
     $skills = "%".$skills."%";
     $city = "%".$city."%";
$stmt->bindParam(':skills', $skills, PDO::PARAM_STR);
$stmt->bindParam(':city', $city, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() > 0){
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

  foreach ($rows as $row) {
  echo $row['skill'] . " is available in " . $row['city'];
    }
}
else {
echo "No result found. Did you enter a city?";
    }
    }
    }//try
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}


感谢。

1 个答案:

答案 0 :(得分:1)

如果你真的需要使用LIKE,那么你需要在字符串中的某个地方使用通配符。由于占位符必须代表完整的数据文字,如果您想使用LIKE,则必须使用包含的通配符创建参数。

try {
    global $pdo;
    if(isset($_POST['search'])) {
        $skills = '%' . htmlspecialchars($_POST['skills']) . '%';
        $city = '%' . htmlspecialchars($_POST['city']) . '%';

        $stmt = $pdo->prepare('SELECT skill.skill_name, team.city 
                               FROM skill 
                                 JOIN team ON skill.skill_id=team.skill 
                               WHERE skill.skill_name LIKE :skill 
                                 AND team.city LIKE :city');

        $stmt->bindValue(':skill', $skills, PDO::PARAM_STR);
        $stmt->bindValue(':city', $city, PDO::PARAM_STR);
        $stmt->execute();
        if ($stmt->rowCount() > 0){
            $rows = $stmt->fetchAll();

            foreach ($rows as $row) {
                echo $row['skill_name'] . " is available in " . $row['city'];
            }
        }else{
            echo "No result found. Did you enter a city?";
        }
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}

ML的次要编辑:将$ row ['skill']更正为$ row ['skill_name']