I am writing some PHP code to allow external read-only access to certain fields in a MySQL database.
I have a table where there is an ID associated with each day of the week and I need to run one query for each day, get a serialised PHP object, manipulate it and return it as JSON.
My code is as follows:
<?php
// Connect to DB
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
mysqli_set_charset($link, DB_CHARSET);
$dayIds = ["Monday" => 3585,
"Tuesday" => 3586,
"Wednesday" => 3587,
"Thursday" => 3588,
"Friday" => 3589,
"Saturday" => 3590,
"Sunday" => 3591];
$dayData = [];
// Iterate over days
foreach($dayIds as $day => $dayId){
// Create SQL
$sql = "select value from table_meta where day_id=".$dayId;
echo $sql."<br><br>";
$result = mysqli_query($link, $sql);
// Get Result
$new_data = [];
$row = mysqli_fetch_row($result);
$data = unserialize($row[0]);
// Manipulate Data and add it to the new_data array
//
// (Hidden for confidentiality reasons)
//
$dayData[$key] = $new_data;
echo json_encode($new_data)."<br><br>";
}
The issue is that the first query always fails (it returns false), I've tried switching the order of Monday and Tuesday in the array and then Monday works and Tuesday fails.
It gives the error "Warning: Invalid argument supplied for foreach()" when I try to loop over the unserialised result.
To solve it I have added another element to the top of the $dayIds array and it is working, but as this code is going to go to a client, I would like to work out the reason the first fails.
Thanks In Advance.
答案 0 :(得分:0)
$row = mysqli_*
需要在$data
之前。
$data = unserialize($row[0]);
$row = mysqli_fetch_row($result);
答案 1 :(得分:0)
在从数据库获取数据之前,您正在反序列化数据。 你的代码应该是这样的
$row = mysqli_fetch_row($result);
$data = unserialize($row[0]);