我正在构建一个网站的职业部分并编写了这个PHP来与我尚未构建的应用程序进行对话。问题是,当json_encode只显示我的数据库的第一行时。任何指向正确方向的人都会非常感激。 谢谢, 约旦
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//variables
$server = 'localhost';
$user = 'root';
$password = '';
$db = 'starkdb';
// Connect to Database
$connection = mysql_connect($server, $user, $password)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
//Check if the skill has been updated. If it has, process and save it to the database
//POST update
if (isset($_POST['update']))
{
//Confirm that the 'id' value is a valid integer before getting the data
if (is_numeric($_POST['id']))
{
//Retrieve the data
$id = $_POST['id'];
$title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$description = mysql_real_escape_string(htmlspecialchars($_POST['description']));
//Error check both fields
if ($title == '' || $description == '')
{
$error = 'ERROR: Please fill in all Fields!';
}
else
{
//Update data to database
mysql_query("UPDATE skill SET title='$title', description='$description' WHERE id='$id'")
or die (mysql_error());
$row = mysql_fetch_array($result);
}
}
//POST create
else
{
//Get data, making sure it is valid
$title = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$description = mysql_real_escape_string(htmlspecialchars($_POST['description']));
//Error check both fields
if ($title == '' | $description == '')
{
$error = 'ERROR: Please fill in all Fields!';
}
else
{
//Save new skill to database
mysql_query("INSERT skill SET title='$title', description='$description'")
or die(mysql_error());
$row = mysql_fetch_array($result);
}
}
}
//GET ID
else
{
//Get the id value from URL
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
//Query DB
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM skill WHERE id=$id") or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$title = $row['title'];
$description = $row['description'];
}
}
//GET list
else
{
$result = mysql_query("SELECT * FROM skill") or die(mysql_error());
$row = mysql_fetch_array($result);
}
}
//Encode data and display with JSON
echo json_encode($row);
?>
答案 0 :(得分:2)
mysql_fetch_array
一次只从数据库中拉出一行,你必须在循环中迭代它,如下所示:
<?php
$rows = array( ); // Initialise an empty array
while( $row = mysql_fetch_array( $result ) ) { // Loop over the database iterator
$rows[] = $row; // Append the row to the array of rows
}
echo json_encode( $rows ); // Output the json encoded array of rows
?>
有关详细信息,请参阅PHP手册页:http://php.net/manual/en/function.mysql-fetch-array.php
答案 1 :(得分:0)
$array_of_rows = array();
while ($row = mysql_fetch_array($result)) {
array_push($array_of_rows, $row);
}
echo json_encode($array_of_rows);
......或其他一些。