Query database on clicking a link - php

I'm retrieving products from my database and listing them in a while loop. Like this
<?php
while($row = mysql_fetch_row($result)){
echo '<div class="product_info">';
echo '<div class="category_product_title">Product';
echo '</div>';
echo '<div class="category_product_number">#'.$row[0].'('.$row[1].')'.'</div>';//prints id and name
echo '<div class="category_product_description">'.$row[2].'</div>';//prints description
echo '<div class="category_product_price">'.$row[4].'TL</div>';//prints price
echo '<div class="category_details">DETAILS</div>';//The link to list the product details
echo '</div>';
echo '</div>';
}
?>
I want to be able to print more details on a paticular prodcut when the "DETAILS" link is clicked by getting the id or name of that paticular product and using to query the database.
I tried saving the id in a session variable like this $_SESSION['id'] = $row[0] but since i'm looping through these products, i'm not able to get the id of a specific product when it is clicked. How can i do this?. I'm confused because of the loop. Thanks

You can assign a different link to each one of the products with a GET variable.
Instead of DETAILS, the link could point to DETAILS.
Then, on the product page productpage2.php, you can get the selected ID from the $_GET superglobal array like this:
$id = $_GET['id'];

Lots of ways to do this. I would probably do something like:
echo '<div class="product_info" data-product-number="' . $row[0] . '">';
Then just grab the data-product-number attribute with JavaScript and pass it along with the request. Obviously, you'll need to verify this on the server side somehow once the request is made, since a user could set the product number in the request to anything they'd like.

Related

Click on an image stored in a MySQL database table and get additional row content for that image

I have created a members.php page that connects to a database table. The table has the following fields: id, username, profile image.
The following PHP code displays the profile image for each user in rows of 6 and allows each image to be clickable.
<?php
// The code below will display the current users who have created accounts with: **datemeafterdark.com**
$result=mysql_query("SELECT * FROM profile_aboutyou");
$row1 = mysql_fetch_assoc($result);
$id = $row1["id"];
$_SESSION['id'] = $id;
$profileimagepath = $row1["profileimagepath"];
$_SESSION['profileimagepath'] = $profileimagepath;
$count = 0;
while($dispImg=mysql_fetch_array($result))
{
if($count==6) //6 images per row
{
print "</tr>";
$count = 0;
}
if($count==0)
print "<tr>";
print "<td>";
?>
<center>
<img src="<?php echo $dispImg['profileimagepath'];?>" width="85px;" height="85px;">
</center>
<?php
$count++;
print "</td>";
}
if($count>0)
print "</tr>";
?>
This is all great, however, when I click on the image that loads it re-directs me to: viewmemberprofile.php which is what it is supposed to do. But it always displays the same image with the same id value (i.e.) 150 no matter which image I click. What I would like to have happened is. If I click on an image with id 155 etc... it will display content for that image data field not consistently the same image data regardless of which image I click.
Your help and guidance would be greatly appreciated. Thank you in advance.
One thing that I forgot to mention is that I do use sessions so... when I am re-directed to the viewmemberprofile.php page I use the following code to aide in getting the data that I need from the table.
<?php
$id = $_SESSION['id'];
echo($id);
?>
<?php
echo('<br>');
?>
<?php
$profileimagepath = $_SESSION['profileimagepath'];
?>
<img src="<?php echo($profileimagepath);?>" width="50px;" height="50px;">
I have yet to impliment the suggested solution.
You need to pass the ID of the row to viewmemberprofile.php, e.g.:
<a href="viewmemberprofile.php?id=<?= $dispImg['profileimagepath'] ?>">
And viewmemberprofile.php needs to select that row from the DB:
SELECT * FROM profile_aboutyou WHERE id = $_GET['id']
The above SQL statement is pseudo-code; you need to write actual code to accomplish what it is describing, preferably using parameterized queries.

PHP/MySQL Auto select option based on previous page

I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.

not retrieving id from browser url when clicking on back button

I found a problem in my code, when I want to remove a user from database, it has to remove him, the code for removing works perfect, but afterwards, the if condition shows that the user has been removed and I have a Back button there, I click on it and it should redirect me back to the classroom with the rest of the users in it. Classroom is identified by ID of course, but when I click on Back, it shows me classroom without an ID of a class...so its not getting ID...
// get value of id that sent from address bar
$id_student=$_GET['id_student'];
$id_trieda = $_GET['id_triedy'];
// Delete data in mysql from row that has this id
$zmaz='DELETE FROM $tbl_name WHERE id_student="'.$id_student.'" AND id_triedy="'.$id_trieda.'"';
mysqli_real_escape_string($prip, $zmaz);
$row = mysqli_query($prip,$zmaz);
// if successfully deleted
if($row){
echo "Študent bol úspešne vymazaný.";
echo "</br>";
echo "<a href='./trieda.php?id_triedy=".$_GET['id_triedy']."'>Späť do triedy<a/>";
}
else {
echo "Chyba";
}
?>
EDIT:
// get value of id that sent from address bar
$id_student=$_GET['id_student'];
// Delete data in mysql from row that has this id
$zmaz="DELETE FROM $tbl_name WHERE id_student='$id_student'";
$result=mysql_query($zmaz);
// if successfully deleted
if($result){
$id_trieda = $_GET['id_triedy'];
echo "Študent bol úspešne vymazaný.";
echo "</br>";
echo "<a href='./trieda.php?id_triedy=".$id_trieda."'>Späť do triedy<a/>";
}
else {
echo "Chyba";
}
here is edited code which is similar to one that is working when I add a student into the class and then there is a Back button again, but it works....so problem will be in deleting the student, it cant find the ID of class he was in..i think..but I have no idea how to get the ID of the class before he is removed..
Looking at the page you linked to in your comment, I see the problem - you aren't passing id_triedy in your zmazat link. It reads:
http://www.xxx.xx/project/zmazat_studenta.php?id_student=15
Where it should read:
http://www.xxxx.xx/project/zmazat_studenta.php?id_student=15&id_triedy=18
(or whatever the relevant id_triedy is).
Then the $_GET['id_triedy'] in your question code actually has something to get.
You should really build in a check for this kind of thing:
if(isset($_GET['id_triedy'])){
$id_trieda = $_GET['id_triedy'];
} else {
echo 'No trieda ID';
}
This will check the URL for id_triedy and tell you if it's not there.
Is the trieda.php the file that contains the Classroom? If so, this line should be amended:
echo "<a href=\"./trieda.php?id_triedy=".$_GET['id_triedy']."&id_student=".$_GET['id_student']."\">Späť do triedy<a/>";
It looks like you left out the id_student in the URL

