send id through the link with php and MySQL - php

I have table with items and for each item there is an option for user to delete and restore it. And there is special php file for it 'delete.php'.
print "<td>";
if ($row['deleted'] == 'y') {
print "<a href='delete.php?id=2'>Undeleted</a> ";
}
if ($row['deleted'] == 'n') {
print "<a href='delete.php?id=1'>Deleted</a> "; //'$_GET['id']'
}
print "</td>"
My question is how can I get the id of item that user clicked and send it to 'delete.php'?
So instead of
"<a href='delete.php?**id=2**'>Undeleted</a> ";
there should be something like:
"<a href='delete.php?**$_GET['id']'**'>Undeleted</a> ";
or
"<a href='delete.php?**<?php $_GET['id'] ?>**'>Undeleted</a> ";
but in second example it doesn't make sense php inside php. I think I probably just don't know correct syntax.

what's wrong with
echo "<a href='delete.php?id=$_GET[id]'>Undeleted</a>";
?
or, in somewhat more modern terms:
echo <<<EOL
Undeleted
EOL;

If you just want to send the id to delete.php, just keep your HTML part as it is :
print "<td>";
if ($row['deleted'] == 'y') {
print "<a href='delete.php?id=2'>Undeleted</a> ";
}
if ($row['deleted'] == 'n') {
print "<a href='delete.php?id=1'>Deleted</a> "; //'$_GET['id']'
}
print "</td>"
Inside delete.php, Access the id as :
$id = $_GET['id']
If you want to tell the delete.php whether to delete or restore the item, you might want to add another param to the URL like delete.php?id=1&action=d or delete.php?id=1&action=u
Now, if your id comes from a GET parameter of the above file like file.php?id=1, you will have to access it like -
print "<a href='delete.php?id={$_GET[id]}'>Undeleted</a> ";
Make sure that you sanitize and escape this id value before using it in the query.

Related

How can I use hyperlinks in PHP to display data on the page it sends you to?

