Using a foreach inside an array - php

I am trying to use codeigniter's active record class to fetch a value from the database that i need to insert to a table with this code
$q = $this->db->get('center_number');
$cd = $this->db->get('running_tasks');`
$ask_for_permission = array(
'messagefrom' => $le_message_from,
'messageto' => foreach ($q->result() as $row)
{
$row->center_number;
},
'messagetext' => 'The dataset'. '' .foreach ($cd->result() as $row)
{
$row->task_name;
}. ' is requesting permission to credit the account.Reply with yes to allow or no to decline.Anything else other than yes or no shall be ignored.'
);
I get the error:
unexpected 'foreach'
How can I fetch the record from the database from within $ask_for_permission array?.

// First Generate the Array
$ask_for_permission = array(
'messagefrom' => $le_message_from,
'messageto' => '',
'messagetext' => 'The dataset'. '' .foreach ($cd->result() as $row)
{
$row->task_name;
}. ' is requesting permission to credit the account.Reply with yes to allow or no to
decline.Anything else other than yes or no shall be ignored.'
);
// Second, populate it with all values of the $q->result() array
foreach ($q->result() as $row)
{
$ask_for_permission['messageto'] .= $row->center_number;
}

Try this
function msgTo() {
$str = '' ;
foreach ($r->result() as $row) {
$str .= $row;
}
return $str;
}
and replace your foreach with msgTo()

I solved it this way
$q = $this->db->get('center_number');
$le_message_from = '08009898';
$ask_for_permission = array(
'messagefrom' => $le_message_from,
'messageto' => $q->row->center_number,
'messagetext' => 'The dataset'. ' '. $this->db->query("select task_name from running_tasks limit 1")->row()->task_name .' '.'is requesting permission to credit the account.Reply with yes to allow or no to
decline.Anything else other than yes or no shall be ignored.'
);
$this->db->insert('messageout', $ask_for_permission);

Related

json_decode showing no data

I'm using below logic to store data in JSON format in MySQL using PHP.
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
session_start();
$date = new Date();
$modified = $date->getDate();
$query = ' UPDATE pages SET last_updated_user_author_id = "'.$_SESSION['user_id'].'", data = "'.htmlentities($store, ENT_QUOTES).'", modified = "'.$modified.'" WHERE id = "'.$pageID.'" ';
Then while decoding the data i'm using below logic:
$query = ' SELECT data FROM pages WHERE id = "'.$_POST['pageID'].'" ';
$connection = $this->establish_connection();
$data = $connection->query($query);
$connection->close();
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$var = html_entity_decode($row['data']);
echo json_decode($var);
}
}
While json_decode it shows no data in response, when i did var_dump it shows null, but if i did not do json_decode and only used html_entity_decode() i get below output
{"page_base_url":"http://www.myblog.com/about/contact/"}{"page_url_revision":"http://www.myblog.com/about/contact/"}{"page_url_alternate":"http://www.myblog.com/about/contact/"}{"page_url_shortlink":"http://www.myblog.com/about/contact/"}{"page_url_canonical":"http://www.myblog.com/about/contact/"}{"page_title":"Example | Contact"}{"page_name":"Example Contact"}{"page_type":"WebSite"}{"page_meta_description":"Want to get in touch with us? You're on the correct page, you can get in touch with us by filling the form below. We will get in touch with you with 24 hours."}{"page_keywords":["example","contact","support","help","getintouch","feedback","bug","updates"]}
I'm not sure where i'm going wrong, could anybody help me out here?
I want to give an eccho in json_encode format as a response to ajax call. i use below logic to do so
echo json_encode(
array(
"type" => "error",
"status" => "Error While Retrieving Data!",
"message" => $error
)
);
I think you need something like:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[] = array($value[1] => $value[2]);
else
$store[] = array($value[1] => trim($value[2]));
}
$save = json_encode($store);
or even (if your $value[1] is always unique within the loop)
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
$save = json_encode($store);
then use $save to store in your table. I'm not 100% on that, though.
The string you've shown is not valid JSON. If you wanted to store a list of objects like that in JSON format, they need to be within an array, and separated by commas. Otherwise they are just unrelated individual objects and cannot be decoded as a single block of JSON.
Therefore you need to build an array in PHP and then encode the whole thing at the end. Something like this:
$storedata = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$storedata[] = array($value[1] => $value[2]);
else
$storedata[] = array($value[1] => trim($value[2]));
}
$jsondata = json_encode($storedata);
And then use $jsondata in your SQL statement.
Your problem is your "saving" to the database. You encode every key-value-pair in an own json-string and concat those json-strings.
Your snippet
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
Yields $store = "{key1:value1}{key2:value3}{key3:value3}". Note all the brackets, you have 3 distinct json-objects with a single key-value pair in your string, instead of one json-object with 3 key-value-pairs.
However, I assume you want a single json-object with the key-value-pairs as result like the folling?
$store = "{
key1:value1,
key2:value2,
key3:value3
}";
If so, you need to build your array differently:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
And please, for the safety of everyone, your code is vulnerable of sql-injections. Please fix that, too.

Error "indirect modification of overloaded property has no effect " when attempting to update array

I'm attempting to update a nested array in php. However, my updates have no effect. Here's the relevant code:
foreach($form["fields"] as $field){
Populate Checkbox Fields
if($field['type'] == 'checkbox'){
$inputs = $field['inputs'];
$count = '0';
foreach($inputs as $input){
if(($user_meta[$input['id']] !== '') && (isset($user_meta[$input['id']]))){
$select = true;
}
else{
$select = false;
}
$field['choices'][$count] = array( 'text' => $field['choices'][$count]['text'], 'value' => $field['choices'][$count]['value'] , 'isSelected' => $select );
$count = $count + '1';
}
}
}
I've tried a few different workarounds after searching for this error, but none of them seem effective. I'm grateful for any help anyone can offer.
Just use a reference & for $field with your existing code:
foreach($form['fields'] as &$field){
Alternately, use the key and modify the main array:
foreach($form['fields'] as $key => $field){
// later in the code
$form['fields'][$key]['choices'][$count] = array( /* ... */ );

bulk PHP isset generator

I just joined a project developed in plain php ( As in no frameworks). I have a table that has 213 fields and according to the guidelines i have to do an isset, prepare string, prepare number for 212 fields.
This is a lot of repetitive code and most of the tables in this system are huge. As such i would like to save time by developing an isset generator but before I go re-inventing the wheel i would like to ask: Can anyone point me in the direction of such a generator that returns the isset code? Something similar to http://www.fpmgonline.com/mysql_insert.php
Edited to add code
Supposing $data is my $_POST array , instead of checking many fields one by one I wanted to generate a bulk isset code
Here's is some sample code
<?php
$data = Array('name' => 'Sample name', 'desc' => 'Sample description');
if (isset($data['name'])) {
$name = trim($data['name']);
} else {
$return[] = ' Name code is required';
}
if (isset($data['desc'])) {
$desc = trim($data['desc']);
} else {
$return[] = ' Description is name is required';
}
if (isset($data['age'])) {
$age = trim($data['age']);
} else {
$age = 0;
}
?>
Thank you.
There is no need for "generating" code. That's why you have data structures, loops and conditionals in programming languages.
$data = Array('name' => 'Sample name', 'desc' => 'Sample description', 'age' => 'Foo bar');
$defaults = Array('age' => 0);
$messages = Array('name' => ' Name code is required', 'desc' => ' Description is name is required');
for($data as $key => $val) {
if (isset($data[$key])) {
$$key = trim($data[$key]);
} else if (isset($defaults[$key])) {
$$key = $defaults[$key];
} else {
$return[] = $messages[$key];
}
}
The need to use variable variables ($$key) here also is plain wrong. When working with "dynamic" data you should not need to work with a separate variable for each item. I'd refactor that into this:
$clean_data = Array();
for($data as $key => $val) {
if (isset($data[$key])) {
$clean_data[$key] = trim($data[$key]);
} else if (isset($defaults[$key])) {
$clean_data[$key] = $defaults[$key];
} else {
$return[] = $messages[$key];
}
}
Also $data should not be whatever comes from $_POST. It should be everything that's in your fields list and then check if it's present in $_POST, so that you don't end up running arbitrary code based on user input.
I did a simple one for the isset:
$data = Array('name' => 'Sample name', 'desc' => 'Sample description');
bulkisset($data, 'name,description,age');
function bulkisset($data, $table_fields) {
$code = '';
$inputs = explode(',', $table_fields);
foreach ($inputs as $key) {
$code .= '<br/>if (isset($data["' . $key . '"])){'
. '$name = trim($data["' . $key . '"]);} else {$' . $key . ' ="";};';
}
echo $code;
}
This might not be the best way to check data but with my hands tied I think this will save me some time.

how to merge keys with same value?

code;
$all_tags = array();
while ($row = mysql_fetch_assoc($result)) {
$all_tags = array_merge($all_tags, explode(' ', $row['title']));
}
$all_tags = array_count_values($all_tags);
echo "<pre>";
arsort($all_tags);
foreach ($all_tags as $key => $val) {
echo "$key = $val\n";
}
output;
fuups! = 7
401 = 5
Authorization = 5
Required = 5
, = 3
izle = 3
Error = 2
Server = 2
Internal = 2
500 = 2
Full = 1
MegaSinema.net = 1
Sinema = 1
Bad = 1
Request = 1
Film = 1
400 = 1
all i wanna do is merge 'keys' with same integer 'value'. example;
401 = 5
Authorization = 5
Required = 5
to
401 Authorization Required = 5
i don't know how could i do it. i tried a bunch of ways but i never let it work. thank you.
I misunderstood you in the beginning.
I think you could just save the objects in an array and implode them if needed.
$out = array();
foreach($array as $key=>$value)
if(array_key_exists($value, $out))
$out[$value][] = $key;
else
$out[$value] = array($key);
// Then you could do
echo implode(" ", $out[5]); // Should output "401 Authorization Required"
Working example at http://codepad.org/MgLKXA75
Another option is to directly append it and trim the "extra" space at the end.
$out = array();
foreach($array as $key=>$value)
if(array_key_exists($value, $out))
$out[$value] .= $key . ' ';
else
$out[$value] = $key . ' ';
// Then you could do
echo trim($out[5]); // Should output "401 Authorization Required"
Try this
<?php
$data = array('fuups!' => '7','401' => '5','Authorization' => '5','Required' => '5',',' => '3','izle' => '3','Error' => '2','Server' => '2','Internal' => '2','500' => '2','Full' => '1','MegaSinema.net' => '1','Sinema' => '1','Bad' => '1','Request' => '1','Film' => '1','400' => '1');
$rows = array();
$values = array_values($data);
asort($values);
$highestVal = $values[0];
for ($i = 0; $i <= $highestVal; $i++) {
foreach ($data as $key => $value) {
if ($i == $value) {
$rows[$i] = $rows[$i] . " {$key}";
}
}
}
?>
Working Example XD http://codepad.org/x9uHs1sp
EDIT----
To echo all keys, just replace var_dump($rows) with:
foreach ($rows as $key) {
echo "{$key}<br />";
}
I'm not familiar with PHP, but I think you can try to create a hash table to handle this.
For example, if you insert above 3 items into the hash table and use '5' as the key, the first item can be inserted correctly, and the other two should throw exceptions. You can catch the exception since it's excepted and append the values to the value of the first item. So the item in you hash table should be like:
key: 5
value: 401 Authorization Required
But you should make sure about the orders in the value.
Just my 2 cents, good luck!
Update:
If throwing exception is not acceptable, you can look-up a key in the hash table first, if the key doesn't exist then insert the key and value, if it already exists then append the value to existing item value.

PHP adding foreach to my array

I would like to append html to an item in my array before echoing it on my page and am unsure how to go about doing it.
My data is put into an array like so:
$query = $this->db->get();
foreach ($query->result() as $row) {
$data = array(
'seo_title' => $row->seo_title,
'seo_description' => $row->seo_description,
'seo_keywords' => $row->seo_keywords,
'category' => $row->category,
'title' => $row->title,
'intro' => $row->intro,
'content' => $row->content,
'tags' => $row->tags
);
}
return $data;
I would like to perform the following on my 'tags' before returning the data to my view:
$all_tags = explode( ',' , $row->tags );
foreach ( $all_tags as $one_tag ){
echo '' . $one_tag . '';
The reason for doing this is that the tags in my database contain no html and are simply separated by commas like so news,latest,sports and I want to convert them into
sports ...
My reason for doing this here rather than when I echo the data is that I don't want to repeat myself on every page.
You could just create a function to be used everyhwere you are including tags in your output:
function formatTags($tags) {
$tmp = explode(',', $tags);
$result = "";
foreach ($tmp as $t) {
$result .= sprintf('%s',
urlencode(trim($t)), htmlentities(trim($t)));
}
return $result;
}
And whenever you do something like echo $tags; you do echo formatTags($tags); instead. View code should be separated from model code, which is why I would advise to not put HTML inside your array.
Well first of all you're overwriting $data with every run of the loop so only the final result row will be listed.
Once that's out of the way (fix with $data[] = ...), try this:
...
'tags' => preg_replace( "/(?:^|,)([^,]+)/", "$1", $row->tags);
...

Categories