unserialize problem - php

I'm facing a problem in unserialize the data from the database table. I'm serialized the data and saved into the table. When i'm retrieving the data i'm not able to get it properly. Below is my code .
$miscel = serialize(array($_POST['Prod_Price'],$_POST['Prod_Cond']));
I successfully inserted the data into the database. In the database table it looks like
s:38:"a:2:{i:0;s:4:"4444";i:1;s:6:"Middle";}
How i can retrieve the data properly?

What exactly is the problem? You should be able to simply call unserialize() to retrieve your data in its original form:
// assuming your database column 'foo' contains
// s:38:"a:2:{i:0;s:4:"4444";i:1;s:6:"Middle";}
$miscel = unserialize($row['foo']);
print_r($miscel);
// returns array([0] => 4444, [1] => 'Middle');
If the problem lies within the fact that the data being serialized is not very readable, you should consider storing the array keys as well:
$miscel = serialize(array('price' => $_POST['Prod_Price'], 'cond' => $_POST['Prod_Cond']));

$records = array(
'name'=>'abc',
'mobile'=>'1234566789',
'address'=>'test',
'email'=>'test#test.com');
$records_serialize = serialize($records);
echo "serialize<br/>";
print_r($records_serialize);
echo "<br/><br/>unserialize<br/>";
$records_unserialize = unserialize($records_serialize);
print_r($records_unserialize);
Here code to use serialize and unserialize
output
serialize
a:4:{s:4:"name";s:3:"abc";s:6:"mobile";s:13:"1234566789";s:7:"address";s:4:"test";s:5:"email";s:13:"test#test.com";}
unserialize
Array ( [name] => abc [mobile] => 1234566789[address] => test [email] => test#test.com )

http://nl2.php.net/manual/en/function.unserialize.php

You need to use the unserialize function. This will return every back into an array.

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

PHP: Trying to insert Twilio response JSON into MySQL TEXT field, but string is being truncated, possibly before the insert

Wordpress 5.3.2 and PHP 7.2 on localhost.
I'm sending a Twilio sms, and capturing the response from Twilio, which is JSON.
I want to store the response, because in it are all kinds of goodies, like the send date-time stamp.
When I make a test file, and print_r the response, it is a rather large JSON object. Not sure I should even post it here, at 11,568 characters. Here's a partial output (Acct values have been slightly altered):
Twilio\Rest\Api\V2010\Account\MessageInstance Object
(
[_media:protected] =>
[_feedback:protected] =>
[version:protected] => Twilio\Rest\Api\V2010 Object
(
[_accounts:protected] =>
[_account:protected] => Twilio\Rest\Api\V2010\AccountContext Object
(
[_addresses:protected] =>
[_applications:protected] =>
[_authorizedConnectApps:protected] =>
[_availablePhoneNumbers:protected] =>
[_calls:protected] =>
[_conferences:protected] =>
[_connectApps:protected] =>
[_incomingPhoneNumbers:protected] =>
[_keys:protected] =>
[_messages:protected] => Twilio\Rest\Api\V2010\Account\MessageList Object
(
[version:protected] => Twilio\Rest\Api\V2010 Object
*RECURSION*
[solution:protected] => Array
(
[accountSid] => AC3365f6c6dddaac48edfb902a3e1b8688d
)
[uri:protected] => /Accounts/AC3365f6c6dddaac48edfb902a3e1b8688d/Messages.json
)
[_newKeys:protected] =>
(etc., etc...)
My test code looks like this:
$data['numbers'] = array( "9541234567");// phone numbers of sms recipients. Just one for now.
$count = array();
for($i=0;$i<count($data['numbers']);$i++){
$args = array(
'number_to' => $data['numbers'][$i],
'message' => "This is a test.\n",
);
$sent = twl_send_sms( $args );
echo "<pre>";
print_r($sent);//This line outputs that beautiful, robust JSON string I am after.
echo "</pre>";
}
...so far, so good. The Twilio sms sends, and Twilio gives me a nice large response in JSON format.
Now, I transfer my code to the larger, production context, and I want to capture that 11,568 character JSON object, and store it in a table (by means of update). I think it should be a TEXT type, which is probably correct.
Here is my slightly revised code for production:
$data['twilio_response'] = twl_send_sms( $args ); //This sends the sms, captures a Twilio response into an array element.
$table = $wpdb->prefix . "npf_notifications";
$data['notification-update'] = $wpdb->update(
$table,
array('twilio_response' => $data['twilio_response']),
array('id' => $data['notifications-insert']['id']),
array('%s'),
array('%s')
);
$data['notification-update-query'] = $wpdb->last_query; // this records the query in an array element, so I can examine it.
Unfortunately for me, I don't get anything near as complete as the raw JSON from my test script. Instead, my Twilio response JSON looks like this:
notification-update-query = UPDATE `xsdslp_npf_notifications` SET `twilio_response` = '[Twilio.Api.V2010.MessageInstance accountSid=AC3365f6c6dceec35edfb902a3e1b8688d sid=SMfeb33b00895e455091445e4901547e70]' WHERE `id` = '5e092437a6037_1577657399'
...and the value of the array element to which I assign my Twilio response data looks like (after printing it out using javascript):
$data['twilio_response'] = [Twilio.Api.V2010.MessageInstance accountSid=AC3365f6c6ddaac48edfb902a3e1b8688d sid=SMfeddaac485e455091445e4901547e70]
It looks like the MySQL update (or insert) isn't the problem, but the JSON response string is being shortened in my array element variable. Can someone out there tell me what I'm doing wrong?
looks like you need to use json_encode() on $data['twilio_response'] first, because the returned object from twl_send_sms is not a JSON string, but a PHP object. Alternatively you can use serialize()

I have output like this array ( 'myField' => 'given value in text area', 'myCheckboxes' => array ( 0 => 'someValue1', 1 => 'someValue2', ), )

am getting all these values from a form submission .
i want to split these repeated values into separate variable and i want to store them into mysql DB.
this the output
array ( 'myField' => 'given value in text area',
'myCheckboxes' => array ( 0 => 'someValue1',
1 => 'someValue2', ),
)
i want to store each value into DB like this
myField = given value in text area
myCheckboxes1 = someValue1
myCheckboxes2 = someValue2
i tried code like this
<?php
$field = $_POST['myField'];
$checkValue1 = $_POST['myCheckboxes.(0)'];
$checkValue2 = $_POST['myCheckboxes.(1)'];
echo "$field"; //getting this output correctly
echo "$checkValue1"; //empty output
echo "$checkValue2"; //empty output
?>
(I'm reposting my comment as an answer since it seems that it solved the problem)
To see why you get empty values use var_dump($_POST) to see the full contents of the $_POST array (that is an useful debug technique for PHP).
You can get several outcomes:
Maybe the checkboxes are not grouped as an array, then you have a problem when you defined its name in the HTML.
Maybe there are grouped but with empty values, then you have a problem with the associated inputs or in the onsubmit() event.

Array of objects not altered after first file write

I have an empty array in a remote file but intend to momentarily add and alter objects in it. However, after adding an initial first set of objects, the array does not accept any more values. My error log reports unexpected 'Object' (T_STRING), expecting ')' meaning it regards the keyword "Object" as a string imputed by me so I guess the problem originates from my array structure. Here is the code I used in adding the objects
include 'all_users.php';
$francis_udeh = new Admin("francis_udeh");
$all_users['francis_udeh'] = $francis_udeh;
$victor_nwafor = new Member("victor_nwafor");
$all_users['victor_nwafor'] = $victor_nwafor;
$print_arr = print_r($all_users, TRUE);
$updated_arr = "<?php \n \$all_users = $print_arr; \n?>";
file_put_contents('all_users.php', $updated_arr);
returns the following in the remote file
<?php
$all_users = Array
(
[francis_udeh] => Admin Object
(
[name] => francis udeh
[pagename] => francis.udeh
[can_comment] => 1
[can_view_announcements] => 1
[profile_pic] => /blog/accounts/assets/user.png
[can_delete_comment] => 1
)
[victor_nwafor] => Member Object
(
[name] => victor nwafor
[pagename] => victor.nwafor
[can_comment] => 1
[can_view_announcements] => 1
[profile_pic] => /blog/accounts/assets/user.png
)
);
?>
(which, by the way, is what I want). However, when I try
include 'all_users.php';
$raheem_sadiq = new Member("raheem_sadiq");
$all_users['raheem_sadiq'] = $raheem_sadiq;
$print_arr = print_r($all_users, TRUE);
$updated_arr = "<?php \n \$all_users = $print_arr; \n?>";
file_put_contents('all_users.php', $updated_arr);
it returns the error I posted earlier resulting in the array not changing. What am I doing wrong?
You include all_users.php at the beginning of code, but after first file_put_contents() it's a not correct php code in this file.
As #Indra already mentioned: the output given by print_r() is human readable, but not valid php code. If you don't have the possibilty to pass the data via a data storage (like mysql), it might be a workaround to put it to the file with serialize(). Alternatively, you could also use json (as your objects seem to be data access objects of some same kind) and then instantiate the objects remotely.
Hope this helps,
Greetings

Check if value exists in array before inserting into database

I have an array that is returned from an API although some keys/values are not present all of the time.
example array
Array
(
[example0] => data
[example1] => data
[example2] => data
[example3] => data
)
Now if I use a query such as below
$dbh = $this->database->prepare("INSERT INTO table(example0, example1, example2, example3)VALUES(:example0, :example1, :example2, :example3)");
$dbh->execute(array(
"example0" => $data['example0'],
"example1" => $data['example1'],
"example2" => $data['example2'],
"example3" => $data['example3']
));
It will work fine. But when the API returns an array like
Array
(
[example0] => data
[example1] => data
[example3] => data
)
It will cause an error due to a value not being set, is there a way to just have it enter nothing into the column rather than throw an error? I am using a really big query for this so writing an if/else for each value would not be a good idea (in my opinion, for performance wise)
You have to check if the key is set and eventually is there is a value:
if(isset($array['your_key']) && !empty($array['your_key'])) { }
I cannot make it clear from your code but validate everything before you use it in a query.
[Edit] Example:
$keys = array('example1', 'example2', 'example3', 'example4');
$use_in_query = array();
foreach($keys as $key)
{
if(isset($array[$key]) && !empty($array[$key])) $use_in_query[$key] = $array[$key];
}
Now you can use the $use_in_query var in your query.
$dbh->execute($use_in_query);
[/Edit]

Categories