PHP echo last Array values - php

Im trying few hours repair my code but its always fail.
I have array in file:
$liquidyLista7 = array(
'Arbuz' => array(
'Wyraźny arbuz, soczysty arbuz, naprawde chyba najlepszy z oferty',
'Delikatny arbuz.',
'odświeżajacy arbuz',
'Bardzo delikatny, mniej wyrażny arbuz'
),
// and much more...
... i want to echo all values from each arrays but my "bad epic" code not work :/
function pokazOpisyVolish($liquidyLista7)
{
$i = 0;
$select = '<div id="volishPage'.$i.'" class="tab-pane fade"><ul class="comment-list">';
foreach($liquidyLista7 as $key => $record) {
$i++;
if (is_array($record)) {
$select .= '<li><p class="desc">'.$key.'</p>';
$select .= pokazOpisyVolish($record);
$select .= '</li>';
} else {
$select .= '<li><p class="desc">'.$record.'</p></li>';
}
}
$select .= '</ul></div>';
return $select;
echo pokazOpisyVolish($liquidyLista7);
Pls visit my test website and check how it works in "Mr Jack" (simple HTML - not PHP) but in "Volish" is my PHP code... :(

may be you are looking for some thing like this. the link you gave
uses plugin and css to display the result onto the webpage,
i can show you how to do it, but after that you have use your own css to display the result, i am thinking you might have add some div
name
just run this code in separate file, and you are good, understand what's happening and than add the div
<?php
$liquidyLista7 = array(
'Arbuz' => array(
'Wyraźny arbuz, soczysty arbuz, naprawde chyba najlepszy z oferty',
'Delikatny arbuz.',
'odświeżajacy arbuz',
'Bardzo delikatny, mniej wyrażny arbuz'
),
'newArtist' => array(
'Wyraźny arbuz, soczysty arbuz, naprawde chyba najlepszy z oferty',
'Delikatny arbuz.',
'odświeżajacy arbuz',
'Bardzo delikatny, mniej wyrażny arbuz'
)
);
//get the link from url
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
foreach ($liquidyLista7 as $key => $record) {
//ad artist name to the current url
echo "<a href=$actual_link?artistName=$key>$key</a><br>";
if(isset($_GET['artistName'])){
if(is_array($record)){
echo "<ul>";
foreach($liquidyLista7[$key] as $value)
if($_GET['artistName']==$key)
echo "<li>$value</li>";
}
echo "</ul>";
}
}
?>

Related

Updating multiple rows with select option

Database:
+------+------+
| id |status|
+------+------+
| 50 | 2 |
+------+------+
| 51 | 0 |
+------+------+
| 52 | 1 |
+------+------+
As you can see there is a column named id and another column named status which indicates the current status of sth (2=done, 1=in work, 0 = open)
So I have done a little GUI where you can choose the current status through an select option input field, it also preselects the current record for status.
function generateSelect($name = '', $options = array(), $default = '') {
$html = '<select name="'.$name.'">';
foreach ($options as $option => $value) {
if ($value == $default) {
$html .= '<option value='.$value.' selected="selected">'.$option.'</option>';
} else {
$html .= '<option value='.$value.'>'.$option.'</option>';
}
}
$html .= '</select>';
return $html;
}
As I have mentioned each number in the database stands for a text with its status
$statusArray=array("Done" => "2", "In Work" => "1","Open" => "0");
This is what the generation of all the select option fields for every id looks like:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$strStatus = generateSelect("stat", $statusArray, $row['status']);
echo '<tr><td>' . $row['id']. '</td><td>'.$strStatus.'</td></tr>';
What I am trying to do right now is that when the submit button is pressed it updates all status records.
What I have tried:
1.getting the selected one
function getSelected(){
$value="";
if($_POST['status']=="0")
$value="0";
else if($_POST['status']=="1")
$value="1";
else if($_POST['status']=="2")
$value="2";
else if($_POST['status']=="3")
$value="3";
return $value;
}
2. SQL statement where probably the problem is
$tmp = getSelected();
$sql = "UPDATE form SET status='$tmp' WHERE *";
Another option would be just saving the one edited, maybe with the onchange method from the select field?
Really appreciate every help I can get :) ty in advance for taking time to look throught the code.
UPDATE
ty for the quick answer and Extra Update #MarioZ
However it still doesnt seem rly to work. :/ maybe you can help me out there ^^
first worked fine with just $row['id'] because I want to be able to update more fields i have added ."['status']"
$strStatus = generateSelect($row['id']."['status']", $statusArray, $row['status']);
and also tried this for person, with no success then.
$personArray=array("Zivildiener" => "4", "Schmikl" => "3", "Poier" => "2","Dirnböck" => "1","Tom" => "0");
$strPerson = generateSelect($row['id']."['person']", $personArray, $row['person']);
and I have also added this which also worked fine, however only for status :/
foreach($_POST as $key => $value) {
$sql = "UPDATE form SET status='$value' WHERE id = $key";
$result = $conn->query($sql); }
Idk I honestly didnt really understand the foreach loop, but it worked somehow, you maybe need to know that there are more columns in the database which I didnt listen, but despite all this the first answer you gave worked perfectly, no clue how though :x so I would really appreciate your help again if you have some time :)
You need to pass the id of each row as the name of each select:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$strStatus = generateSelect($row['id'], $statusArray, $row['status']);
echo '<tr><td>' . $row['id']. '</td><td>'.$strStatus.'</td></tr>';
So, when you retrieve the $_POST data you have the id as key and the value of the option as value:
foreach($_POST as $key => $value) {
$sql = "UPDATE form SET status='$value' WHERE id = $key";
}
You can adapt your function getSelected() in that loop to ge sure no other value is injected in the query.
FINAL UPDATE:
This is a way to do what you want to do, I've wrote to be easy to understand and apply to your code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name="tasks" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<?php
// Names of fields
$status_list[] = "open";
$status_list[] = "in work";
$status_list[] = "done";
$person_list[] = "John";
$person_list[] = "Bran";
$person_list[] = "Edd";
$task_list[50] = "Kill enemies";
$task_list[51] = "Avenge father";
$task_list[52] = "Sleep";
// Database conection
$db = new mysqli("localhost", "root", "", "test");
// Update database only if post
if(!empty($_POST)) {
foreach($_POST as $key => $value){
if($db->query("UPDATE change_status SET status = {$value['status']}, person = {$value['person']} WHERE id = $key ")) {
echo "<span>".$key." - UPDATED!</span>";
} else {
echo "<span>".$key." - FAILED!</span>";
}
}
}
// Get database
$query = $db->query("SELECT * FROM change_status");
// Draw the HTML content
$form = "";
while($result = $query->fetch_array()) {
$form .= '<div>';
$form .= '<span>'.$task_list[$result['id']].'</span>';
$form .= ' - ';
$form .= '<select name="'.$result['id'].'[status]">';
foreach($status_list as $key => $value) {
$form .= '<option value="'.$key.'"';
$form .= $result['status'] == $key? " selected" : "";
$form .= '>'.$value.'</option>';
}
$form .= '</select>';
$form .= '<select name="'.$result['id'].'[person]">';
foreach($person_list as $key => $value) {
$form .= '<option value="'.$key.'"';
$form .= $result['person'] == $key? " selected" : "";
$form .= '>'.$value.'</option>';
}
$form .= '</select></div>';
}
echo $form; // display html content
?>
<input type="submit">
</form>
</body>
</html>

CakePHP pagination not working beyond 1st page

I have a view in my site that has two divs. one houses a search box and the other is where the result of the search is shown. by default, nothing is loaded on the result div. only when there is a search via post request, the result div is populated. However, this is causing problem with the pagination functionality as the second time the page loads, it doesnt have the data to go around with listing the rest of the results. How can i modify my controller/view to meet this need?
My action in the controller:
public function search(){
if($this->request->is('post')){
if($this->request->data['User']['search']!=null){
$search_name=$this->request->data['User']['search'];
$this->Paginator->settings = array(
'conditions'=>array('User.name LIKE'=>'%'.$search_name.'%'),
'order' => array('User.datetime' => 'desc'),
'limit' => 10
);
$feed = $this->Paginator->paginate('User');
$this->set('search_result',$feed);
}
else{
$this->Session->setFlash(__("Cant make an empty search"));
return $this->redirect(array('action'=>'search'));
}
}
}
My View:
<?php
include 'header.ctp';
echo '<div id="feed">';
echo $this->Form->create(null, array('url' => array('controller' => 'users', 'action' => 'search')));
echo $this->Form->input('search');
echo $this->Form->end('Search');
echo 'search by name';
echo '</div>';
if(isset($search_result)){
echo '<div id="tweet_records">';
if(!empty($search_result)){
foreach ($search_result as $user) :
$formatted_text;
$latest_tweet_time;
$formatted_time;
if(!empty($user['Tweet'])){
$formatted_text=$this->Text->autoLinkUrls($user['Tweet']['0']['tweet']);
$latest_tweet_time=$user['Tweet']['0']['datetime'];
$formatted_time;
if(strlen($latest_tweet_time)!=0){
$formatted_time='Tweeted at '.$latest_tweet_time;
}
else{
$formatted_time='No tweets yet';
}
}
else if(empty($user['Tweet'])){
$formatted_text='No tweets yet';
$formatted_time='';
}
echo '<table id="t01">';
echo'<tr>';
echo '<td>'.
$user['User']['name'].'#'.$this->HTML->link($user['User']['username'], array('controller'=>'tweets','action'=>'profile',$user['User']['id'])).'<br>'.$formatted_text.' '.'<br>'.'<font color="blue">'.$formatted_time.'</font>';
echo '<div id="delete">';
$selector='true';
foreach ($user['Follower'] as $follower) :
if($follower['follower_user_id']==AuthComponent::user('id')){
$selector='false';
echo $this->Form->postlink('Unfollow',array('controller'=>'followers','action'=>'unfollow',$user['User']['id']),array('confirm'=>'Do you really want to unfollow this person?'));
}
endforeach;
if($selector=='true' & $user['User']['id']!=AuthComponent::user('id')){
echo $this->Form->postlink('Follow',array('controller'=>'followers','action'=>'follow',$user['User']['id']));
}
echo '</div>';
echo '</td>';
echo '</tr>';
endforeach;
echo'</table>';
echo 'Pages: ';
echo $this->Paginator->prev(
' < ',
array(),
null,
array('class' => 'prev disabled')
);
echo $this->Paginator->numbers();
echo $this->Paginator->next(
' > ' ,
array(),
null,
array('class' => 'next disabled')
);
}
else{
echo '<font color="red"> No results found </font>';
}
echo '</div>';
}
You are searching for results only on post request. But when you press the next button you are making a get request. So the first if statement doen't return true so you are not passing any data to your view.
Even if you remove the first if statement for post you'll still won't see any data because the next button doesn't post any data to make true the second statement.
PS:
On CakePHP include is not a preferable thing to do. Also you haven't mentioned the version you are using.

How to make auto complete form in cakephp?

I am trying to make an auto complete function in CakePHP but did not succeed. I tried the following code.
public function find() {
if ($this->request->is('ajax')) {
$this->autoRender = false;
$country_name = $this->request->data['Country']['name'];
$results = $this->Country->find('all', array(
'conditions' => array('Country.name LIKE ' => '%' . $country_name . '%'),
'recursive' => -1
));
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
echo json_encode($results);
}
}
// Form and jquery
<?php
echo $this->Form->create('Country', array('action' => 'find'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->submit();
echo $this->Form->end();
?>
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'/countries/find',
minLength:2
});
});
</script>
foreach($results as $result) {
echo $result['Country']['name'] . "\n";
}
Breaks your JSON structure.
Keep in mind that autocomplete by default expects "label" and value keys in your JSON table, so all the script should do after fetching DB records is:
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['Country']['name'] , 'value' => $result['Country']['name'] );
}
echo json_encode($resultArr);
exit(); // may not be necessary, just make sure the view is not rendered
Also, I would create the URL to your datasource in the jQuery setup by
source:'<?=$this->Html->url(array("controller" => "countries","action"=> "find")); ?>',
And try to comment-out (just to make sure if the condition is not met by the request when autocomplete makes its call)
if ($this->request->is('ajax')) {
condition

Get current url excluding Included file names

I have a file named administrator1.php and inside it test.php is included. So code inside administrator1.php is
<?php include 'test.php'; ?>
I have a dynamic navigation menu inside test.php. Code is
<?php
$menu = array(
'users' => array('text'=>'USERS', 'url'=>'administrator1.php'),
'createProfile' => array('text'=>'CREATE PROFILE', 'url'=>'administrator2.php'),
'payment' => array('text'=>'PAYMENTS', 'url'=>'administrator3.php'),
'defense' => array('text'=>'DEFENSE', 'url'=>'administrator4.php'),
'progressReport' => array('text'=>'PROGRESS REPORT', 'url'=>'administrator5.php'),
);
class Nav {
function GenerateMenu($items) {
$html = "<ul>";
foreach($items as $item) {
if(stristr(__FILE__,$item['url'])===FALSE) {
$html .= "<li><a href='{$item['url']}' ><span><B>{$item['text']}</B></span> </a> </li>";
}
else {
$html .= "<li class='active'><a href='{$item['url']}' ><span><B>{$item['text']}.nnn</B></span> </a></li>";
}
}
$html .= "</ul>";
return $html;
}};
echo Nav::GenerateMenu($menu);
?>
And I have called the Nav method inside the same file.
Problem here is, the whole navigation bar will be printed, but selected item's ('USERS') CSS class active will not be called. But if I replace this whole code in administrator1.php file without including a test.php file it works fine. So I guess it is a problem to file path of the included file. And is it because I have used __FILE__ to get current path? Then how can I get current file path excluding included files names in the path?
For calling the static function we can use :: operator. But for accessing the non-static member of the class you should make the object, like -
$nav_ob = new Nav();
echo $nav_ob->GenerateMenu($menu);
And there s problem, when you are creating array -
$menu = array(
'users' => array('text'=>'USERS', 'url'=>'administrator1.php'),
'createProfile' => array('text'=>'CREATE PROFILE', 'url'=>'administrator2.php'),
'payment' => array('text'=>'PAYMENTS', 'url'=>'administrator3.php'),
'defense' => array('text'=>'DEFENSE', 'url'=>'administrator4.php'),
'progressReport' => array('text'=>'PROGRESS REPORT', 'url'=>'administrator5.php'), //Here
);
Comma after the last element. It should be -
$menu = array(
'users' => array('text'=>'USERS', 'url'=>'administrator1.php'),
'createProfile' => array('text'=>'CREATE PROFILE', 'url'=>'administrator2.php'),
'payment' => array('text'=>'PAYMENTS', 'url'=>'administrator3.php'),
'defense' => array('text'=>'DEFENSE', 'url'=>'administrator4.php'),
'progressReport' => array('text'=>'PROGRESS REPORT', 'url'=>'administrator5.php')
);
UPDATED
<?php
$menu = array(
'users' => array('text'=>'USERS', 'url'=>'administrator1.php'),
'createProfile' => array('text'=>'CREATE PROFILE', 'url'=>'administrator2.php'),
'payment' => array('text'=>'PAYMENTS', 'url'=>'administrator3.php'),
'defense' => array('text'=>'DEFENSE', 'url'=>'administrator4.php'),
'progressReport' => array('text'=>'PROGRESS REPORT', 'url'=>'administrator5.php')
);
class Nav {
function GenerateMenu($path, $items) {
$html = "<ul>";
foreach($items as $item) {
if(stristr($path,$item['url'])===FALSE) {
$html .= "<li><a href='{$item['url']}' ><span><B>{$item['text']}</B></span> </a> </li>";
}
else {
$html .= "<li class='active'><a href='{$item['url']}' ><span><B>{$item['text']}.nnn</B></span> </a></li>";
}
}
$html .= "</ul>";
return $html;
}};
?>
And on each administrator.php file after including the above php file call the method like -
$nav_ob = new Nav();
echo $nav_ob->GenerateMenu(__FILE__, $menu);
Hope this will help.
Found the answer!
Replaced __FILE__ with $_SERVER["PHP_SELF"]. So the code is;
class Nav {
function GenerateMenu($items) {
$html = "<ul>";
foreach($items as $item) {
if(stristr($_SERVER["PHP_SELF"],$item['url'])===FALSE) {
$html .= "<li><a href='{$item['url']}' ><span><B>{$item['text']}</B></span> </a> </li>";
}
else {
$html .= "<li class='active'><a href='{$item['url']}' ><span><B>{$item['text']}.</B></span> </a></li>";
}
}
$html .= "</ul>";
return $html;
}};
$nav_ob = new Nav();
echo $nav_ob->GenerateMenu($menu);
Now it works as i wanted! Thank you everyone for the help given!

dynamically changing CSS background-image

I'm fairly new to both PHP and Javascript, so please forgive my ignorance and poor use of terminology, but I'll do my best to explain exactly what I'm struggling to achieve.
I have information stored in a PHP array that I call to my index page using the function below (the code below is in a separate PHP file called articles.php that's included in my index.php) :
<?php
function get_news_feed($article_id, $article) {
$output = "";
$output .= '<article class="img-wrapper">';
$output .= '<a href="article.php?id=' . $article_id . '">';
$output .= '<div class="news-heading">';
$output .= "<h1>";
$output .= $article["title"];
$output .= "</h1>";
$output .= "<p>";
$output .= "Read more...";
$output .= "</p>";
$output .= "</div>";
$output .= '<div id="news-img-1">';
$output .= "</div>";
$output .= "</a>";
$output .= "</article>";
return $output;
}
$articles = array();
$articles[] = array(
"title" => "Andy at NABA",
"description" => "Docendi, est quot probo erroribus id.",
"img" => "img/gym-01.jpg",
"date" => "05/04/2013"
);
$articles[] = array(
"title" => "Grand Opening",
"description" => "Docendi, est quot probo erroribus id.",
"img" => "img/gym-01.jpg",
"date" => "05/04/2013"
);
?>
My index.php looks like the following minus some HTML that plays no role in this process:
<?php
include("inc/articles.php");
?>
<?php
$pageTitle = "Home";
include("inc/header.php");
?>
<section class="col-4 news">
<?php
$total_articles = count($articles);
$position = 0;
$news_feed = "";
foreach($articles as $article_id => $article) {
$position = $position + 1;
if ($total_articles - $position < 2) {
$news_feed .= get_news_feed($article_id, $article);
}
}
echo $news_feed;
?>
</section>
I am aiming to dynamically change the CSS Background-Image property of the div element with ID news-img-1 using Javascript.
I have tried such things as:
document.getElementById('news-img-1').style.backgroundImage = 'url('<?php $article["img"]; ?>')';
document.getElementById('news-img-1').style.backgroundImage = 'url('http://www.universalphysique.co.uk/' + '<?php $article["img"]; ?>')';
document.getElementById('news-img-1').style.backgroundImage = 'url('window.location.protocol + "//" + window.location.host + "/" + '<?php $article["img"]; ?>')';
.....but I'm getting nowhere!! My code in practise works because the following Javascript inserts an image correctly:
document.getElementById('news-img-1').style.backgroundImage = 'url("img/gym-01.jpg")';
Here is my site up and running, the images should be placed in the empty circles you'll see! Any help would be great, this ones tough for me!!
comparing the hard coded javascript to ones that don't work, I notice that you are not including the double-quotes around the <?php $article["img"]; ?> snippet. The hard coded one shows
= 'url("img/gym-01.jpg")'
but the ones with the php snippet will produce
= 'url(img/gym-01.jpg)'
so perhaps if you modify it to
document.getElementById('news-img-1').style.backgroundImage = 'url("'<?php $article["img"]; ?>'")';
OR
edit the get_news_feed function as follows:
replace these lines
$output .= '<div id="news-img-1">';
$output .= "</div>";
with
$output .= '<div class="news-img"><img src="' . $article["img"] . '"></div>' ;
and change your css like so:
article.img-wrapper {
position: relative;
}
div.news-img {
position: absolute;
top: 0;
z-index: -1000;
}
OR
Modify your get_news_feed function, change the statement for the <div id="news-img-1"> output to include a data-url attribute like:
$output .= '<div class="news-img" data-url="' . $article["img"] . '">';
Then add a jquery statement like:
$(".news-img").each( function() {
$(this).css("background-image", "url(" + $(this).data("url") +")" );
});
The jquery statement goes in a static js file as opposed to generating the script in php.
You need to remove the quotes from your PHP tags and see if it works!
Do it like this:
document.getElementById('news-img-1').style.backgroundImage = 'url(' + <?php $article["img"]; ?> + ')';
Hope it helps.

Categories