How to implement a "save" feature with dynamic content using cookies - php

I would like to implement a "save" feature, which allows my users to save a particular entry that I have presented to them from my database. For example, if they see something they like, they can press the "save" button and it will save to a "bookmarks" page.
Here is my code:
<?php
// Get all the data from the example table
$result = mysql_query("SELECT * FROM table WHERE item <> 0 ORDER BY id")
or die(mysql_error());
// keeps getting the next row until there are no more to get
$i = 10;
while ($i > 0) {
$i--;
$row = mysql_fetch_array( $result );
if ($row['id'] != "" ) {
?>
<!-- Some content in this div-->
<div class="content">
<img src="<?php echo $row['logo']; ?>"/>
<?php echo $row['id']; ?>
</div>
<!-- This div will have the save icon that users can press -->
<div class="save">
<img src="images/saveIcon.png" />
</div>
<?php }} ?>
<div class="bookmarked">
Every single div that is labled as "content" that has been saved, will be displayed here.
</div>
Question: How would I implement a feature to allow a user to add the particular ID from SQL (of the dynamically created content) to a cookie variable, so that it can be reproduced at a later time.

If I have understood your question correctly, you want a button which marks the related DIV, and stores this relation to cookies.
First of all, I would add the id of entry as class to the DIV. Then you'll have the possibility to get the id easily via javascript (for further implementations).
To set the favorites via php, you should add a link to a new php script. This script sets the cookie, via the setcookie function in PHP.
In your bookmarked-DIV you would make the same while-loop as above, but check the ids with the values in the cookies. You can access cookies with $_COOKIE. Just show items, which are containing in the cookies.
This is a possible way of implementation.

You would probably want to use PHP to store it in it's session rather than using Javascript.
You could achieve this by simply pushing the ID into a session variable:
<?php
session_start();
if(isset($_GET['id']) && is_numeric($_GET['id'])){
$_SESSION['bookmarks'][] = intval($_GET['id']);
}
Using AJAX you could then hit this script with an the ID of the entity to bookmark and it'll get saved into the session.

Related

Performing mysql update based on passed variable from link?

I've built a list of links based off of an array from a select query.
Linking to the page in question works fine, but I've added a link option to each to delete the page in question. The only issue is, I'm wondering the best way to pass the page ID of the given page into the query that deletes (deactivates) the page.
I build my page links like this:
<?php foreach($result as $page): ?>
<div class="col-lg-3 col-sm-6 d-flex" style="padding-bottom: 20px;">
<div class="card text-center flex-fill">
<h2><?php echo $page["title"] ?></h2>
<p><?php echo $page["Name"]?></p>
<a target="_blank" href="showpage.php?pageid=<?php echo $page['id'] ?>">View Page</a>
Edit Page
Delete Page <!--this is where I need to pass $page['id'] and use it in the query below-->
</div>
</div>
<?php endforeach?>
The query to delete/deactivate:
$deletePage = "
UPDATE pages
set active = 0
where id = /*this is page ID from previous link*/
";
$performDelete = $mysqlConn->query($deletePage);
What is the best practice for me to pass the pageID of the link into this query?
You're passing the target page through as a URL parameter on the first page, so it will be available on the second page via $_GET, so the standard structure would be:
$deletePage = "UPDATE pages set active=0 where id=$_GET['pageid']";
However, note that the above is open to attacks; it's trivial for a user to simply modify the value in their address bar, and thus update the wrong row. In fact, with a bit of SQL injection, it's even possible for a user to completely delete your entire database with the above PHP / SQL.
The best way to avoid this is paramaterised queries (I assume MySQLi in the following):
$stmt = $mysqlConn->prepare("UPDATE pages set active=0 where id=?");
$stmt->bind_param('i', $_GET['pageid']);
$stmt->execute();
Note that you'll still want to assure that the user viewing the page is authorised to make the UPDATE command, most likely by checking against their $_SESSION.
Pass it in link and get it in second page using $_GET['id']
Delete Page

PHP - Pass anchor tag value to target page

