Encoding a single key in associative array to base64 - php

I am trying to retrieve user data from a SQL table where one of the columns is blob_medium. I run the SQL query properly and get the data in the php script.
if(mysqli_num_rows($result)){
while($row=mysqli_fetch_assoc($result)){
$result_array['user_data'][]=$row;
}
}
Now, to json_encode this data, I need to encode the data of user_pic column to base 64. For that I am trying this. But, it seems I am doing something wrong. Any kind of help would be appreciated.
foreach($result_array as $key){
foreach($key as $key2){
//print_r(base64_encode($key2['user_pic']).'<br/>'.'<br/>');
$key2['user_pic'] = base64_encode($key['user_pic']);
//print_r(($key['user_pic']).'<br/>'.'<br/>');
}
}
When I uncomment the print_r statements my data is printed in base64 format but the data of the assoc array is not changing.

That's because the array's $key and $keys in the for loop are copies. If you want them to modify the original you can either do it by specifying them to be references, not copies:
foreach($result_array['user_data'] as &$key){
$key['user_pic'] = base64_encode($key['user_pic']);
}
Or by explicit index into the original:
foreach($result_array['user_data'] as $index => $key){
$result_array['user_data'][$index] ['user_pic'] = base64_encode($key['user_pic']);
}

That's because you're changing the $key2 array. A temporary value created by your foreachloop. I myself would recommend using a for loop in this specific situation, because I was told to never use a loop within a loop if I can prevent it, and it makes things a lot easier to read:
for($i=0; $i < count($result_array['user_data']); $i++){
$encodedUserPic = base64_encode($result_array['user_data'][$i]['user_pic']);
$result_array['user_data'][$i]['user_pic'] = $encodedUserPic;
}

Related

convert some value from mysql query using php

using php I make a query to mysql. Inside my query, some values are in seconds (just some of them), I'd like to convert them into mm:ss. So I need to move into my "array" query and I do not understand how to move inside my query result, attribute after attribute.
Here is my db :
In my php code, I make the query and then for each row I put it inside an array.
$data=array();
$q=mysqli_query($mysqli, "SELECT * FROM TEST3612 WHERE user_id=$queryid");
while ($row=mysqli_fetch_object($q)) {
//$data[]=gmdate("H:i:s", $row%86400);
$data[]=$row;
}
I'd like then to move into my array, and when I have the attribute CS for example, convert the value.
Here is what I tried :
foreach($data as $value) {
if ($value['CS']) {
$value['CS'] = gmdate("H:i:s", $value%86400);
}
}
I got an error. I don't know how to move into my array, a select a element of a object. I thought I did it good but apparently no.
Thank you for you help.
mysqli_fetch_object returns objects, not arrays. Also you used $value instead of $value->CS inside of gmdate. So you should iterate like this:
foreach($data as $value) {
if ($value->CS) {
$value->CS = gmdate("H:i:s", $value->CS % 86400);
}
}
Alternativly you can write this directly in your while loop, so you don't need the foreach loop. I would say this is the better solutions because you don't write unnecessary code and performance gets improved a little bit:
while ($row = mysqli_fetch_object($q)) {
if ($row->CS) {
$row->CS = gmdate("H:i:s", $row->CS % 86400);
}
$data[] = $row;
}

php encode nested json in wrong format

I trying to test display a nested Json structure but the result is in wrong format.
php
while($row=$statement->fetch()){
$value=str_replace('"','',$row['item_option_value']);
$option[$row['item_option_name']]=explode(',',$value);
$all[$row['oid']]=$option;
}
echo json_encode($all);
mysql databas structure
Here is the result when i run the script.
I want the json structure to be the right side of the screenshot. Anyone knows what's wrong?
You would need to empty the $option arrays then like this:
$option = []; //or $option = array(); in PHP < 5.4
This is needed in order not to keep storing the data from the previous iteration.
So:
while($row=$statement->fetch()){
$value=str_replace('"','',$row['item_option_value']);
$option = [];
$option[$row['item_option_name']]=explode(',',$value);
$all[$row['oid']]=$option;
}
echo json_encode($all);
The problem is because of this line here,
$option[$row['item_option_name']]=explode(',',$value);
In each iteration of while() loop, you're appending the previously calculated $options array to $all. Instead, create an temporary array to hold intermediate result and append that to $all in each iteration, like this:
while($row=$statement->fetch()){
$opArray = array();
$value=str_replace('"','',$row['item_option_value']);
$opArray[$row['item_option_name']]=explode(',',$value);
$all[$row['oid']]=$opArray;
}
echo json_encode($all);

