我真的很想得到以下 MySQL/PHP 问题的帮助(也许是错误?)
我正在尝试使用 MySQL/PHP 从我的数据库中检索和显示数据数组,但是当我回显该数组时,它返回第一个值作为“null”。
因此,即使数据库具有以下信息:
"Example 1", "Example 2", "Example 3"...
php 回显:
"null", "Example 2, "Example 3"
我想这会是一个普遍的问题,但我还没有设法在互联网上的其他地方找到所需的信息,所以我希望你们好心的人能提供帮助。
我的 PHP
/* If connection to database, run sql statement. */
if ($conn) {
$fetch = mysql_query("SELECT column FROM table WHERE approved = '1' ");
// declare empty array to fill later
$result = array();
// make sure the MySQL pointer is looking at the first row
mysql_data_seek($fetch, 0);
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
foreach ($row as $value) {
$row_array = $value;
// push info into new array with just the value
array_push($result, $row_array);
}
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
更新
新代码由 Mark B 提供:
if ($conn)
{
$sql = "SELECT column_name FROM table WHERE comment_approved = '1' ";
$query = mysql_query($sql) or die(mysql_error());
$result = array();
while ($row = mysql_fetch_assoc($query)) {
$result[] = $row['column_name'];
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($result);
注意:
'null' 问题在有或没有:
mysql_data_seek($fetch, 0);
因为这似乎什么都不做。
任何帮助都会很棒!
已解决
感谢Mark B谁指出问题可能出在数据库而不是 PHP 中,结果发现字符 ` 潜伏在应该有 ' 的地方。这导致信息显示为“空”。
最佳答案
$sql = "SELECT column FROM table WHERE approved = '1'";
$result = mysql_query($sql) or die(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($result)) {
$data[] = $row['column'];
}
echo json_encode($data);
您不必执行查找操作,因为您当时没有对结果执行任何操作。由于您只是从数据库中获取单个列,因此也不需要内部 foreach() 循环。
关于php - 我的 PHP 数组的第一个值在有值时返回为 'null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6022435/