Displaying the BLOB file on frontend using PHP - php

I have a table named listing_fees
and I want to get the data by the id of 12
the data that I want to get is a BLOB that is named [BLOB - 205B]
inside the BLOB file is an array like this:
a:7:{s:2:"id";s:1:"1";s:5:"label";s:8:"For Sale";s:6:"amount";s:4:"0.00";s:4:"days";s:1:"7";s:6:"images";s:1:"0";s:10:"categories";a:2:{s:3:"all";i:0;s:10:"categories";a:1:{i:0;i:30;}}s:10:"extra_data";N;}
I don't understand a thing on this code.
I want to display it on the frontend of my html using PHP
what will I to display it?
SQL Query or something else.

That data is in PHP Serialized format you can decode it using unserialize
Example
$data = 'a:7:{s:2:"id";s:1:"1";s:5:"label";s:8:"For Sale";s:6:"amount";s:4:"0.00";s:4:"days";s:1:"7";s:6:"images";s:1:"0";s:10:"categories";a:2:{s:3:"all";i:0;s:10:"categories";a:1:{i:0;i:30;}}s:10:"extra_data";N;}';
$data = unserialize($data);
echo "<pre>" ;
foreach ( $data as $key => $value ) {
if ($key == 'categories') {
echo $key, " = ", $value['categories']['0'], PHP_EOL;
} else {
echo $key, " = ", $value , PHP_EOL;
}
}
Output
id = 1
label = For Sale
amount = 0.00
days = 7
images = 0
categories = 30
extra_data =

The data in the BLOB column appears to be serialized data, not a file. Because of this, you don't want to just "output" it to the page - you'll want to unserialize it (via PHP's unserialize() method) and then process to be displayed, well, however it should be displayed. Taking the exact data you display in your question and passing using unserialize() on it gives me an array with the following:
Array
(
[id] => 1
[label] => For Sale
[amount] => 0.00
[days] => 7
[images] => 0
[categories] => Array
(
[all] => 0
[categories] => Array
(
[0] => 30
)
)
[extra_data] =>
)
A simple setup, to query the database and retrieve the column, would be:
$mysqli = new mysqli('localhost', 'username', 'password', 'db');
$result = $mysqli->query('SELECT column_name FROM listing_fees WHERE id = 12');
$data = $result->fetch_assoc();
$result->close();
To use the data that is in the $data array, you can do:
$blob = unserialize($data['column_name']);
Now, you can display the data however you want, accessing each value with $blob['label'] or $blob['days'].

Related

PHP > How to skip an element while using json_encode

I need to send data to the client side in JSON format.
So far, it worked just fine with json_encode as follows:
$sql = "SELECT `card`.`CardID`,`card`.`Text`,... WHERE (`card`.`CardID`= :ItemId)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ItemId', $itemid);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
$posts[]=$row;
}
...
...
$res["rows"] = $posts;
$res["maptel"] = $maptelindicator;
echo json_encode($res,JSON_UNESCAPED_UNICODE);
But now I have a problem. I have a new field (Videofiles) in the DB that is already JSON formatted- stored as the ouput of a SDK function. If I encode this JSON encoded field once more, I get data which is unreadable on the client side..
How can I json_encode all the other data, but skip this specific field, Videofiles?
Here is the output of a sample data structure using print_r:
Array
(
[rows] => Array
(
[0] => stdClass Object
(
[Name] => Company13
[CID] => 26
[CardID] => 26-000002
[Text] => Kleopatra Deluxe Hotel reservations
[ImageLink] =>
[VideoFiles] => [{"quality":"mobile","type":"video/mp4","width":480,"height":270....}]
[ClickDate] => 2015-11-03
)
)
[maptel] => 0
)
Thanks...
You could use json_decode to decode the already encoded field and then add the result in the $res array.
Best way to do it delete this section in SQL!
But if you want to delete in php it will have a cost for you and you can use unset for this situation;
foreach ($posts as $post){
unset($posts['VideoFiles']);
}
$res["rows"] = $posts;
$res["maptel"] = $maptelindicator;
echo json_encode($res,JSON_UNESCAPED_UNICODE);

Editing a poorly formatted JSON string in PHP

I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!

Append Array to Output to JSON after Looping with PHP

