gpt4 book ai didi

php - 是否有相当于 mysqli 语法 $stmt->bind_param() 的 PDO?

转载 作者:行者123 更新时间:2023-11-29 11:24:22 24 4
gpt4 key购买 nike

编辑代码
我有一行 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();
}


谢谢。

最佳答案

如果您确实需要使用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']

关于php - 是否有相当于 mysqli 语法 $stmt->bind_param() 的 PDO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38482448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com