[英]how to fix undefined variable in php?
我有一個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
總是顯示“未定義的變量”?
提前致謝。
您會收到 undefined $count
錯誤,因為$count
僅在if
語句中定義。
當if
子句不適用時, $count
未定義。
在if
添加else
子句並初始化$count=0;
它會解決你的問題。
例子:
....
$count = $actual_row_count;
exit;
}
else $count = 0;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.