Performing mysql update based on passed variable from link? - php

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

Related

How to add button for every field when retrieving data from a database

I have looked everywhere for this question, perhaps I'm just not phrasing it correctly.
I have a page displaying various products, the table is called items. There in my fields I have all the information and images to display on the page, this works fine. Now I want to be able to press a button to add the item to cart, I have the code below where I access the data.
<div class="col-md-5">
<h2 style="font-size:25px;"> <?=$items['title'];?></h2>
<img src="<?=$items['image'];?> "width='300' height='500'/>
<p style="font-size:20px;" class = "lprice">GBP <?= $items['price'];?></p>
</div>
Now that I have done that, my question is how can I add a button for every time a result is displayed and have that button linked with that item, I appreciate this may no be as straight forward as I am phrasing this, but just looking for some help.
Thanks
You can do it in two ways, either way, you need a primary key (eg: id) in your items table which will hold a unique number for each of your items.
After that, you print your id along with everything else inside a button or inside an a tag. Like
<div class="col-md-5">
<h2 style="font-size:25px;"> <?=$items['title'];?></h2>
<img src="<?=$items['image'];?> "width='300' height='500'/>
<p style="font-size:20px;" class = "lprice">GBP <?= $items['price'];?></p>
<a class="btn btn-primary" href="add_to_cart.php?id=<?=$items['id'];?>">Add to Cart</a>
</div>
Now inside your add_to_cart.php file, you can receive the id of the products like this $product_id = $_GET['id'];
Once you have the id of the product, you can process the rest on the add_to_cart.php file and redirect the user back to the previous page with a success or error message.
This way, we passed the id using a URL parameter. The second way is to pass the id using a form. I just wanted to let you that this method exists. I hope this helps. If you have any doubt, feel free to ask in the comment section.

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'];

PHP- Store in a session variable the name of the clicked link

I have a list with many links. These options are generated by a mysql query. My idea is when I click on one of the options (these options link to menuestaciones.php), I can store in my session variable, eg $_SESSION [ 'station'], the name of the clicked link
<div class="listadoestaciones">
<?php while ($row1 = mysql_fetch_array($estacionesclientes)):; ?>
<p> <?php echo $row1['lnStationName']; ?>
</p>
<?php endwhile; ?>
</div>
For example,the next code,my session variable is $_SESSION['clickedlink']:
<a href="menuestacion.php" name="link1">
page1
</a>
<a href="menuestacion.php" name="link2">
page2</a>
<a href="menuestacion.php" name="link3">
page3</a>
If I click on page3 , $_SESSION['clickedlink']="link3"
Thank you for your help.
You are totally confused. You are combining client side script (used to track clicks) with server side script ($_SESSION). There are two ways to tackle your issue here, either use AJAX and alter sessions by parsing links or another way is to save it using sessionStorage in Javascript (recommended 'cause it is very fast and user friendly).

Using a PHP variable as a MySQL query table name

self taught at PHP so please spare me if i made any obvious errors,
im trying to dynamically create an accordion and have the corresponding content beneath each accordion header be created from its corresponding table,(if the header is tacos, the information below would come from the tacos_info table) some of the solutions i came up with im not sure about, cheifly passing a variable value as the table name in the mysqli query.
<?php
//initialize list
$res = mysqli_query("SELECT * FROM tables ORDER BY votes DESC");
//build the accordion header and div content in descending order
while($row= mysqli_fetch_assoc($res)){
//create value for SQL table name to build content
$dbname='$row['name']';
//create the accordion headers
$accordioncontent= '<h3>'.$row['name'].'</h3>';
//build the query that will be used to create the accordion content dynamically
$res2 = mysql_query("SELECT * FROM '$dbname' ORDER BY votes DESC");
//while loop to build the div content dynamically
while($row2= mysqli_fetch_assoc($res2)){
//dynamically create the list items i.e the accordion content
$ranks= '<li id="li $row2['id']">
<div class="tut-img">
<img src="<?php echo $row2['img']?>" width="50" height="70" alt="<?php $row['title']?>" />
</div>
<div class="title"><?php $row2['title']?>
</div>
</li>';
}//close content while loop
//create the submit button that submits according to each accordion divs content
$submitbutton='';
//limit submissions to once per IP, per table
$voted=false;
$vcheck= mysqli_query("SELECT 1 FROM sort_votes
WHERE ip='".$_SERVER['REMOTE_ADDR']."'
AND date_submit=CURDATE()
AND Tablename='$dbname' "
);
if(mysqli_num_rows($vcheck)==1)
$voted=true;
//conditional to assign either a submit or edit
if(!$votedIFC){$submitbutton='Enter opinion<span></span>'}
else{$submitbutton='Enter opinion<span></span>'}
//concatonate the div header with the div content
$accordioncontent .= '<div><ul class="sort" id="rank_ul">'$ranks'</ul><div class="button-holder">'$submitbutton'</div></div>';
}//close accordion while loop
//send all this data to the AJAX GET request
echo $accordioncontent;
?>
am i passing these values to the query correctly? is this allowed? if not what are better alternatives? any and all tips, input and knowledge is much appreciated.
First of all, I can see that you are using simple and double quotes sometimes in a strange way. Which IDE are you using for your development? My first recommendation, would be for you to use a proper editor that will automatically check your code syntax.
For example this seems strange (difficult to ready and will surely at one point generate an error):
'<li id="li $row2['id']"> ..... ';
In my opinion, a correct syntax here would be:
"<li id='li ".$row2['id']."'> .... ";
More details here: http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm
Now to answers to your question, you seems to be more focused on the way you are passing the values to the SQL query. If you are looking for best practices, then I'd recommend you to use php PDO. It's a layer between PHP and your database that will among other things, make sure that the you correctly passed values to SQL (reduce risk of SQL injection, problem of quotes, etc ...).
More details about PDO here: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
My last advises:
Please make efforts in the indentation of your code, it will be easier to read and understand for you and others and it will then avoid obvious errors.
Use correct variable name. For example you are here using $dbname to speak about database tables ...
Good luck.

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

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.

Categories