I have this piece of code below. It displays the image and name of all the entries in a table in my database. The name is set up to become a hyperlink.Is it possible to make it so when one specific name is clicked that data for only that specific name will be displayed on the page you are sent to?
So for example if I select the first entry that is displayed back "mealname1" and it takes me to the showrecipe.php page, can I make it so I can display all the data I have for "mealname1" and only "mealname1". I'm really lost, I have scoured the internet and my php books but can't find anything to that is relevant.
If there is no way of doing it is there an obvious solution that I am missing?... I am very much a novice to this... thanks for your help guys.
<?php
require("db.php");
$prodcatsql = "SELECT * FROM recipes";
$prodcatres = mysql_query($prodcatsql);
$numrows = mysql_num_rows($prodcatres);
if($numrows == 0)
{
echo "<h1>No Products</h1>";
echo "There are no recipes available right now.";
}
else
{
echo "<table id='recipetable'>";
while($prodrow = mysql_fetch_assoc($prodcatres))
{
echo "<tr>";
if(empty($prodrow['image'])){
echo "<td><img
src='./images/No_image.png' alt='"
. $prodrow['mealname'] . "'></td>";
}
else {
echo "<td><img src='./images/".$prodrow['image']
. "' alt='"
. $prodrow['mealname'] . "'></td>";
}
echo "<td>";
echo ''.$prodrow['mealname'].'';
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
Change the query to
SELECT * FROM recipes WHERE mealname='$mealname' LIMIT 1;
You can remove "LIMIT 1" if you want but this makes sure you will only get 1 or 0 row back. Don't forget to escape the string.

If database field is empty echo "nothing" if something there echo "something"

looking for a solution to this bit of coding below.
<?php
$nextfive_events = mysql_query("SELECT date_format(date, '%d/%m/%Y') AS formatted_date, title, location, regs FROM events WHERE status = 'ACTIVE'");
if(mysql_num_rows($nextfive_events) == 0) { echo "<p>No events coming up!"; } else {
echo "<table width=\"600\" border=\"0\" cellpadding=\"2\" cellspacing=\"2\" class=\"greywritinglight\" align=\"left\">
<tr align=\"center\">
<td>Date</td>
<td>Name</td>
<td>Location</td>
<td></td>
</tr>";
$x=1;
while($next_row = mysql_fetch_array($nextfive_events))
{
if($x%2): $rowbgcolor = "#FFFFFF"; else: $rowbgcolor = "#EEEEEE"; endif;
echo "<tr align=\"center\">";
echo "<td>" . $next_row['formatted_date'] . "</td>";
echo "<td>" . $next_row['title'] . "</td>";
echo "<td>" . $next_row['location'] . "</td>";
echo "<td>Regs</td>";
echo "</tr>";
$x++;
}
echo "</table>";
}
?>
I want the row echo "<td> <a href regs .....
To display the word Regs when there is something in 'regs' in the database. Say if there is nothing in that field I want it to be blank and not say Regs.
thanks
You could do Ternary operator:
echo "<td><a href='" . (empty($next_row['regs']) ? "#" : $next_row['regs']) . "'>Regs</a></td>";
Try not to do escape characters, they look confusing, do single quote for href attribute. Also, Did you want
<a href='#'>Regs</a>
to show if it was blank?
If Not, try this:
echo (!empty($next_row['regs']) ? "<td><a href='" . $next_row['regs'] . "'>Regs</a></td>" : "");
You could use a ternary:
echo ( ! empty($next_row['regs'])) ? '<td>Regs</td>' : '<td>&nspb;</td>';
First off, I'd like to show you a really handy trick with PHP that allows you to echo out into HTML without actually saying echo. Just create a break in your PHP code, and in between anything you put will be echoed as HTML.
As for the number of rows returned, you are doing it correctly. Make sure that you are querying properly, that you have an established connection, and that there are no logical errors in your SQL.
Sorry, didn't notice you wanted to check if the column was empty! Just use the function empty(). This function will return true when the data you give it is empty, so simply give it the column from the row of data you wish to check.
<?php
// Lets say this is your database connection variable
$connection = mysqli_connect(//Your info goes here);
// This is the query you want to run
$query = "SELECT something FROM somewhere WHERE something='$something_else'";
// This is where you are storing your results of the query
$data = mysqli_query($connection, $query);
// Here, you can ask for how many rows were returned
// In PHP, ZERO is evaluated to false. We can use a
// Short-hand boolean expression like this
if (mysqli_num_rows($data))
{
// Because zero evaluates to false, we know
// that if we get HERE that there ARE rows
// We can break out of PHP and into our HTML
// by simply ending our PHP tag! Just remember
// that you need to open it back up again though!
?>
<!--You can put your HTML here-->
<p>
We found some rows that you might
need to know about!
</p>
<?php
}
else
{
// But, if we get here, we know it evaluated as
// FALSE and therefore no rows returned
// Here's that HTML trick again
?>
<!--HTML can go here-->
<p>
No rows returned!
</p>
<?php
}
?>

dynamic php page calls

So I have looked through many of the other questions posted but none seemed to properly answer my question.
I currently have a php script that reads rows from a database and runs a loop to display the info of each row in a html div.
The issue I am now having is that in each "card" of info previously loaded there has a picture. And when the picture is clicked I need to load a different file names listing.html. The problem is that depending on which picture is clicked on I want to load different information based on which listing was clicked on. I looked into using sessions but since i dynamically load all of the pictures in one loop I do not know a way to differentiate between them.
here is the code I currently have that loads all the info from the database.
$query = "SELECT * FROM Listings ORDER BY OrderNumber";
if ($result = mysqli_query($con, $query))
{
while ($row = mysqli_fetch_row($result))
{
echo "<div class ='listing'>";
echo "<a href='listing.html'>";
echo "<img src=$row[2] alt='' width='60%' align='left' >";
echo "</a>";
echo "<span style = 'font-size: 25px;'>";
echo $row[4];
echo "</span>";
echo "<br>";
echo "<br>";
echo "MLS Number: #";
echo $row[1];
echo "<br>";
echo "<br>";
echo "<b>Open House Details: </b>";
echo $row[6];
echo "<br>";
echo "<br>";
echo $row[5];
echo "<br>";
echo "<br>";
echo "<a href='";
echo $row[9];
echo "' style='color: #8a0b0b; font-weight: bold; font-style: italic; font-size: 18px;' target='_blank'>Virtual Tour</a>";
echo "<div class='listingPrice'>";
echo "$ ";
echo $row[7];
echo "</div>";
echo "</div>";
}
mysqli_free_result($result);
}
I need some way that when the a tag is clicked to first be able to discern which picture was clicked then probably make a session variable with the corresponding row.
When you output the link, include a query string value from the row in the data. Something like this:
echo "<a href='listing.html?id=" . row[0] . "'>";
(I'm just guessing on the row[0] part, it would be any identifier which uniquely identifies that record.) That way all of the links would have the data you need on the listing.html page embedded directly in them. (Shouldn't it be listing.php?)
So on the page being referenced, the value would then be available in the query string. Something like this:
$_GET["id"]
There really isn't a need for session state in this case, if all you need to know is which record was clicked then that information can be placed directly in the link. This reduces coupling in the code, keeps the links a little more RESTful, even lets people bookmark the link directly if they want to.

Ifstatement used to make a functionality button appear?

I am on my 2nd day(16th hour) of trying to get my delete button to do what I want with PHP. I have a site that is a social network that has user profiles. Users can leave comments on another users profile. I am trying to put a delete link in a designated area that only shows up if you are viewing your own profile and goes away when you are viewing someone elses profile. I am also not wanting to make a delete confirm page. I want the page to reload with the comment selected to delete gone, and be sent to my db marked as dead. This is what I have so far:
<?php
$query = "SELECT * FROM `ProfileComments` WHERE `ToUserID` = '".$prof->id."' ORDER BY `date` DESC, `time` DESC LIMIT 10";
$request = mysql_query($query,$connection);
while($result = mysql_fetch_array($request)) {
$poster = new User($result['FromUserID']);
echo "<div id='CommentProfile'>";
echo "<div id='CommentPhotoProfile'>";
echo "<a href='http://www.blah.org/Profile.php?id=".$poster->id."'>";
echo "<img src='" . $poster->img('mini') . "' border='0'/>";
echo "</a>";
echo "</div>";
echo "<div id='ProfileCommentBody' class= 'round_10px'>";
echo "<div id='CommentNameProfile'>";
echo "<div class='ProfileCommentTail'> </div>";
echo "<a href='http://www.blah.org/Profile.php?id=".$poster->id."'>";
echo $poster->first_name. " ". $poster->last_name. " <span style='font-weight:normal'>says...</span>";
echo "</a>";
echo "</div>";
echo stripslashes(nl2br($result['commentProfileBody']));
echo "<div id='CommentInfoProfile'>";
echo date('M d, Y',strtotime($result['date']));
echo " at " . date('g:i A',strtotime($result['time']));
if ($poster->id == $prof->id)
echo "<a href='http://www.blah.org/DeleteComment.php?id=".$prof->id."'>";
echo " delete";
echo "</a>";
echo "</div>";
echo "</div>";
echo "</div>";
}
?>
do I need to make a seperate query underneath the one I already have that is for the composition of the comments?
do I need to add on to that query?
how do I make the delete button only appear when the user is looking at their own page?
how do I make the page reload with the comment gone after I selected it deleted and mark it dead in the db?
thank you in advance
Be careful if all you do after authorization of the delete privilege is then hide or not hide a button.
If users figure out another way to invoke the delete action, that kind of authorization checking won't work. For example, if your implementation uses a "delete URL" that encodes the delete command, and your button merely POSTs to that URL, then when the button is hidden, a user could manually post the delete command.
Fill in your variables:
if ($current_user_id == $profile_user_id)
echo 'delete';
This is toatlly lame, code, but just a random thought since you are really giving us nothing to work with.
Take it for what it is:
function getPageUserID()
{
return $_GET['userID'];
}
if ($user->userID == getPageUserID())
{
//show delete button
echo '<button value="Delete">Delete</button>';
}

PHP - Excluding blank rows when printing a table

The code below works great. It prints out items in a MySQL database as an HTML table. However, the database has entries where the first column (the variable "site") is blank. How can I have this table exclude rows / entries where "site" is blank?
$result=mysql_query("SHOW TABLES FROM database LIKE '$find'")
or die(mysql_error());
if(mysql_num_rows($result)>0){
while($table=mysql_fetch_row($result)){
print "<p class=\"topic\">$table[0]</p>\n";
$r=mysql_query("SELECT * , itemsa - itemsb AS itemstotal FROM `$table[0]` ORDER BY itemstotal DESC");
print "<table class=\"navbar\">\n";
while($row=mysql_fetch_array($r)){
$itemstotal = $row['itemsa'] - $row['itemsb'];
print "<tr>";
print "<td class='sitename'>".'<a type="amzn" category="books" class="links2">'.$row['site'].'</a>'."</td>";
print "<td class='class1'>".'<span class="class1_count" id="class1_count'.$row['id'].'">'.number_format($itemstotal).'</span>'."</td>";
print "<td class='selector'>".'<span class="button" id="button'.$row['id'].'">'.''.Select.''.'</span>'."</td>";
}
print "</tr>\n";
}
print "</table>\n";
}
else{
print "";
}
Add a where clause to the SQL query.
WHERE `site` <> ''
or
WHERE `site` != ''
should work.
However, if you want the rows where site is blank for other PHP options, it would be better to filter out the blank sites in the PHP and not the MySQL query.
Just put the following before the print calls in your while loop:
if (trim($row['site']) == '') {
// skip output of this row if site is empty
continue;
}
while($row=mysql_fetch_array($r)){
if($row['site'] != "") {
$itemstotal = $row['itemsa'] - $row['itemsb'];
print "<tr>";
print "<td class='sitename'>".'<a type="amzn" category="books" class="links2">'.$row['site'].'</a>'."</td>";
print "<td class='class1'>".'<span class="class1_count" id="class1_count'.$row['id'].'">'.number_format($itemstotal).'</span>'."</td>";
print "<td class='selector'>".'<span class="button" id="button'.$row['id'].'">'.''.Select.''.'</span>'."</td>";
}
}
The simplest solution would be to insert the following line into your inner while block:
while($row=mysql_fetch_array($r)){
if (!trim($row['site'])) continue; // skip empty rows
$itemstotal = $row['itemsa'] - $row['itemsb'];
Edit: Actually, it looks like that $itemstotal variable isn't needed; it's being calculated as a "virtual" itemstotal column in the SQL query. If you replace "number_format($itemstotal)" with "number_format($row['itemstotal'])" a few lines down, you can get rid of the "$itemstotal = ..." line entirely.

Categories