TL:DR - I need to pass an anchor tag value to another php page and looking for alternatives to SESSION / COOKIES. Going for forms with POST/GET is discouraged as I would like to avoid having to submit.
Detailed description:
I have a php page which lists a mysqli result set in list form as per the following:
ID fname surname
12 John Doe
13 Carl Brown
Now I would like to have the ID field as a link, which I can achieve using an an HTML anchor tag. Once clicked I would like to redirect to another page and pass the clicked ID (e.g. 12 or 13) for further use.
I know this is achievable through cookies or sessions, but I wanted to check if perhaps there's another way of doing this. Also I would like to avoid forms in order to avoid having to 'submit' the actual form. I'd like to keep the experience as a click and redirect.
To give some context here is my php code:
<?php
include 'functions.php';
session_start(); //Fetches session already initialized in other pages.
$page_fund=new page_fundementals; //simply gets menu items
$conn = new consultant_ops; //executes a mysqli query to get the results used further below
$result=$conn->listPatients($_SESSION['user_id']); //passes the $_SESSION['user_id'] to a listPatients method in order to get the mysqli resultset
foreach($result as $row){
$i=0;
${'p_id'.$i}=$row['p_id'];
${'p_fname'.$i}=$row['p_fname'];
${'p_surname'.$i}=$row['p_surname'];
echo ${'p_id'.$i}." ".${'p_fname'.$i}."<br />";
$i++;
}
?>
have an anchor tag like this
<a href="sample.php?id=<?= $user->id ?>">
<?= $user->name ?>
</a>
then maybe in your sample.php
<?php
if(isset($_GET['id']) {
$user_id = $_GET['id'];
/* your code here to get user from database, maybe
SELECT * FROM users WHERE id = $user_id something like that
then format afterwards */
}
?>
maybe something like that
Why not pass variable in a GET request?
echo "<a href='page.php?pid=".$row['p_id']."'>redirect</a>";
which you can access on the target page.php
$pid = $_GET['pid'];
In anchor tag you can specify query params for eg
12
In this case, when a user clicks on 12 he will be redirected to todo.php?id=12.
In todo.php you can fetch $_GET['id'] and work accordingly.

How do i get make session id from a loop of mysqli?

I am learning php and i need some help in one of my project.
How can i get id of a specific row while displaying the value of other column (in my case title) from a loop so that i can make it $SESSION and forward it to next page.
For now what i want to do is get an id of the row when i click the title and show the post in the next page and work further on it. I think i can use javascript for but don't know how to do so.
My codes (by which i am currently fetching data from database)
<div class="list-group">
<?php while($row = mysqli_fetch_array($search_result)):?>
<?php echo $row['title'];?>
<?php endwhile;?>
</div>
Thanks in Advance
Assume view_page.php is the page you want to view content of that row on when you click the row and you will use get method to extract id to go fetch content of a specific row in your database.
" class="list-group-item list-group-item-action list-group-item-dark">
on url address you will see something like after view_page.php?id=1
use this coode to get that row id: $id = $_GET['id'];

Dynamically changing <div> content on link click with PHP?

I have an area on my webpage that is populated by different <div> containers of information. When a link in my navigation bar is pressed, one <div> will fade out and another will fade in. What I'd like to do is have one of these content <div>'s filled with dynamic information, and when a link is pressed on another one of the "pages" it would change which database to load the information from and then display, or fade in, that <div> with the new information.
Sudo:
View information
<div id = "dynamicDiv">
<?php include 'file.php' ?>
</div>
file.php
**Find which database to load information from and display content**
I thought about using $GLOBAL vars, but I'm not sure how to set those from a link, and also it wouldn't reload the div content.
I also considered using a form, but I'm not sure of the "correct" way of doing this would be, and also when the page is reloaded the <div> that is displayed by default would be loaded, not the <div id = "dynamicDiv>
Any suggestions/ideas are very much welcomed....
In this case you should use ajax.
AJAX is used for changing the page content from server without reloading the page.
You can use this JQUERY AJAX And JQUERY LOAD
$(document).ready(function(){
$("#changediv").load("load.php?id=1");
})
in load.php
$id=$_GET['id'];
// use that id for dynamic query in database
$query="SELECT *.....";
$result=mysql_query($query);
echo mysql_fetch_array($result);//somthing like that
All the word echoed in php become response in ajax.

Swap images from PHP array with Ajax and also get ID

On my website an user is able to fill in an url. When he fills in the url, he gets all the images src's from that url. I push these src's to an array in php:
array_push($goodfiles,$pic);
Now the user will be able to choose on of the pictures (with a next or prev button) and then save it to the database. The picture that's saved is based on the id of the image in the array. So $goodfiles['0'] means id = "0" and so on.
I want the swapping of the images to work with ajax, so that the pages doesn't have to refresh all the time when clicking the next or previous button. And then when I save the form, I want to know the id of the current image, so that I can save it to the database.
How do I realize this with Ajax (jquery)?
Edit:
This is how I do it right now:
$current_id = $_GET['id'];
if(empty($_GET['id']) || !empty($empty)) { $current_id = 0; }
$prev_id = $_GET['id'] - 1;
if($prev_id < 0){ $prev_id = 0;}
$next_id = $_GET['id'] + 1;
if($next_id > $_SESSION['count']-1 && $_SESSION['count'] != 'empty') { $next_id = $_SESSION['count']-1;}
This is the code for the pagination
And this is the pagination:
<div id="url_pic">
<img src="<?=$_SESSION['pictures'][$current_id]?>" class="img_load"><br>
<? if($_SESSION['count'] > 1) { ?><center><img src="img/add/left.png"> <img src="img/add/right.png"></center> <? } ?>
</div>
So right now my solution doesn't contain any javascript, but it's all php coded. And the page refreshes everytime you want to see the next picture. I want to solve this in ajax, so that you can paginate through the images without a refresh. The way I want it is like this link:
http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm
But except for the text, I want to paginate through images.
You probably don't need to use AJAX for this. Simply return a html file containing a JavaScript array, which contains all those image URLs and do the other stuff using JavaScript.
Get back to StackOverflow in case you've a more precise question and hopefully some code, which we can help on ;)
Load a script at the bottom of your php page the user side of the PHP where all your HTML is, above the closing body tag thats something loosely similar to this
<script type="text/javascript">
var myArray = <?php echo json_encode($myPHParray); ?>
</script>
this way when your page loads out it renders with a dynamic javascript json object as a variable that you can work with client side, this removes the need for an AJAX request all together unless your doing stuff with the data your playing with. From first glance Im guessing not really per say. But yea, at the very least its one less transaction to be made when the page is loading.
edit just noticed someone said similar while I was typing out.. Lars.. so I guess this is a follow up to his answer :-D

Categories