【发布时间】:2014-02-08 04:49:09
【问题描述】:
您好,我在调用函数时出错。
"警告:C:\xampp\htdocs\blog\posts.php 中的非法字符串偏移 'id' 在第 28 行 2"
功能:
function get_short_posts() {
$sql = "SELECT * FROM posts ORDER by id DESC LIMIT 0, 5";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$timestamp = new DateTime($row['date']);
return array (
"id" => $row['id'],
"title" => $row['title'],
"content" => $row['content'],
"author" => $row['author'],
"date" => $timestamp->format('d-m-Y'),
"time" => $timestamp->format('H:i')
);
}
呼叫:
require_once "functions.php";
$_posts = get_short_posts();
foreach($_posts as $_post) {
echo $_post['id'];
}
【问题讨论】:
-
尝试在您的 while 循环中执行
die(var_dump($row));。这将停止所有其他执行,并在屏幕上显示错误。 -
你知道你在 get_short_posts 函数的第一次迭代之后返回,所以 foreach 不会按预期工作。
-
请显示您的表格列名。也许列“id”称为“Id”或“ID”?
-
另外,试试:
$result = mysql_query($sql)or die(mysql_error());
标签: php arrays function foreach while-loop