Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.
Related
I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);
I am trying to unset a value from test_bots.json and save it back, but somehow the data format is being changed in the process.
test_bots.json contains this JSON array:
["John","Vladimir","Toni","Joshua","Jessica"]
My code looks like this:
$good = 'Toni';
$good_arr = file_get_contents('test_bots.json');
$good_arr = json_decode($good_arr);
if(in_array($good, $good_arr)){
$key = array_search($good, $good_arr);
unset($good_arr[$key]);
$good_arr2 = json_encode($good_arr);
file_put_contents('test_bots.json',$good_arr2);
}
The output that's saved is:
{"0":"John","1":"Vladimir","3":"Joshua","4":"Jessica"}
but I want the output to look like:
["John","Vladimir","Joshua","Jessica"]
I tried to unserialize the array before saving it, but it's not working.
Why is this happening?
In order for json_encode to convert a PHP array with numeric keys to a JSON array rather than a JSON object, the keys must be sequential. (See example #4 in the PHP manual for json_encode.)
You can accomplish this in your code by using array_values, which will reindex the array after you have removed one of the items.
$good_arr2 = json_encode(array_values($good_arr));
I want to store short arrays in a field. (I realize there are reasons to break the array up into items and store separately, but I'm opting for a simple storage option at the expense of less capability.)
My code to create the array is as follows:
$str = "one,two,three,four";
$array = explode (",",$str)
I then store into a text field in mysql using an insert statement It seems to store fine. In PhPAdmin, it shows ARRAY in the field and if I just echo $array, it prints "ARRAY".
The problem is occurring when I try to retrieve data.
I am retrieving using
while($row = mysql_fetch_array($res)) {
$array = $row['list']; //that's the field it is stored in
echo $array; // echoes "ARRAY"
//so far so good. However, when I then try to print out the contents of the array, I get error messages. I have tried using implode and also for each.
$text = implode(",", $array);//yields error message improper argument in implode function
foreach($array as $val) {
echo $val;
} //yields error message improper argument for for each statement
}
Could my entry in the dbase not be a proper array? What could the problem be? Thanks for any suggestions.
The usual approach to storing an array in this way is to serialize the data before input, and unserialize it upon retrieval.
$array = array('one', 'two', 'three', 'four');
$stringToStore = serialize($array);
Later:
while($row = mysql_fetch_array($res)) {
$array = unserialize($row['list']);
var_dump($array);
}
What you're inserting is not an array, just what PHP has evaluated your array as being in string form. To store an array in MySQL without properly normalizing your data you'll need to serialize it. Basically you'd want to do something like:
$serialized = implode(',', $arrayToStore);
and then store that in MySQL. On its way out then you'll do:
$unserialized = explode(',', $arrayFromMySQL);
I think you can use serialize and also (if you don't use serialize) if your array string is as follows
$str = "one,two,three,four";
then why you are making it an array before inserting it into your database, I think you can insert the string directly and when you need to use your string as an array then you can simply retrieve the string from database and make it an array using explode like
while($row = mysql_fetch_array($res)) {
$array = explode(",", $row['list']); // "one,two,three,four"
echo $array[0]; // one
I have a "recruiter" table in my database which has different attributes and one of them is "Professions". "Professions" is a serialized array which I get from a multiple select form. And this works fine.
When I unserialize this attribute nothing is printed - no error, no text.
This is a code I was testing serialization with:
$sql = 'SELECT Company_name, Status, Size, Professions, Seniority_levels, Sector, Website, Location FROM Recruiter';
$query = mysql_query($sql, $con);
while($result = mysql_fetch_array($query, MYSQL_BOTH)){
$recruiters[] = array($result[0], $result[1], $result[2], $result[3], $result[4], $result[5], $result[6], $result[7]);
}
foreach($recruiters AS $recruiter){
$test = unserialize($recruiter[3]);
echo $test[0].'<br>';
}
So basically $test[0] prints nothing although the new lines are printed. Please help!
try printing the $test array and the $recruiters and the $recruiter arrays. See if the result is fine before the unserialisation of the data. If the query returns any data. Also try the while loop with mysql_fetch_assoc. Let me know of the results and if this solves the problem
test = unserialize($recruiter[3]); should become test = unserialize($recruiter[5]); since the sector field is the sixth column .
However what if somewhere in the future you might need to select rows where sectors equal smth ? serialize whont help you then so i suggest you have a look at a different implementation for the sector filed witch is called bitwize http://www.litfuel.net/tutorials/bitwise.htm
Edit
Asuming you hit the right column and the column contains a:1:{i:0;s:27: a:1:{i:0;s:27: a:38:{i:0;s:27: a:9:{i:0;s:39:, it looks like the serialized array is not fully saved in you're db, it's only part of it . So the unserialize function whont return you an array . Have a look at the length of the mysql field i assume you've set it smaller than you need so you're data is trimmed on insert/update .
Edit
a:1:{i:0;s:27: you're still missing the rest of the serialized array . s:27: means a string is following containint 27 characters, and you're serialized array stops there when it should look like
a:1:{i:0;s:27:"123456789012345678901234567";}
( a:1 stands for an array containing 1 value with it's content between {}, i:0; is the array key 0, s:27:""; stands for a string containing 27 characters as the value for the i:0 key ) .
I have a database table as follows.
<table border='1'><th>Id</th><th>FirstName</th><th>last Name</th><tr><td>1</td><td>Tom</td><td>T</td></tr><tr><td>2</td><td>Jerry</td><td>J</td></tr></table>
I would like to store all values as a multi dimensional array using php(using a while loop to retrieve fields).That is,
I would like the data to be echoed as:
array(array(1,Tom,T),array(2,Jerry,J));
$result = mysql_query("SELECT * FROM tablename;");
while($result_ar = mysql_fetch_array($result)) {
$multid_array[] = $result_ar;
}
after which $multid_array will be an array of arrays.
You can use phps serialize function to convert any variable into a string representation
$string = serialize($dbData);
You can use unserialize() to convert the string back into arrays, objects, etc
$dbData = unserialize($string);
Once you have the data within a string, it's very easy to store in a file, db, etc. A disadvantage is that you won't be able to search your database easily for this data.