gpt4 book ai didi

php在stmt准备和执行语句后获取结果

转载 作者:可可西里 更新时间:2023-11-01 08:16:38 24 4
gpt4 key购买 nike

我正在尝试在 SQL 中执行搜索查询,使用 AJAX 将 div 标记更改为搜索结果。但是,我无法使用 stmt 绑定(bind)参数(为了安全)运行查询。通过打印变量,我发现所有部分都在工作,但我认为参数没有正确搜索,或者 get_result 使用不正确。我这么说的原因是,在 while 循环中打印时,输出总是“()”。顺便说一句,它从中提取的表有 20 多列

请看下面的代码:

<?php
$q = $_GET['q'];

$con = mysqli_connect('localhost','user','password','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}


$stmt=$con->prepare("SELECT * FROM Contacts WHERE firstGroup=? OR secondGroup=? OR thirdGroup=?");
$stmt->bind_param("sss", $q, $q, $q);
if($stmt->execute()){
$stmt->bind_result($name, $code);
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
}else{
echo "Didn't work";
}

非常感谢任何帮助!

最佳答案

请避免使用“select *”。你会遇到问题。

  • mysqli 仅当您对所有 列执行 bind_result 时才有效。
  • 如果您更改数据库,则必须编辑所有 bind_result 部分。
  • 性能较差。
  • 如果不查看数据库模式,您将看不到哪些列绑定(bind)到哪些变量

相反,使用

$stmt=$con->prepare("SELECT `name`,`code` FROM Contacts WHERE firstGroup=? OR secondGroup=? OR thirdGroup=?");

这个问题应该用这个来解决。如果您希望更轻松地更改选定的列,请参阅 this comment在 php.net 上使用数组并为每个元素调用 bind_result。然后您可以轻松地将查询更改为

$colums=Array("name","code","firstGroup");
$stmt=$con->prepare("SELECT `".implode("`,`",$columns)."` FROM Contacts WHERE firstGroup=? OR secondGroup=? OR thirdGroup=?");

并且在避免上述问题的同时配置所选列非常容易(在本例中,添加了“firstGroup”)。

关于php在stmt准备和执行语句后获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24769763/

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