Essentially, the data should look as follows, but as one array for each user that contains their info. It should be packaged as a JSON after completely looping through.
Preface
Using the pre tags with print_r I got what it should look like using some humorous sample data:
User 1 is following:
Array
(
[0] => Array
(
[first] => Hugh
[last] => Janus
[bg] => /resources/bg/2/b.png
[prof_pic] => /resources/profilepics/2/b.jpg
[bio] => 50% proctologist, 50% baker.
)
)
Array
(
[0] => Array
(
[first] => Andrew
[last] => Dickens
[bg] => /resources/bg/3.c.jpg
[prof_pic] => /resources/profilepics/3/c.jpeg
[bio] => Therapists are pretty cool.
)
)
Array
(
[0] => Array
(
[first] => Anita
[last] => Dickson
[bg] => /resources/bg/4/d.jpg
[prof_pic] => /resources/profilepics/4/d.JPG
[bio] => Just another barista.
)
)
Essentially, everything needs to come back as one JSON item that someone could use for any purpose with the supplied info.
Background on the Following Code
This code selects all User IDs from the table 'followers' where the person who is following someone is equal to fB and the person who owns that friendship is fA. In this instance, userID 1 is trying to look at a page of every person they follow with their profile pic, background pic, first name, last name, and bio. The data that the JSON is outputting will be formatted in another file, but this is just being used to curate the raw data.
$dbh is the PDO database connection and the code uses prepared statements for security.
Code
$flingJSON = 0;
$userid = "1";
$result = $dbh->prepare('SELECT fA
FROM followers
WHERE fB=:userid');
$result->bindParam(':userid', $userid);
$result->execute();
$rawData = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($rawData as $following) {
$followingID = $following['fA'];
$getInfoFling = $dbh->prepare('SELECT first, last, bg, prof_pic, bio
FROM users
WHERE id=:flingID
');
$getInfoFling->bindParam(':flingID', $followingID);
$getInfoFling->execute();
$flingJSON = $getInfoFling->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($flingJSON);
echo "</pre>";
}
Your help is greatly appreciated in advance and as a thanks you'll get a shout-out in the documentation for this file.
This should return a single array with all the user's info:
//Create empty data array
$flingData = array();
$userid = "1";
$result = $dbh->prepare('SELECT fA
FROM followers
WHERE fB=:userid');
$result->bindParam(':userid', $userid);
$result->execute();
$rawData = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($rawData as $following) {
$followingID = $following['fA'];
$getInfoFling = $dbh->prepare('SELECT first, last, bg, prof_pic, bio
FROM users
WHERE id=:flingID
');
$getInfoFling->bindParam(':flingID', $followingID);
$getInfoFling->execute();
//Append user info to data array
$flingData[] = $getInfoFling->fetch(PDO::FETCH_ASSOC);
}
//Create JSON string
$flingJSON = json_encode($flingData);
echo "<pre>";
print_r($flingJSON);
echo "</pre>";

PHP - Removing one array layer

I have a simple PHP function that will grab information from a database based on a unique ID:
function oracleGetGata($query, $id="id") {
global $conn;
$results = array();
$sql = OCI_Parse($conn, $query);
OCI_Execute($sql);
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row[$id] ] = $row;
}
return $results;
}
So for example $array = oracleGetData('select * from table') would return:
[1] => Array
(
[Title] => Title 1
[Description] => Description 1
)
[2] => Array
(
[Title] => Title 2
[Description] => Description 2
)
This is fine, however, if I just want to return one record $array = oracleGetData('select * from table where id = 1') it returns the data like:
[] => Array
(
[Title] => Title 1
[Description] => Description 1
)
Not only am I unsure of how to reference this (there is nothing identifying the array) I'd also like to somehow change my function so if it just returns one record, it will just be a simple one dimensional array.
I've looked into the usual PHP array functions but can't find anything that'll help, nor an easy way of identifying how deep the array is.
Would really appreciate any help, thank you
Use array_pop():
$array = array_pop(oracleGetData('select * from table where id = 1'));
You will then get one single array:
Array
(
[Title] => Title 1
[Description] => Description 1
)
Instead of an array embedded in another one:
Array
(
[] => Array
(
[Title] => Title 1
[Description] => Description 1
)
}
I think there is an logic error in your script:
Change
$results[ $row[$id] ] = $row;
into
$results[] = $row;
The problem is, that you want to have the Database key value as array key value, but you don't know the Database key, since you don't know what the query will look like.
You could try:
$results[$row['id']] = $row;
But this only works when all of your results have a Database key named "id".
You pass a $id in the function signature, but in the loop you uses $row[$id], Why? Maybe the error is there.
If you want a sequencial id in your result set, you don't need use the $id, you can uses array_push() function
array_push($result, $row);
OR
$results[] = $row;

PHP Array insert into MySQL table as individual rows

I am trying to insert multiple rows in a MySQL table from PHP arrays. I managed with with help of other members to get set of values in a pair of brackets but when i try to insert this i get "Error: Column count doesn't match value count at row 1" I donot know where am i going wrong. my codes are as below: (The number of values i get vary according to user input)
$docno1=array();
$serialno = array();
$acc_name = array();
$debit = array();
$credit = array();
for ($i=1;$i<=$rowcount;$i++)
{
//echo 'Accountname'.$i.' :'.($_GET['accname'.$i]).'<br>';
$docno1 [] = ($_GET['docno']);
array_unshift($docno1,"");
unset($docno1[0]);
$serialno [] = $i;
array_unshift($serialno,"");
unset($serialno[0]);
$acc_name[] = ($_GET['accname'.$i]);
array_unshift($acc_name,"");
unset($acc_name[0]);
$debit[] = ($_GET['DrAmount'.$i]);
array_unshift($debit,"");
unset($debit[0]);
$credit[] = ($_GET['CrAmount'.$i]);
array_unshift($credit,"");
unset($credit[0]);
}
$sum_dr = array_sum ($debit);
$sum_cr = array_sum ($credit);
echo ' values of $multi<br>';
$multi = array(
($docno1),
($serialno), //Array for a row of fields
($acc_name),
($debit),
($credit),
($docno1)
);
print_r($multi);
$new = array();
foreach($multi as $key=>$value) {
$new[] = "'".implode("','", $value)."'";
}
echo '<br>Values of $new <br>';
print_r($new);
$query = "(".implode("), (",$new).")";
echo $query.'<br>';
mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());
echo "Inserted successfully";
die;
The results i get are :
values of $multi
Array
(
[0] => Array
(
[1] => 3434
[2] => 3434
)
[1] => Array
(
[1] => 1
[2] => 2
)
[2] => Array
(
[1] => Lemon
[2] => Kidney Beans
)
[3] => Array
(
[1] => 20
[2] => 10
)
[4] => Array
(
[1] => 0
[2] => 0
)
[5] => Array
(
[1] => 3434
[2] => 3434
)
)
Values of $new
Array
(
[0] => '3434','3434'
[1] => '1','2'
[2] => 'Lemon','Kidney Beans'
[3] => '20','10'
[4] => '0','0'
[5] => '3434','3434'
)
('3434','3434'), ('1','2'), ('Lemon','Kidney Beans'), ('20','10'), ('0','0'), ('3434','3434')
Error: Column count doesn't match value count at row 1
mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());
You are trying to insert something into 6 fields, so that $query string must have 6 values in it, or you get this error.
You have a lot of $query's that are 2 values. And that's not 6
It looks to me as if you are mapping your array the wrong way round. You're trying to add two records with six fields each, but what you're actually putting into the SQL statement are six records with two fields each.
This is why MySQL is complaining -- because you've told it you want to update six fields, but in each of the records you've given it, you've only specified two fields.
You need to build your array differently.
I assume that $docno1, $serialno, $acc_name, $debit and $credit will always all have the same number of array elements (it appears from your code that you are assuming this, so I'll follow you in your assumption).
In that case, you need to build your array something like this:
$multi = array();
foreach($docno1 as $key=>value) {
$multi[] = array(
$docno1[$key],
$serialno[$key], //Array for a row of fields
$acc_name[$key],
$debit[$key],
$credit[$key],
$docno1[$key])
}
Replace the block in your code where you set $multi with this, and your program should work.
Look at what print_r($multi) looks like now, and you'll see the difference.
(note, there are more efficient ways of writing your whole program than this, but I've focused on giving you a drop-in replacement for this specific bit, to help show you where you were going wrong, rather than simply rewriting the whole program for you)
Hope this helps.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the specific inserts -- for which you didn't specify a value.

Categories