on my website I currently have a save to 'favorites' button which saves a recipe to the users favorites and displays their favorites on their dashboard. I have managed to display the favorites on their dashboard with hyperlinks surrounding them. However I can't quite figure out how to actually connect each favorite to its link.
Below is the code to retrieve the favorites stored on the database.
$favs = array();
$links = array();
$sql = "SELECT * FROM recipe WHERE fav='yes'";
$records = mysql_query($sql);
while($result =mysql_fetch_assoc($records)){
$favs[] = $result['recipeName'];
$links[] = $result['url'];
}
I have also saved the url of each recipe on my database, so just need to print out each favorite with the link to their url.
below is the code to display the favourites surrounded by a tags. I have also managed to return the url links from the database but just need to conect them to each recipe.
foreach ($favs as $fav) {
echo '<a href=''>'.$fav.'</a>'.' ';
}
You don't need foreach loop and opening blank arrays here:
while($result =mysql_fetch_assoc($records)){
echo 'Go to '.$result['recipeName'].'';
}
I suggest you put the recipeName and the URL in a single array.
e.g.
$i = 0;
while($result =mysql_fetch_assoc($records)) {
$fav_links[i] = array('recipeName' => $result['recipeName'], 'url' => $result['url']);
}
Then in your foreach:
foreach ($fav_links as $fav) {
echo ''.$fav["recipeName"].''.' ';
}
Related
I've started to code in April 2021 so I'm super new to this. Working on my final exam, I'd need your precious help! I want to generate a dynamic list from a database, containing 2 joined tables (users and interest). The 2 tables both contain "ID_user" which links them as a foreign key. The idea is that one the user is logged in, the profile page displays all the interests the user selected at sign up. At the moment I can only display the last interest selected and not all of them.
Here is my php:
$request2 = "SELECT `interest`.`name_Interest`
FROM `interest`
INNER JOIN `users`
ON `interest`.`ID_user` = `users`.`ID_user`
WHERE `pseudo` = '".$url_pseudo."'
";
$resultat2 = mysqli_query($connexion, $request2) or die (mysqli_error($connexion));
$nb_resultat2 = mysqli_num_rows($resultat2);
if ($nb_resultat2 > 0) {
while ($row = mysqli_fetch_array($resultat2)){
$name_Interest = $row["name_Interest"];
}
}
Here is the HTML displaying the response:
enter image description here
Here is my db:
enter image description here
Any idea why I can get only 1 value?
enter image description here
thanks in advance
Your while loop is writing to the same variable for each iteration of the loop;
while ($row = mysqli_fetch_array($resultat2)){
$name_Interest = $row["name_Interest"];
}
This will leave $name_Interest containing the last value from your database after the loop has completed.
To resolve this, you will need to keep a list of interest names - this can be achieved by using an array. PHP Array Documentation
// Declares the empty array
$interests = [];
// Loop through database results
while ($row = mysqli_fetch_array($resultat2)){
// Add this value to the array
$interests[] = $row["name_Interest"];
}
Now, $interests will hold all of the values from the database!
You will need to print these out differently in your HTML, by looping through all the values in the array and printing one at a time:
(PHP foreach documentation)
<ul>
<?php foreach ($interests as $interest) { ?>
<li><?php echo $interest; ?></li>
<?php } ?>
</ul>
Solution
Simple store all user interests on array and then show in iteration on page.
Code:
$user_interests=array();
while ($row = mysqli_fetch_array($resultat2)){
$user_interests[] = $row["name_Interest"];
}
Now $user_interests array holds all interests of users as a result of join.
At last loop over it
<?php foreach ($user_interests as $interest) { ?>
<p><?php echo $interest; ?></p>
<?php } ?>
Working on a website where you can add news, that data gets sent to a database and then converted to json, which is used in an app.
I'm having trouble with filtering the news using the url. I want to be able to filter news by 2 database columns, Type and Region. When I add the news I need to specify which type[can only choose 1] of news it is and in what region[can choose multiple] it goes under. Now when i'm in the app, let's say I want to only see "Emergency" news from "X" region. For that I would check "Emergency" type checkbox and "X" region checkbox.
With my current code I can filter the news by type perfectly, but im having trouble adding an extra filter to only show X region news.
<?php
function turnIntoUTF8($arrayName) {
if (is_array($arrayName)) {
foreach ($arrayName as $k => $v) {
$arrayName[$k] = turnIntoUTF8($v);
}
} else if (is_string ($arrayName)) {
return utf8_encode($arrayName);
}
return $arrayName;
}
$tag = $_GET["tag"];//Tag = type
//Tried adding a new GET here.
$sql = "SELECT * FROM news WHERE
FIND_IN_SET(`tag`, '$tag')//Tried to do another FIND_IN_SET here with &&.
ORDER BY id DESC";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode(turnIntoUTF8($emparray));
mysqli_close($connection);
?>
Currently I can use this url: http://localhost/vvuudised/getNewsJson.php?tag=uudis,teade to show only news that have their type set as "uudis" or "teade. The outcome is the following:
Now if I wanted to I would filter the news to only show lets say "rohuneeme" region news with the url. How can I do that. Thanks and sorry for the bad explanation.
Thank you for reading this and for your help in advance.
I got a simple Book-Catalogue /procedure code/, every visitor can see the book catalogue and click through out the books and check their authors BUT I've got an idea to add a feature that allows the users to write a comment to each book ONLY if they're logged. So I added a session variable $_SESSION['isLogged']. But there is a lot of code blocks that duplicates. What I need is an advice, what to do with this duplicated blocks of code. What the good practice says? And my code below is from one of the 6 files that I got. In everyfile I got this repeating of code.
So here's my code:
if (!isset($_SESSION['isLogged'])) {
echo '<div class="user-navigation">
<a href="register.php" class="user-nav" >Register now</a>
Log in
</div>
<div class="navigation1">
Add book
Add author
</div>';
$booksAndAuthors = mysqli_query($connection, 'SELECT DISTINCT * FROM books LEFT JOIN books_authors ON books.book_id=books_authors.book_id LEFT JOIN authors ON authors.author_id=books_authors.author_id');
$result = array();
while ($resultArr = mysqli_fetch_assoc($booksAndAuthors)) {
$result[$resultArr['book_id']] ['book_name'] = $resultArr['book_title']; // Reodering array
$result[$resultArr['book_id']] ['author'][$resultArr['author_id']] = $resultArr['author_name']; // Reordering array
}
echo '<table class="table"><tr><th>Book name</th><th>Author</th></tr>'; // Open table html table tags
foreach ($result as $k=>$b) { // Foreach the result array to get the book_name
echo '<tr><td>' . $b['book_name'] . '</td><td>';
$data = array(); // Create an empty array in order to fill the data inside
foreach ($b['author'] as $k => $a) { // Foreach the nested array with the authors to get the author_name displayed
$_GET['author_name'] = $a;
$data[] = '' . $a . ''; // Link is chosen by the author_id
}
echo implode(', ', $data); // Add a comma after every record
echo '</td></tr>'; // Close table cell and row
}
exit;
echo '</table>'; // Close html table tag
}
else {
echo '<div class="user-navigation">
My Profile
Log out
</div>
<div class="navigation2">
Add book
Add author
</div>';
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$booksAndAuthors = mysqli_query($connection, 'SELECT DISTINCT * FROM books LEFT JOIN books_authors ON books.book_id=books_authors.book_id LEFT JOIN authors ON authors.author_id=books_authors.author_id');
$result = array();
while ($resultArr = mysqli_fetch_assoc($booksAndAuthors)) {
$result[$resultArr['book_id']] ['book_name'] = $resultArr['book_title']; // Reodering array
$result[$resultArr['book_id']] ['author'][$resultArr['author_id']] = $resultArr['author_name']; // Reordering array
}
echo '<table class="table"><tr><th>Book name</th><th>Author</th></tr>'; // Open table html table tags
foreach ($result as $k=>$b) { // Foreach the result array to get the book_name
echo '<tr><td>' . $b['book_name'] . '</td><td>';
$data = array(); // Create an empty array in order to fill the data inside
foreach ($b['author'] as $k => $a) { // Foreach the nested array with the authors to get the author_name displayed
$_GET['author_name'] = $a;
$data[] = '' . $a . ''; // Link is chosen by the author_id
}
echo implode(', ', $data); // Add a comma after every record
echo '</td></tr>'; // Close table cell and row
}
echo '</table>'; // Close html table tag
}
*If my question is not properly asked or you have some notices.Please let me know!
* (=
Put this code in a file then include that file at the bottom of all of the pages.
For example put the code in isLogged.php
Then on each page where the code is duplicated replace it with:
include "isLogged.php";
include is what you're looking for.
You should create a file that contains your repeated code. functions.php for example.
Then call it with one of these methods.
include "functions.php"
http://php.net/manual/en/function.include.php
include_once("functions.php")
http://php.net/manual/en/function.include-once.php
require_once("functions.php")
http://php.net/manual/en/function.require-once.php
create a function of repeated block and call when it required or create a file with the set of repeated code and use any of include,include_once,require_once to add the file.for more detail see php manual for these functions.
I am trying to build a dynamic subnavigation with Codeigniter. I have managed successfully to build a dynamic main navigation, but can't seem to manage to loop through the data from the joined table. In my code below i know i am not using the Foreach for the submenu correctly, but can somebody please help me or at least point me in the right direction.
Thank you a lot in advance
I am loading the foreach loops in the view like so
foreach ($query->result() as $row) {
$page_menu = $row->page_menu;
$page_menuName = base_url().$row->url;
//If page_menu is in database 1, show main menu item
if ($page_menu == '1') {
echo anchor($page_menuName, $row->page_headline)."<br/>";
}
}
if ($page_id == $webpage_id)
{
// I WANT THIS PART TO LOOP. THIS IS DATA FROM THE JOIN TABLE
foreach ($query->result() as $row) {
echo $subpage_id. "<--SUBID- " .$webpage_id. "<--- webpage id- ".$subpage_headline. "<--subheadline <br/><br/>";
}
}
This is the controller:
$this->load->module('webpages');
$query = $this->webpages->get_where_custom('url', $first_bit);
foreach ($query->result() as $row) {
$data['id'] = $row->id;
$data['headline'] = $row->headline;
$data['url'] = $row->url;
$data['content'] = $row->content;
$data['page_menu'] = $row->menu;
$data['sub_id'] = $row->sub_id;
$data['webpage_id'] = $row->webpage_id;
$data['sub_headline'] = $row->sub_headline;
}
And this is the model:
function get_where_custom($col, $value) {
$table = $this->get_table();
$this->db->where($col, $value);
$this->db->join('subpages', 'subpages.webpage_id = webpages.id', 'left');
$query=$this->db->get($table);
return $query;
}
My tables:
webpages
id,
headline,
title,
url,
content,
page_menu
subpages
sub_id,
subpage_headline,
subpage_title,
subpage_url,
subpage_content,
webpage_id,
sub_headnav
Your code:
if ($page_id == $webpage_id)
is not inside your foreach loop, is one thing. I know you say "i know i am not using the Foreach for the submenu correctly" but it's really hard for us to help you if you don't fix the bits you already know about before posting. No idea if what I said above is your problem or not
Im trying to create dynamic links from some post inside a database table,
but i cant figure out how to create the link, when the user is already logged in.
I think something like this.
<?php $articles = new Articles();
foreach($articles->fetch_user_article($_GET['uid']) as $article) :?>
<?php echo $article['title'];?>
<?php endforeach ?>
This gives me a link that looks like this
edit_articles.php?uid=5&article=213
The article id:s are correct from the DB table.
Now my edit_articles.php file
$articles = new Articles();
$article = $articles->fetch_user_article($_GET['uid']);
echo $article['text'];
But when im reach the edit_articles.php file i get
Undefined index: text
And my function
function fetch_user_article($uid){
$uid = (int)$uid;
$query = $this->link->query ("SELECT id, title,text FROM blog WHERE user_id = '{$uid}' ");
$tweet = array();
while(($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$tweet[] = $row;
}
return $tweet;
}
Your function fetch_user_article is returning more than one article.
Use like this to fecth all articles.
$articles = $articles->fetch_user_article($_GET['uid']);
foreach ( $articles AS $article ) {
echo $article['text'];
}
If you want fetch_user_article to return only one article, then the field user_id of table blog should be unique.
Or you will have to rewrite the query
SELECT id, title,text FROM blog WHERE user_id = '{$uid}'
so it gives you only one result, something like:
$article_id = $_GET['article'];
SELECT id, title,text FROM blog WHERE id = '{$article_id}'