i want to display data from database and also i have created function in model file which is showing data from database but all values are shown in the array format.
problem is that when i print echo $values['title']; in foreach loop it is showing only first letter from title array??
model code
function reviewcitypage()
{
$cacheKey = 'city_page';
GigaCache::set(array('duration'=>"+1 minutes",'path'=>CACHE));
$cachedCategoryData = GigaCache::read($cacheKey);
if($cachedCategoryData && !cr('DynamicPage.field'))
{
$recentactivity = $cachedCategoryData;
}else
{
$recentactivity= $this->find("list",array("conditions"=>array("status"=>1),'fields'=>array('title','body','rating'),'recursive'=>-1,'limit'=>10));
//dont't set cache if dynamic field
if(!cr('DynamicPage.field'))
{
GigaCache::set(array('duration'=>"+1 minutes",'path'=>CACHE));
GigaCache::write($cacheKey,$recentactivity);
}
}
return $recentactivity;
}
view file
$ReviewObj = cri('Review');
$recentactivity = $ReviewObj->reviewcitypage();
foreach ($recentactivity as $name => $value){
foreach($value as $values)
{
echo $values['title'];
}
}
**problem is solved now thanks for support **
i have changed the code in model file and it is woking now
$recentactivity= $this-
>find("all",array("conditions"=>array("status"=>1),'recursive'=>-1,
'limit'=>10));
Your find() query is preparing the data as a 'list'. in cake lists are always key => value pair arrays. so in your view when you use the second foreach loop you are saying foreach character in a string...do.....
in your example $value can only be a string. foreaching it can only make $values a single char.
Let me know if you still unsure what i mean. not the best at explaining what i mean
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
Because you are after 3 fields I suggest using either first or all in place of list as the first argument in the find() method.
Related
I have a Wordpress build that uses CalderaWP forms. Unfortunately, the plugin's author has decided to store all checkbox entries as JSON arrays in the WP database and custom field values show up as "Array" instead of the actual text values.
I'd like to run a cron job that reformats these entries, but the first part is trying to figure out how to find and replace all values that are JSON objects.
I've written a function to get values from a specific table in the database, specifically the "wp_cf_form_entry_values" table. This function uses a regular expression in the SELECT query to find all values that begin with the "{" character. This is what I came up with to find JSON objects in the value field, but maybe there is a better way. Anyway, the function gets these values and reformats them from a JSON object to a list of individual items (i.e. various values that were checked in the submitted form).
Here is my current function:
function reformat_my_data() {
global $wpdb;
$data = $wpdb->get_results("SELECT value
FROM `wp_cf_form_entry_values`
WHERE `value` REGEXP '^[{].*$'
");
foreach($data as $key => $field) {
foreach($field as $val) {
if( is_json($val) ) {
$val = json_decode($val, true);
foreach($val as $checked) {
echo ' - ' . $checked . '<br/>';
}
}
}
}
}
reformat_my_data();
I also have another function to determine if the value is a JSON object:
function is_json($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
This works and outputs a list like this:
- checked #1
- checked #2
- checked #3
My question is: How do I get this newly formatted value back into the database? In other words, how do I do a mass replace of JSON type objects in the WP database?
My page grabs some records from a mssql DB, reads them into an array called $rows, with 3 columns:
ComputerName, Room, time_in_days
From $rows a second array is created (called $graph) with two columns, with the key being time_in_days from $rows, and the value column being a count of how often time_in_days occurred in the first array. The $graph array is used to create a number of HTML divs to give the impression of a graph.
I then want to be able to click on each individual div and using the $key value from the $graphs array, want to look up the rest of the information associated with all records in $rows where $graph[$key] matches $rows['time_in_days'] and display those records on the page.
But I have got stuck! I don't know where to put the function, the if statement(see code below) and at the moment, it doesn't even seem to be running the function. I don't even think I have the function code right. So if you could help with any of that I will very much appreciate it!
This is the code where the divs/graph is created:
foreach($graph as $key => $value){
$width = $value * $factor;
$page .= '<div style="width:40px;display:inline-block;">'.$key.'</div><div class="bar '.$key.'" style="width:'.$width.'px;"></div><div style="display:inline-block;margin-left:2px;">'.$value.'</div><br/>';
}
This is the function so far:
function SearchDays($key, $page, $rows) {
$computers = array();
foreach ($rows as $arr){
if ($key == $arr["time_in_days"]){
$computerName = $arr["ComputerName"];
$computers[$computerName] = $arr;
}
}
$page .= '<p>computers array from function SearchDays(): <pre>'.print_r($computers,true).'</pre></p>';
return;
}
And this is the if statement that makes the if statement that should run the function:
if (isset($_GET['barclick'])){
SearchDays($key, $page, $rows);
}
$page is just a variable that holds everything that is printed out onto the HTML page. The page itself can be seen here: cems.uwe.ac.uk/~s3-gupta/histogram/index.php. The whole page code can be got here: https://www.dropbox.com/s/h2q7x9xxtjbktx9/index.php
Thanks in advance. Please let me know if you need me to clarify things. I try and be as clear as possible on here, but usually don't manage it, so let me know if you need more.
I am getting a value from an input box in array. I want to post all this into a database with a single insert query so that all relevent data are inserted together in MySQL
Here is my code
foreach ($_POST['stop'] as $stopIndex => $stopValue) {
echo $stopname=$stopValue;
}
foreach ($_POST['timing'] as $timingIndex => $timingValue) {
}
foreach ($_POST['ampm'] as $ampmIndex => $ampmValue) {
}
Can anyone help me with correct code where to write insert query
This is example if you use codeigniter's way of fetching data.
Just prepare one array with appropriate keys (relevant to database keys you defined) and import it with the update_batch CI db method.
This is actually method like the one you can use in your model.
function save_something() {
$post_data = $this->input->post();
foreach ($post_data as $key => $value) {
$settings[] = array( 'key' => $key, 'value' => $value);
}
}
$this->db->update_batch('settings',$settings,'key');
return true;
}
Yes sure.
Assumed that you have something like the below.
<input type="text" name="variable1['key1']">
<input type="text" name="variable1['key2']">
Here variable1 is an array. When you submit, instead of using "for" OR "foreach" serialize it directly as:
$s = serialize($_POST['variable1']);
echo $s;
Your $s will be something like this:
"a:2:{s:6:"'key1'";s:6:"value1";s:5:"'bcd'";s:6:"value2";}"
The $s can be stored in a single column in the database (type can be text in DB).
While retrieving you can unserialize that column which converts back to array and you can use it easily.
Advantages, less number of records in DB, and in your front end you there is no need to use
looping statements.
UPDATED - TO ADD INTO DATABASE:
foreach ($_POST as $key)
{
$s = serialize($key);
mysqli_query("INSERT INTO `test`.`abc` (`id` ,`data`) VALUES (NULL , $s)");
}
Serialize value acts as a string, so the resultant will be number of records == number of arrays.
Im trying to fetch my form date in one for loop and then put the data into the database. My problem is that i have'nt worked that much with PHP myself and i cant figgure out how to put the data into the database.
Here is the code
<?php
function get_post_information() {
$inf[] = array();
foreach($_POST as $field => $value) {
$inf[$field] = $value;
}
return $inf;
}
I execute the code like this:
get_post_information();
But then what? How do i get this into my database?
Hope anyone can help :)
If you want to store the complete array in one single database column, you should use the serialize() function to make a string from your array. There also is an unserialize() function to convert it to an array again.
I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.
What would be the best way to loop through those items to get the values?
Here's what I have, which obviously isn't working.
extract($_POST);
$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop
while(${'item_name_' .$x} != '') {
echo ${'item_name' .$x};
$x++;
}
I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.
Thanks.
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
Use array-like fields:
<input name="name_for_the_items[]"/>
You can loop through the fields:
foreach($_POST['name_for_the_items'] as $item)
{
//do something with $item
}
If your post keys have to be parsed and the keys are sequences with data, you can try this:
Post data example: Storeitem|14=data14
foreach($_POST as $key => $value){
$key=Filterdata($key); $value=Filterdata($value);
echo($key."=".$value."<br>");
}
then you can use strpos to isolate the end of the key separating the number from the key.
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need