我正在尝试将MySQL查询转换为准备好的语句并遇到麻烦,出于某种原因我没有得到任何结果。 MySQL查询肯定有效,但我无法看到我做错了什么。我真的很感激任何帮助。
在我的错误日志中,我收到错误Invalid argument supplied for foreach()
$results = $mysqli->prepare("SELECT up.id,up.file,up.title,p.user_name,p.user_id, GROUP_CONCAT(CONCAT(cp.user_id,'~',cp.user_name) SEPARATOR '|') AS tagGroup
FROM tbl_uploads up
LEFT JOIN tbl_users p ON up.user_id = p.user_id
LEFT JOIN tbl_collab c ON up.file = c.file
LEFT JOIN tbl_users cp ON cp.user_id = c.collab_userid
GROUP BY up.file ORDER BY up.id DESC");
$results->execute(); //Execute prepared Query
$results->bind_result($page_id,$user_id,$file); //bind variables to prepared statement
//output results from database
while($results->fetch()){ //fetch values
$page_id = explode (",", $row['id'] );
$user_id = explode (",", $row['user_id'] );
$files = explode (",", $row['file']);
foreach($user_id as $user_id) {
foreach($files as $file) {
foreach($page_id as $page_id) {
echo '<li>'.$page_id.' - '. $user_id.' - '.$file.'</li>';
}
}
}
}
?>
答案 0 :(得分:2)
相应地更改您的代码:
$stmt = $mysqli->prepare("SELECT up.id,up.file,up.title,p.user_name,p.user_id, GROUP_CONCAT(CONCAT(cp.user_id,'~',cp.user_name) SEPARATOR '|') AS tagGroup
FROM tbl_uploads up
LEFT JOIN tbl_users p ON up.user_id = p.user_id
LEFT JOIN tbl_collab c ON up.file = c.file
LEFT JOIN tbl_users cp ON cp.user_id = c.collab_userid
GROUP BY up.file ORDER BY up.id DESC");
$stmt->bind_param( 'iis', $page_id, $user_id, $file );
$stmt->execute();
$result = $stmt->get_result();
//output results from database
while( $row = $result->fetch_assoc() ){
$page_ids = explode( ",", $row['id'] );
$user_ids = explode( ",", $row['user_id'] );
$files = explode( ",", $row['file'] );
foreach( $user_ids as $user_id ) {
foreach( $files as $file ) {
foreach( $page_ids as $page_id ) {
echo '<li>'.$page_id.' - '. $user_id.' - '.$file.'</li>';
}
}
}
}
还有一件事:在用逗号分隔的数据库中的一个字段中存储page_ids
,user_ids
,files
不是最好的数据库结构!
<强>更新强>
如果您没有将任何参数传递给SQL语句,请使用以下命令:
$query = "SELECT up.id,up.file,up.title,p.user_name,p.user_id, GROUP_CONCAT(CONCAT(cp.user_id,'~',cp.user_name) SEPARATOR '|') AS tagGroup
FROM tbl_uploads up
LEFT JOIN tbl_users p ON up.user_id = p.user_id
LEFT JOIN tbl_collab c ON up.file = c.file
LEFT JOIN tbl_users cp ON cp.user_id = c.collab_userid
GROUP BY up.file ORDER BY up.id DESC";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$page_ids = explode (",", $row['id'] );
$user_ids = explode (",", $row['user_id'] );
$files = explode (",", $row['file']);
foreach($user_ids as $user_id) {
foreach($files as $file) {
foreach($page_ids as $page_id) {
echo '<li>'.$page_id.' - '. $user_id.' - '.$file.'</li>';
}
}
}
}
$result->close();
}