<?php
include_once 'DB_Connect.php';
function getCategories() {
$db = new DB_Connect();
// array for json response
$response = array();
$response["Student"] = array();
// Mysql select query
$result = mysql_query("SELECT * FROM Student");
while ($row = mysql_fetch_array($result)) {
// temporary array to create single category
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["name"] = $row["name"];
$tmp["number"] = $row["number"];
$tmp["address"] = $row["address"];
// push category to final json array
array_push($response["Student"], $tmp);
}
// keeping response header to json
header('Content-Type: application/json');
// echoing json result
echo json_encode($response);
}
getCategories();
?>
我的Android应用程序有这个API,但我在下面遇到此错误的问题。有什么想法吗?
<br />
<b>Warning</b>: mysql_fetch_array() expects parameter 1 to be resource, boolean given in <b>...\get_Student.php</b> on line <b>13</b><br />
{"Student":[]}
答案 0 :(得分:2)
mysql_*
已被正式弃用。使用PDO
或mysqli
。这就是你使用MySQLi库的方法:
<?php
// Connect To Db
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Query Function
function getCategories()
{
// Init
global $mysqli;
$response = array('Student' => array());
// Query Db
$query = "SELECT * FROM Student";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$response['Student'][] = array(
'id' => $row['id'],
'name' => $row['name'],
'number' => $row['number'],
'address' => $row['address'],
);
}
$result->free(); // free up memory
}
// Finished
header('Content-Type: application/json');
exit(json_encode(response));
}
// Test
getCategories();
// Close Db Connect
$mysqli->close();
您可以拥有以下代码:
// Connect To Db
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
在名为 db_connect.php 的文件中,您可以将其包含在需要数据库连接的脚本中。因为变量$mysqli
是在function() { ... }
范围之外启动的;您需要使用global $mysqli;
来访问它。无论连接代码在同一文件上还是包含在外部文件中,都适用。快乐的编码。