我已经看到了一些类似的问题,并尝试了修复,但它们无法正常工作。任何帮助将不胜感激。
我试图将数据库中的一些数据作为JSON返回。
这是我的代码:
<?php
$db = "signup";
$servername = "localhost";
$username = "username";
$password = "password";
$fetch = ("SELECT * FROM bookings");
$return_arr = array();
$conn = new mysqli($servername, $username, $password, $db); // working
$query_result = mysqli_query($conn, $fetch);
mysqli_select_db("bookings",$db);
while ($row = mysqli_fetch_array($query_result, MYSQL_ASSOC)) {
$return_arr[] = array(
'TIMESLOT' => $row['TIMESLOT'],
'USERPIN' => $row['USERPIN'],
'PLAYERS' => $row['PLAYERS'],
'ACCEPTED' => $row['ACCEPTED'],
'EMAIL' => $row['EMAIL'],
'TOTAL BOOKINGS' => $row['TOTALBOOKINGS'],
'BOOKING ID' => $row['BOOKINGID'],
'LAST BOOKING' => $row['LASTBOOKING'],
'DATE' => $row['DATE']
);
}
$user = json_encode($return_arr);
echo "<pre>";
print_r($return_arr);
echo "</pre>";
mysqli_close($conn);
?>
现在我从数据库中获取此信息:
Array
(
[0] => Array
(
[TIMESLOT] => 12:00-14:00
[USERPIN] => 25225649
[PLAYERS] => 4
[ACCEPTED] => 0
[EMAIL] => email@address.com
[TOTAL BOOKINGS] => 0
[BOOKING ID] => 1
[LAST BOOKING] => 0000,00,00
[DATE] => 0000,00,00
)
)
答案 0 :(得分:0)
我会将$ tclsh 2patt.tcl file foo4
foo4 #98980
更改为:
while
看到我在//...
$conn = new mysqli($servername, $username, $password, $db); // working
$query_result = mysqli_query($conn, "SELECT * FROM bookings");
//...
// Option 1 : Change MYSQL_ASSOC to MYSQLI_ASSOC
while ($row = mysqli_fetch_array($query_result, MYSQLI_ASSOC)) {
// Option 2 : Change to mysqli_fetch_assoc
// while ($row = mysqli_fetch_assoc($query_result)) {
// Debug
echo "<pre>";
print_r($row);
echo "</pre>";
$return_arr[] = array($row['BOOKINGID'],
$row['USERPIN'],
$row['TIMESLOT'],
$row['PLAYERS'],
$row['ACCEPTED'],
$row['EMAIL'],
$row['TOTALBOOKINGS'],
$row['LASTBOOKING'],
$row['DATE']
);
}
添加了括号,否则您将更改数组的值,而您只会获得最后一个。
之后删除&#34; [0]&#34;来自$return_arr
。这样你就可以将整个数组编码为json。
答案 1 :(得分:0)
试试此代码
$conn = new mysqli($servername, $username, $password, $db); // working
$sql = ""; // your query
$result = $conn->query($sql);
while($row = $result->fetch_array()) {
// Create results array
$rows[] = array(
'BOOKINGID' => $row['BOOKINGID'],
'USERPIN' => $row['USERPIN'],
// and go on....
);
}
mysqli_close($conn);
echo json_encode($rows[0]);