我有一个index.php
页面。这个页面的功能是使用AJAX,PHP和MySQL无限滚动。顶部包含PHP MySQL代码,底部包含JavaScript
我想在页面中心打印总行数,但每次尝试时都会显示“未定义变量”错误。
我认为在加载页面时,变量的总数首先尝试打印,然后发生PHP查询,因此它显示“未定义的变量”,但是当我将变量的总数放在PHP编码中时,没有问题。
我该如何防止这种情况?
我的index.php
是
//my php part here
<?php
if(isset($_POST["anotherID"])){
require_once("config.php");
$limit = (intval($_POST['limit']) != 0 ) ? $_POST['limit'] : 10;
$offset = (intval($_POST['offset']) != 0 ) ? $_POST['offset'] : 0;
$id = $_POST["anotherID"];
$query = $id;
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM x where title like '%xx%' ORDER BY rand() LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
$row_object = $DB->prepare("Select Found_Rows() as rowcount");
$row_object->execute();
$roww_object =$row_object->fetchobject();
$actual_row_count = $roww_object->rowcount;
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo'something';
}
}
$count = $actual_row_count;
exit;
}
?>
//my html part here
<html>
//some html codes
<?php echo $count; ?>
//some html codes here
//my java scripts here
<script type="text/javascript">
var busy = false;
var limit = 6
var offset = 0;
var anotherID = 5
function displayRecords(lim, off) {
$.ajax({
type: "POST",
async: false,
data: "limit=" + lim + "&offset="+ off+"&anotherID="+anotherID,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button"><div id="loader_image"><img src="loader.gif" alt="" width="24" height="24">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
//some html codes her
</html>
我知道在加载页面时,首先加载HTML部分,然后我的jQuery激活PHP部分,然后我的结果出现。
我该如何解决这个问题?
为什么$count
总是显示“未定义的变量”?
提前致谢。
答案 0 :(得分:0)
您收到未定义$count
的错误,因为$count
仅在if
语句中定义。
当if
子句不适用时$count
未定义。
向else
添加if
子句并初始化$count=0;
,它将解决您的问题。
示例:
....
$count = $actual_row_count;
exit;
}
else $count = 0;
?>