i struggling with forloop in MVC.
i want to pass data from input text where in data is equivalent to 1,2,3,4,5,6,7...... -that is from database.
i pass it to controller and get the data using $_POST method with name text1.
here is my controller code
{
$template = $this->loadView('view_display');
if(isset($_POST['check'])):
$text1= $_POST['text1'];
$text1= explode(',', $text1);
foreach($text1 as $text1):
$rem = $this->Faculty_model->testFunction($this->security_plugin->cleanInput($text1));
$template->set(['stud' => $rem, 'username' => $this->session_helper->get('username'), 'security'=> $this->security_plugin, 'url' => $this->url_helper]);
endforeach;
endif;
$this->security_plugin->CSRFToken();
$template->render();
here is my model
{
$sql="select * from table where id=:text1";
$bind = array(
':text1' => $text1
);
$data = $this->db->fetchAll($sql, $bind);
return $data;
}
and this is my view
<?php if(!empty($stud)): ?>
<?php foreach($stud as $stud): ?>
<?php echo $security->SanitizeString($stud->ID); ?>
<?php echo $security->SanitizeString($stud->NAME); ?>
<?php echo $security->SanitizeString($stud->AGE); ?>
The problem is it will only display the last number from text1 textbox. i cant figure it out.
anyhelp is appreciated :)
1.You need to define $rem as an array before foreach() and then do assignment of values.
2.Put $template->set() code outside of foreach()
$template = $this->loadView('view_display');
if(isset($_POST['check'])):
$text1= $_POST['text1'];
$text1= explode(',', $text1);
$rem = [];
foreach($text1 as $text1):
$rem[] = $this->Faculty_model->testFunction($this->security_plugin->cleanInput($text1));
endforeach;
$template->set(['stud' => $rem, 'username' => $this->session_helper->get('username'), 'security'=> $this->security_plugin, 'url' => $this->url_helper]);
endif;
$this->security_plugin->CSRFToken();
$template->render();
Related
Look at my code below, first, I want to combine three arrays together to create content in the foreach loop, and then create the final array by using the first array and the content string inside the foreach. It is kind of challenge for me, help, appreciate.
<?php
//above code, I deleted them, unnecessary to show
$fruit = explode(',',$fruit);
$type = explode(',',$type);
$date = explode(',',$date);
foreach (array_combine($fruit, $type, $date) as $fruit => $type => $date) {
echo $content = $fruit.'is'.$type.'at'.$date;
}
//create my final array
$total = array(
'date'=>$date,
'content'=>$content
);
?>
Please try:
<?php
$fruits = explode(',',$fruit);
$types = explode(',',$type);
$dates = explode(',',$date);
$total=array();
foreach ($fruits as $index=>$fruit) {
$type=$types[$index];
$date=$dates[$index];
echo $content = $fruit.'is'.$type.'at'.$date;
$total[]=array('fruit'=>$fruit,'date'=>$date,'type'=>$type,'content'=>$content);
}
?>
In CakePHP when I save the data with the below code, I get the data being saved as expected but I get all the data saved 2 times. The $lesson data variable does not retrieve 2 copies of the data so the save function is the problem. I tried using save in a loop and that gives the same problem. There must be something simple I am doing wrong.
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-save-array-data-null-boolean-validate-true-array-fieldlist-array
$data=array();
$i=0;
$this->Lessondata->cacheQueries = false;
$this->Lessondata->create( );
foreach ($lessons as $item):
// $this->Lessondata->cacheQueries = false;
$data[$i]['Lessondata']['lesson_id']=$item['Lesson']['id'];
$data[$i]['Lessondata']['st_id']=$item['Student']['id'];
$data[$i]['Lessondata']['tutor_id']=$item['Tutor']['id'];
$data[$i]['Lessondata']['student_name']=$item['Student']['first_name'].' '.$item['Student']['last_name'];
$data[$i]['Lessondata']['subject']=$item['Subject']['name'];
$data[$i]['Lessondata']['tutor_name']=$item['Tutor']['first_name'].' '.$item['Tutor']['last_name'];
$data[$i]['Lessondata']['class_year']=$item['Student']['class_year'];
// debug($data[$i]);
debug($i);
$i=$i+1;
endforeach;
$this->Lessondata->saveAll($data);
Try it.
$data = array();
foreach ($lessons as $item):
$data['Lessondata'][] = array(
'lesson_id' => $item['Lesson']['id'],
'st_id' => $item['Student']['id'],
'tutor_id' => $item['Tutor']['id'],
'student_name' => $item['Student']['first_name'] . ' ' . $item['Student']['last_name'],
'subject' => $item['Subject']['name'],
'tutor_name' => $item['Tutor']['first_name'] . ' ' . $item['Tutor']['last_name'],
'class_year' => $item['Student']['class_year'],
);
endforeach;
$this->Lessondata->create();
$this->Lessondata->saveAll($data);
This works but I need to check when the duplication starts. This is a bad answer as I am allowing for a quirk. As yet there is no other answer. I am happy to take this down if someone provides a working answer.
$this->Lessondata->create();
foreach ($lessons as $item):
$ff = $this->Lessondata->find('first', array(
'conditions' => array('Lessondata.lesson_id' => $item['Lesson']['id'])
));
if (!empty($ff)) {
debug($item);
break;
}
$data[$i]['Lessondata']['lesson_id'] = $item['Lesson']['id'];
$data[$i]['Lessondata']['st_id'] = $item['Student']['id'];
$data[$i]['Lessondata']['tutor_id'] = $item['Tutor']['id'];
$data[$i]['Lessondata']['student_name'] = $item['Student']['first_name'].' '.$item['Student']['last_name'];
$data[$i]['Lessondata']['subject'] = $item['Subject']['name'];
$data[$i]['Lessondata']['tutor_name'] = $item['Tutor']['first_name'].' '.$item['Tutor']['last_name'];
$data[$i]['Lessondata']['class_year'] = $item['Student']['class_year'];
$i = $i+1;
endforeach;
debug($data);
$this->Lessondata->saveAll($data);
I'm trying to pull out a json feed from a Wordpress query. I need the JSON to be formatted [{"id":"1","title":"title"},{"id":"2","title":"title2"}]
The json_encode function is not pulling out this specific format: Items are not separated by commas and I'm also missing the initial and final [ ]
I made this code echoing those missing elements, which works good, but the final comma, because of the echo is making the script reading it to fail.
<?php
$args = array(
'post_type' => 'location',
'posts_per_page' => -1
);
$locations = new WP_Query($args);
if($locations -> have_posts()):
echo '[';
while ($locations->have_posts()) : $locations->the_post();
$coords = get_field('coordinates');
$pid = get_the_ID();
$json["id"] = $pid;
$json["name"] = get_the_title();
$json["lat"] = $coords['lat'];
$json["lng"] = $coords['lng'];
$json["address"] = get_field('address');
$json["address2"] = get_field('address_2');
$json["city"] = get_field('city');
$json["state"] = get_field('state');
$json["postal"] = get_field('zip_code');
$json["phone"] = get_field('office_phone');
$json["fax"] = get_field('office_fax');
$json["web"] = apply_filters('the_permalink', get_permalink());
echo json_encode($json);
echo ',';
endwhile;
echo ']';
endif;
?>
I know that echoing those elements is not the correct way to do it, and I'm doing something wrong on the encode, that's why it's pulling out without the right formatting.
I have been researching for days and I couldn't find a way to create a json_encode echoing and at the same time controlling the fields that it will show from a wordpress query.
I appreciate in advance any solution/lead to solve this.
You're adding it wrong in your loop. What you want to do is create an array, and present that array as json.
if($locations -> have_posts()):
$data = array();
while ($locations->have_posts()) : $locations->the_post();
// add the location stuff to the $data array
$data[] = array(
'id' => $pid,
'name' => get_the_title(),
// etc....
);
endwhile;
// present your json
echo json_encode($data);
endif;
I'm new to the world of PHP and looking to see if there is a better way of writing this little code snippet that I have. Basically, it gives variables for some social media links, checks if they are empty, creates an array in a function and I call the array in a UL. I know its simple but I'm just looking if what I have is best or if I can improve on it any.
<?php
$facebook = of_get_option('facebook');
$twitter = of_get_option('twitter');
$youtube = of_get_option('youtube');
$linkedIn = of_get_option('linkedin');
$instagram = of_get_option('instagram');
$socialMediaLinks = array(
);
if (!empty($facebook)){
$socialMediaLinks[facebook] = $facebook;
}
if (!empty($twitter)){
$socialMediaLinks[twitter] = $twitter;
}
if (!empty($youtube)){
$socialMediaLinks[youtube] = $youtube;
}
if (!empty($linkedIn)){
$socialMediaLinks[linkedIn] = $linkedIn;
}
if (!empty($instagram)){
$socialMediaLinks[instagram] = $instagram;
}
function socialMediaList($value, $key){
echo '<li class="'.$key.'">'.$key.'</li>';
}
?>
<?php if (!empty($socialMediaLinks)){ ?>
<ul class="social-media">
<?php array_walk($socialMediaLinks, 'socialMediaList'); ?>
</ul>
<?php } ?>
You could shorten the code by simply doing:
$socialMediaLinks = array_filter(array(
'facebook' => of_get_option('facebook'),
'twitter' => of_get_option('twitter'),
'youtube' => of_get_option('youtube'),
'linkedIn' => of_get_option('linkedIn'),
'instagram' => of_get_option('instagram'),
));
This will automatically remove all empty entries, so you won't need that whole bunch of if-statements afterwards.
Try this:
<?php
$socialMediaItems = array(
'facebook' => of_get_option('facebook'),
'twitter' => of_get_option('twitter'),
'youtube' => of_get_option('youtube'),
'linkedin' => of_get_option('linkedin'),
'instagram' => of_get_option('instagram')
);
$socialMediaLinks = array();
foreach ($socialMediaItems as $key => $item) {
if ($item) {
$socialMediaLinks[$key] = $item;
}
}
function socialMediaList($value, $key){
echo '<li class="'.$key.'">'.$key.'</li>';
}
?>
<?php if (!empty($socialMediaLinks)){ ?>
<ul class="social-media">
<?php array_walk($socialMediaLinks, 'socialMediaList'); ?>
</ul>
<?php } ?>
Using array
<?php
$facebook = of_get_option('facebook');
$twitter = of_get_option('twitter');
$youtube = of_get_option('youtube');
$linkedIn = of_get_option('linkedin');
$instagram = of_get_option('instagram');
$socialMediaLinks = array();
$madeArray = array('facebook' => $facebook,'twitter' => $twitter,'youtube' => $youtube,'linkedin' => $linkedIn,'instagram' => $instagram);
foreach ($madeArray as $key => $value) {
if (!empty($value)) {
$socialMediaLinks[$key] = $value;
}
}
function socialMediaList($value, $key){
echo '<li class="'.$key.'">'.$key.'</li>';
}
?>
<?php if (!empty($socialMediaLinks)){ ?>
<ul class="social-media">
<?php array_walk($socialMediaLinks, 'socialMediaList'); ?>
</ul>
<?php } ?>
Better can be:
<?php
$socialmedia = array('facebook', 'twitter', 'youtube', 'linkedin' 'instagram');
$socialMediaLinks = array();
function GetOptions($name)
{
$value = of_get_option($name);
if (!empty($value))
$socialMediaLinks[$name] = $value;
}
foreach ($socialmedia as $smname)
GetOptions($smname);
function socialMediaList($value, $key){
echo '<li class="'.$key.'">'.$key.'</li>';
}
if (!empty($socialMediaLinks)){
?>
<ul class="social-media">
<?php array_walk($socialMediaLinks, 'socialMediaList'); ?>
</ul>
<?php
}
?>
I'd made something like this:
$social_networks = ['facebook', 'twitter', 'youtube', 'linkedin', 'instagram'];
$media_links = [];
foreach ($social_networks as $network) {
if ($option = of_get_option($network)) {
$media_links[$network] = $option;
}
}
// your code to output...
If you write simple application with short support time - your displaying style its normal. But if it something complex, you should look to MVC pattern.
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);
...