使用mysqli union的PHP mysqli_stmt_bind_result

时间:2015-05-16 12:22:32

标签: php mysql mysqli

所以我正在尝试创建一个UNION query,所以我可以从两个表(相同的数据库)中获取数据,之后我试图用mysqli_bind_result()来获取数据,但是我得到了错误:

  

mysqli_stmt_bind_result():绑定变量数与数字

不匹配

这是我的代码:

$sql = mysqli_stmt_init($con);
if(mysqli_stmt_prepare($sql, "(SELECT `naslov`, `id_lang` FROM `naslovi` WHERE `id_vijesti` = ?) UNION ALL (SELECT `text`, `id_lang` FROM `tekstovi` WHERE `id_vijesti` = ?)")) {
    mysqli_stmt_bind_param($sql, "ii", $id, $id);
    mysqli_stmt_execute($sql);
    mysqli_stmt_bind_result($sql, $naslov, $id_lang1, $text, $id_lang2);    
    $vijest = array();

    while(mysqli_stmt_fetch($sql)) {
        echo $naslov;
        if($id_lang1 == $id_lang2) {
            $vijest[] = array($naslov, $text, $id_lang1);
        }

    }

    mysqli_stmt_close($sql);

1 个答案:

答案 0 :(得分:1)

错误表示变量数量不匹配。 UNION查询合并内部查询中的所有列。

我认为你在这里寻找一个JOIN查询。请查看此页面:http://www.sitepoint.com/understanding-sql-joins-mysql-database/

编辑:添加了一个示例

"SELECT 
    `naslovi`.`naslov`, `naslovi`.`id_lang`, `tekstovi`.`text`, `tekstovi`.`id_lang` AS tekstovi_id_lang 
    FROM `naslovi` JOIN `tekstovi` 
    ON `naslovi`.`id_vijesti` = `tekstovi`.`id_vijesti` 
    WHERE `naslovi`.`id_vijesti` = ?"