我正在尝试使用动态where子句和动态参数创建一个select查询,但是我总是遇到错误:
警告:mysqli_stmt :: bind_param():类型定义字符串中的元素数量与绑定变量的数量不匹配
我真的不明白,因为似乎计数还可以。因此,这就是原始代码的样子。我看不到我在做什么错。
//get variables $mediaArray ='Facebook,Twitter,Twitch,'; $otherMedia = 'House'; //convert string to array $socialArray = explode(',', $mediaArray) //declare some variables to be used later $andwhere = ''; $bp = ''; $socialmarray = '' //get every value from array of social media foreach($socialArray as $socialmedia){ $socialmarray .=$socialmedia.','; $andwhere .= " AND socialmedianame=?"; $bp .='s'; } //test strings echo $wheres = $andwhere;//AND socialmedianame=? AND socialmedianame=? AND socialmedianame=? echo $bip = $bp.'s';//ssss echo $validarayy = rtrim($socialmarray,',');//Facebook,Twitter,Twitch //select query $selectquery = $conn->prepare("select * from mediaservices where socialmedianame=? $wheres"); $selectquery->bind_param("$bip",$otherMedia,$validarayy); $selectquery->execute(); $resultquery = $selectquery->get_result();
因为:
您应该使用准备好的语句,并将所有WHERE子句逻辑合并到一个IN语句中。
WHERE
IN
与使用pdo相比,构建此动态的预处理语句要复杂得多(就语法而言),但这并不意味着仅由于此任务就需要放弃mysqli。
$mediaArray ='Facebook,Twitter,Twitch,'; $otherMedia = 'House'; $media = array_unique(explode(',', $mediaArray . $otherMedia)); $count = count($media); $conn = new mysqli("localhost", "root", "", "myDB"); $sql = "SELECT * FROM mediaservices"; if ($count) { $stmt = $conn->prepare("$sql WHERE socialmedianame IN (" . implode(',', array_fill(0, $count, '?')) . ")"); $stmt->bind_param(str_repeat('s', $count), ...$media); $stmt->execute(); $result = $stmt->get_result(); } else { $result = $conn->query($sql); } foreach ($result as $row) { // access values like $row['socialmedianame'] }
对于正在寻找类似的动态查询技术的任何人:
`SELECT
LIKE
`INSERT
execute()