Pushing values from a $_Get query to a value using implode

I am attempting to use a for loop or for each loop to push the values from a get query to another variable. May I have some help with this approach?
Ok here is where I am:
for ($i = 0 ; i < $_GET['delete']; i++) {
$_jid [] = $_GET['delete'];
}
You don't actually need a loop here. If $_jid already is an array containing some values, consider just merging it with $_GET['delete'].
if (is_array($_jid)) {
$_jid = array_merge($_jid, $_GET['delete']);
}
If $_jid is not an array and doesn't exist except as a container for $_GET['delete'] you do can just assign the array. There is no need to loop at all.
$_jid = $_GET['delete'];
Of course in that case, you don't even need to copy it. You can just use $_GET['delete'] directly, in any context you planned to read from $_jid.
Update:
If the contents of $_GET['delete'] are originally 923,936, that is not an array to begin with, but rather a string. If you want an array out of it, you need to explode() it on assignment:
$_jid = explode(',', $_GET['delete']);
But if you intend to implode() it in the end anyway, there's obviously no need to do that. You already have exactly the comma-delimited string you want.
As you can see if you do a var_dump($_GET), the variable $_GET is a hashmap.
You can easily use a foreach loop to look through every member of it :
foreach($_GET as $get) // $get will successively take the values of $_GET
{
echo $get."<br />\n"; // We print these values
}
The code above will print the value of the $_GET members (you can try it with a blank page and dull $_GET values, as "http://yoursite.usa/?get1=stuff&get2=morestuff")
Instead of a echo, you can put the $_GET values into an array (or other variables) :
$array = array(); // Creating an empty array
$i = 0; // Counter
foreach($_GET as $get)
{
$array[$i] = $get; // Each $_GET value is store in a $array slot
$i++;
}
In PHP, foreach is quite useful and very easy to use.
However, you can't use a for for $_GET because it's a hashmap, not an array (in fact, you can, but it's much more complicated).
Hope I helped

How to use JSON with unknown multiple keys (PHP)

I am receiving a JSON String, which has multiple unknown keys. It's pretty hard to explain, because those JSON strings are pretty large, I'll try to break them down in the most efficient way.
I use PHP to break down the object, that I get, when I decode the JSON string.
$data1 = $json->result->map->12313214654[0]
$data2 = $json->result->map->12313214654[2]
$differentdata1 = $json->result->map->12313214655[0]
As you can see, there are different subsections after the map key.
Those are numbers, that are pretty random. And their appearance isn't regular either. So sometimes there's just one subsection (or number), and sometimes more.
How can I access them? I tried to use $datacount = $count($json->result->map) But it always displays 1. And then I still wouldn't be able to access the subelements of the map key.
Does anyone have a solution for this?
As you seem to have an unknown amount of data in array form, you could iterate your results with a foreach loop:
foreach ($json->result->map as $key => $dataArray) {
// $key will be the numeric key, e.g. 12313214654
// $dataArray will be the array of data you're after
foreach ($value as $dataIndex => $data) {
// $dataIndex is the position of $data within the $dataArray
// $data is the value you were trying to access with $json->result->map->12313214654[n]
// You do your work with $data here.
print_r($data);
}
}

Inserting textarea elements into MySQL from PHP

I need to get all the elements from a textarea in a HTML form and insert them into the MySQL database using PHP. I managed to get them into an array and also find the number of elements in the array as well. However when I try to execute it in a while loop it continues displaying the word "execution" (inside the loop) over a 1000 times in the page.
I cannot figure out what would be the issue, because the while loop is the only applicable one for this instance
$sent = $_REQUEST['EmpEmergencyNumbers'];
$data_array = explode("\n", $sent);
print_r($data_array);
$array_length = count($data_array);
echo $array_length;
while(count($data_array)){
echo "execution "; // This would be replaced by the SQL insert statement
}
you should use
foreach($data_array as $array)
{
//sql
}
When you access the submitted data in your php, it will be available in either $_GET or $_POST arrays, depending upon the method(GET/POST) in which you have submitted it. Avoid using the $_REQUEST array. Instead use, $_GET / $_POST (depending upon the method used).
To loop through each element in an array, you could use a foreach loop.
Example:
//...
foreach($data_array as $d)
{
// now $d will contain the array element
echo $d; // use $d to insert it into the db or do something
}
Use foreach for the array or decrement the count, your while loop
is a infinite loop if count is >0

Categories