Knowing which <li> item is selected using PHP and mySQL

I have 2 questions. One is if there is any error in this code.
The 2nd question I want to ask is how do you know which <li> item is selected. Right now, the code performs a search in mySQL for all rows that matches city, language and level and returns the results in a list item.
I want it so that when the user clicks on anyone of the list items, it will goes into another page displaying a more detail description by querying the selected list item.
I have a guess, which is for step 2, I also grab the ID (primary key) for each row and somehow keep that stored within the list but not echo.. Would I need to wrap <a> in <form action="XX.php" method="get">?
<?php
//1. Define variables
$find_language = $_GET['find_language'];
$find_level = $_GET['find_level'];
$find_city = $_GET['find_city'];
//2. Perform database query
$results = mysql_query("
SELECT name, city, language, level, language_learn, learn_level FROM user
WHERE city='{$find_city}' && language='{$find_language}' && level='{$find_level}'", $connection)
or die("Database query failed: ". mysql_error());
//3. Use returned data
while ($row = mysql_fetch_array($results)){
echo "<li>";
echo "<a href=\"#result_detail\" data-transition=\"flow\">";
echo "<h3>".$row["name"]."</h3>";
echo "<p>Lives in ".$row["city"]."</p>";
echo "<p>Knows ".$row["level"]." ".$row["language"]."</p>";
echo "<p>Wants to learn ".$row["learn_level"]." ".$row["language_learn"]."</p>";
echo "</a>";
echo "</li>";}
?>
Your code looks alright from what I can see. Does it not work?
One way would be to get the ID through your SQL-query as well and then add the id to the href in your link. Then you can fetch it through the querystring on the other page, to display the proper post depending on which li-element the user clicked on:
echo "<a href=\"details.php?id=". $row["id"] ."\" data-transition=\"flow\">";
Not sure how you mean "somehow keep that stored within the list but not echo" - it wouldn't be possible to store anything in the list, if it is not echoed, as it then wouldn't be sent to the client. You can of course store the id in a data-attribute on the li-element, which won't be displayed to the user. It will however be visible through the source code! Don't know why that should be a problem though?

PHP catalog, click on item image to display product details

I am trying to build a simple catalog displaying items from a mysql database.
So far I can get the items to display in a list format including the images stored as a path in the items table in a field called "path".
I would like the ability to be able to click on the item image and it takes you to a dedicated page showing you the details of that product. The link would correspond to which ever item you click on based on the data in the item table.
So far I have the following code;
<?php
session_start();
require "connect.php";
$date = date("d-M-Y");
$query = "select * from item order by date && time asc limit 0,3";
$query2 = "select * from users where userid = ".$_SESSION['userid'];
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['item'] ?>
<?php echo $row['description'] ?>
//Code for Image Link
<a href='<a href='<?php echo $row['path']?>'><img src="<?php echo $row['path']?>
<?php
}
?>
The above code allows you to click on the image and it takes me to http://127.0.0.1/steal/%3Ca%20href=
However I don't know what I would need to enter in order for it to take me to a page that shows the product?
Please Help
Many Thanks
I don't know your database schema, so I'm taking some liberties here about your columns for the product. But, try this:
<img src="<?php echo $row['path']?"/>
I also am not sure what your product page URL is either, so change product_page.php to whatever template you are using to display your products.
You need to create another page called for example showProductsOrder.php that accepts the orderID and then does output the content.
showProductsOrder.php?orderID=1
<?php
SELECT * FROM order WHERE orderID = $_GET['orderID']
while(fetch()) {
//> Show product here
}
?>
Also please don't use mysql_query. Use php.net/pdo
Addendum
Show all products
As yes123 said you would need to create another page, but i if you have a problem creating the link here is my suggested solution:
Replace your link with:
<?php echo ("<a href='".$row['pagePath']."'><img src='".$row['imagePath']."' /></a>";?>
$row['pagePath'] is the page that it will load when the image is clicked on, and
$row['imagePath'] is where the image is stored on your pc / server.

Categories