为什么我的php脚本没有返回任何变量?

时间:2016-10-15 17:37:23

标签: php jquery ajax

我一直试图在php脚本中添加一个“加载更多”按钮。

我在这里有一个相当复杂的MYSQL查询,但是我现在尝试使用预处理语句并输出两个变量。

虽然脚本 会返回预期的结果数,但它实际上并没有回显任何变量。我怀疑问题出在foreach循环中...在控制台响应中我可以看到:

<li>-</li><li>-</li><li>-</li>

脚本

//get current starting point of records
$position = (($page_number-1) * $item_per_page);

//fetch records 
$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 LIMIT ?, ?");

//bind parameters for markers
$results->bind_param("dd", $position, $item_per_page); 
$results->execute(); //Execute prepared Query
$results->bind_result($title, $file); //bind variables to prepared statement

//output results from database

while($row = $results->fetch()){ //fetch values

$titles =  explode (",", $row['title']);
$files = explode (",", $row['file']);

foreach($titles as $title) {
foreach($files as $file) {
    echo '<li>'.$title.'-'.$file.'</li>';   
}
}
}

这是一个来自phpadmin的输出示例。 enter image description here

1 个答案:

答案 0 :(得分:1)

我认为你误解了bind_result()的工作原理。

  

当调用mysqli_stmt_fetch()来获取数据时,MySQL客户端/服务器协议将绑定列的数据放入指定的变量var1,....

这意味着select语句中列出的列将映射到调用bind_result()

中列出的变量

例如,如果您有SELECT first_name, last_name FROM names并且您致电:

$results->bind_result($first, $last);

当您循环结果时,对于每一行,first_name的值将通过变量$first提供,last_name的值将通过$last提供}

这意味着你可以这样做:

while($results->fetch()){ //fetch values
    echo 'Hi '.$first.' '.$last;
}

尝试使用以下代码:

        //fetch records
        // change your select to only select the columns you need and the order needs to be the same as bind_result below
        $results = $mysqli->prepare("SELECT up.file,up.title
                                     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 LIMIT ?, ?");




        //bind parameters for markers
        $results->bind_param("dd", $position, $item_per_page);
        $results->execute(); //Execute prepared Query
        $results->bind_result($title, $file); //bind variables to prepared statement
        // this binds the selected columns to the variable names given for use below
        // $title below is equivalent to $result['title] inside a for loop 



        while($results->fetch()){ //fetch values 
            echo '<li>'.$title.'-'.$file.'</li>';
        }