Obtaining data from a table using foreign keys PHP MySQL - php

I'm trying to output a product from my products table using a foreign key that is in another table because the products are then saved into a user account.
relational tables:
useraccount > savedproduct < products
As many users can have many products and many products can have many users i have made up a table for the inbetween that holds only savedProductId, productId and user_id.
I want to output the product data from the savedproduct table that only has a certain user id attached, if that makes sense.
It practically works but shows all products (twice repeated) instead of just the ones that are under the user id in saved products, my code is here:
NOTE: Please do not say anything about injections, etc., i will be implementing that after i have everything worked out, thank you.
$user_check=$_SESSION['login_user'];
$sqlCommand = "(SELECT * FROM userAccount WHERE email='$user_check')";
$query = mysqli_query($con,$sqlCommand) or die("Error: ".mysqli_error($con));
$column = mysqli_fetch_array($query);
if($column['admin'] != NULL){
echo "<section class='userName'><h3>".$column['firstName']." ".$column['surname']."</h3></section>";
echo "<section class='address'>".$column['addressLine1']."<br />".$column['addressLine2']."<br />".$column['county']."<br />".$column['country']."<br />".$column['postCode']."</section>";
echo "<section class='email'><h3>".$column['email']."</h3></section>";
echo "<section class='passwordUpdate'><a href='update.php?user_id=".$column['user_id']."'>Change Password</a></section>";
echo "<section class='logout'><a href='extras/logoutProcess.php'>Logout</a></section>";
echo "<hr />";
</section>";
Part where I am trying to output the saved products associated with the user id, etc:
}else{
$userIdent=$column['user_id'];
$sqlCommand = "SELECT savedProduct.user_id, product.productName, product.productId, product.productImg, product.price FROM savedProduct, product WHERE savedProduct.user_id=$userIdent LIMIT 2";
$query = mysqli_query($con,$sqlCommand) or die("Error: ".mysqli_error($con));
echo "<section class='userName'><h3>".$column['firstName']." ".$column['surname']."</h3></section>";
echo "<section class='address'>".$column['addressLine1']."<br />".$column['addressLine2']."<br />".$column['county']."<br />".$column['country']."<br />".$column['postCode']."</section>";
echo "<section class='email'><h3>".$column['email']."</h3></section>";
echo "<section class='passwordUpdate'><a href='update.php?user_id=".$column['user_id']."'>Change Password</a></section>";
echo "<section class='logout'><a href='extras/logoutProcess.php'>Logout</a></section>";
echo "<hr />";
echo '<section style="overflow:auto;height:400px;"><table cellpadding="0" cellspacing="0" border="0">
<tr>
<th></th>
<th>Product</th>
<th>Price</th>
</tr>';
while($savedP = mysqli_fetch_array($query)){
echo "<tr>
<td>
<a target='_self' href='fullProductInfo.php?productId=".$savedP['productId']."'>
<img src='http://www.littlepenguindesigns.co.uk/pages/CMX/images/products/".$savedP['productImg']."' alt='".$savedP['productName']."' width='180' height='150' border='0' />
</a>
</td>
<td><a target='_self' href='fullProductInfo.php?productId=".$savedP['productId']."'>".$savedP['productName']."</a></td>
<td>£".$savedP['price']."</td>
</tr>";
}
echo "</table></section>";
}
Every bit of help is appreciated.

if i understood your question correct you only need a right join over these 3 tables.

Related

PHP giving specific item access to admins

So I have this food ordering system where each admin uploads his or her food from the backend and users can browse through those food from the frontend, a simple program. But what I want is that an admin should not be able to view or update the food from another admin as right now any of the admins can view and update all the food that are uploaded on the backend. What I want is only a specific admin only viewing and updating his or her added food items.
Attached below is the snippet and picture of the food view and update page where it displays all foods and can update them.
FYI the code is in PHP and the backend is SQL in phpMyAdmin
Please do let me if there are any confusions in my explanation.
<?php include('partials/menu.php'); ?>
<div class="main-content">
<div class="wrapper">
<h1>Manage Food</h1>
<br /><br />
<!-- Button to Add Admin -->
Add Food
<br /><br /><br />
<?php
if(isset($_SESSION['add']))
{
echo $_SESSION['add'];
unset($_SESSION['add']);
}
if(isset($_SESSION['delete']))
{
echo $_SESSION['delete'];
unset($_SESSION['delete']);
}
if(isset($_SESSION['upload']))
{
echo $_SESSION['upload'];
unset($_SESSION['upload']);
}
if(isset($_SESSION['unauthorize']))
{
echo $_SESSION['unauthorize'];
unset($_SESSION['unauthorize']);
}
if(isset($_SESSION['update']))
{
echo $_SESSION['update'];
unset($_SESSION['update']);
}
?>
<table class="tbl-full">
<tr>
<th>S.N.</th>
<th>Title</th>
<th>Price</th>
<th>Image</th>
<th>Featured</th>
<th>Active</th>
<th>Actions</th>
</tr>
<?php
//Create a SQL Query to Get all the Food
$sql = "SELECT * FROM tbl_food";
//Execute the qUery
$res = mysqli_query($conn, $sql);
//Count Rows to check whether we have foods or not
$count = mysqli_num_rows($res);
//Create Serial Number VAriable and Set Default VAlue as 1
$sn=1;
if($count>0)
{
//We have food in Database
//Get the Foods from Database and Display
while($row=mysqli_fetch_assoc($res))
{
//get the values from individual columns
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$image_name = $row['image_name'];
$featured = $row['featured'];
$active = $row['active'];
?>
<tr>
<td><?php echo $sn++; ?>. </td>
<td><?php echo $title; ?></td>
<td>$<?php echo $price; ?></td>
<td>
<?php
//CHeck whether we have image or not
if($image_name=="")
{
//WE do not have image, DIslpay Error Message
echo "<div class='error'>Image not Added.</div>";
}
else
{
//WE Have Image, Display Image
?>
<img src="<?php echo SITEURL; ?>images/food/<?php echo $image_name; ?>" width="100px">
<?php
}
?>
</td>
<td><?php echo $featured; ?></td>
<td><?php echo $active; ?></td>
<td>
Update Food
Delete Food
</td>
</tr>
<?php
}
}
else
{
//Food not Added in Database
echo "<tr> <td colspan='7' class='error'> Food not Added Yet. </td> </tr>";
}
?>
</table>
</div>
</div>
<?php include('partials/footer.php'); ?>
Attached is a picture of this
What you need is a new column in the table tbl_food
Actual clumns:
//get the values from individual columns
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$image_name = $row['image_name'];
$featured = $row['featured'];
$active = $row['active'];
Add a column "owned_by" with the admin_ID of the user that added that food.
Step 1. (that's MySQL, but you can adapt to your DB)
alter table tbl_food add owned_by int;
Step 2.
when some admin add a food, you add this ID value in the insert, with others food information.
Step 3.
When some admin update the food, you check if this food is owned by this admin, and in update query you add
[..]and owned_by = admin_ID;
To accomplish this, you need that any admin has his own ID or email or access token
If all the admins are sharing the same account to upload the food, before of what I said you need to add a multiuser control access system.

binding specific data to the url

I'm trying to bind the id from a row to the href output. that is getting a url something?id=*** in order to use $_GET and bring the id on the next page.
I need to be the id on the same row that is clicked on a table I'm displaying.
If I try to bind it by stating href=" wahtever?id=<php echo $row['id'] ?> the id will return as empty. If I use a loop it works but give me all the id's on the table.
I tried different solutions I found on internet like stating echo '<td> <a href="****?id='.$row['id'].' </a></td>' or making a new selection using php code on the href link... nothing seems to work.
I'm confused, how can I make a link on a table that will include the id of the clicked row?
My code looks like this now:
<td bgcolor="#FAB1CA"><a href="view_topic.php?id=<?php $sql="SELECT * FROM forum_question ORDER BY id DESC";
$result = mysqli_query($link, $sql);
while($rows = mysqli_fetch_assoc($result){
echo $rows['ID'] ; ?>">
Just to make it clearer, it is a simple table displaying 4 columns with different data using a loop, the first column is the id and the second one would be the topic, where I trying to build the links.
It sounds like you have 5 columns in a database table and you want to show them on the page, and link the topic cell to the topic page and pass the id of that topic.
I cleaned your code up a little and gave an example of how to do that. Keep in mind, I'm using an associative array so you'll need to be sure it matches what the columns are called in your database.
<table>
<tr>
<th>ID</th>
<th>Topic</th>
<th>Answers</th>
<th>Views</th>
<th>Date</th>
</tr>
<?php
$sql="SELECT * FROM forum_question ORDER BY id DESC";
$result = mysqli_query($link, $sql);
while($row = myslqi_fetch_assoc($result)) : ?>
<tr>
<td><?php echo $row['id']; ?></td>
<td bgcolor="#FAB1CA">
<a href="view_topic.php?id=<?php echo $row['id']; ?>">
<?php echo $row['topic']; ?>
</a>
</td>
<td><?php echo $row['answers']; ?></td>
<td><?php echo $row['views']; ?></td>
<td><?php echo $row['theDate']; ?></td>
</tr>
<?php endwhile; ?>
</table>
I cant see $row variable in your code
you can use myslqi_fetch_assoc for get $row variable
i think this answer its true
<?php
$sql="SELECT * FROM forum_question ORDER BY id DESC";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result)){
?>
<td bgcolor="#FAB1CA"><a href="view_topic.php?id=<?php echo $row['id']?>go to view_topic</a></td>
<?php
}
?>

Call Two MySql Table with A Button

I have these table that list all the users of the site. I would like to add a button where in, once that is clicked, the other details of the user will show.
This is my code so far.
echo "<table border=1 align=center><tr class=style2><td>+<td>Student Name<td>Age<td>Address<td>School<td>Email";
$query = mysql_query("SELECT name, age, address, school, email FROM mst_user",$cn) or die(mysql_error());
while($row=mysql_fetch_row($query))
{
echo "<tr class=style8><td>+<td>$row[0]<td align=center> $row[1]<td align=center>$row[2]<td align=center>$row[3]<td align=center>$row[4]";
}
echo "</table>";
The code shows all the user of the site. The <td>+will be a button that when click will show the other details of the user. The other details will show or call a file which is result.php
result.php
$rs=mysql_query("select t.test_name,t.total_que,r.test_date,r.score from mst_test t, mst_result r where
t.test_id=r.test_id and r.login='$login'",$cn) or die(mysql_error());
echo "<h1 class=head1> Result </h1>";
if(mysql_num_rows($rs)<1)
{
echo "<br><br><h1 class=head1> You have not given any quiz</h1>";
exit;
}
echo "<table border=1 align=center><tr class=style2><td width=300>Test Name <td> Total<br> Question <td> Score";
while($row=mysql_fetch_row($rs))
{
echo "<tr class=style8><td>$row[0] <td align=center> $row[1] <td align=center> $row[3]";
}
echo "</table>";
my tables
Any suggestions on how can I achieve it?

upload and display multiple images for one product?

I am working on a basic ecommerce website using PHP/MYSQL. I just need to know how I can upload multiple images for a product and then display them in the products page.
as for uploading multiple images, I don't want to use uploadify or open source codes like that. i rather have 3-4 extra fileupload fields if possible at all!
And I cannot get my head around the displaying the images (multiple images for 1 product). I really don't understand how it should work! so any advice on simple terms would be appreciated.
Currently I can only upload 1 image per product.
Here is what I have so far, please ignore the mysql queries in the first file as this is a not going live yet until I have converted the mysql to mysqli. Just need to get functions sorted first:
upload.php
<?php
// Parse the form data and add inventory item to the system
if (isset($_POST['product_name'])) {
$product_name = mysql_real_escape_string($_POST['product_name']);
$price = mysql_real_escape_string($_POST['price']);
$quantity = mysql_real_escape_string($_POST['quantity']);
$category = mysql_real_escape_string($_POST['category']);
$details = mysql_real_escape_string($_POST['details']);
// See if that product name is an identical match to another product in the system
$sql = mysql_query("SELECT id FROM products WHERE product_name='$product_name' LIMIT 1");
$productMatch = mysql_num_rows($sql); // count the output amount
if ($productMatch > 0) {
echo 'Sorry you tried to place a duplicate "Product Name" into the system, click here';
exit();
}
// Add this product into the database now
$sql = mysql_query("INSERT INTO products (product_name, price, quantity, details, category, date_added)
VALUES('$product_name','$price','$quantity','$details','$category',now())") or die (mysql_error());
$pid = mysql_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../inventory_images/$newname");
header("location: add.php");
exit();
}
?>
product.php <<< this is the page that displays the product details and image.
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
include "config/connect.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = "SELECT * FROM products WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$quantity = $row["quantity"];
$category = $row["category"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
<table width="900" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="300" rowspan="5" align="right" valign="top" style="padding-top:10px;"><img src="inventory_images/<?php echo $id; ?>.jpg" width="300" height="450" alt="<?php echo $product_name; ?>" /></td>
<td width="126" height="106"> </td>
<td width="274"><h3 style="font-family:Times New Roman; font-size:1.8em;"><?php echo $product_name; ?></h3></td>
</tr>
<tr>
<td height="120"> </td>
<td><?php echo $details; ?></td>
</tr>
<tr>
<td height="110"> </td>
<td style="font-family:Times New Roman; font-size:1.8em;">Price: £<?php echo $price; ?></td>
</tr>
<tr>
<td height="50"> </td>
<td style="font-family:Times New Roman; font-size:1.8em;">Quantity Left: <?php echo $quantity; ?></td>
</tr>
</table>
Thanks
Well the way you are currently doing it isn't really setup for multiple photos since you aren't storing a reference to the photo in the database. You are simply renaming the image to the primary key of the product. So you will need to either do something like 1_1.jpg 1_2.jpg or you will need to create a database table that stores the filename and the product id so you can have a one to many relationship.
As for uploading more images just add more file inputs to your form.
And for displaying you will need to either pull records from the photo db table or use glob() to find all the files that start with the primary key + '_'.
Also FYI mysql functions should no longer be used as they are deprecated.

PHP website search and display items

I am creating a dummy online store to illustrate some real world functionality which one of them is to search the website for items i.e.
I have written PHP code to deal with this scenario but it does not work properly. Wchat it does dough is it matches the results and the number of results but it does not display them which I of course wont it to do.
Been trying to look for answers on GOOGLE but didn't find corresponding solution or a tip to my problem.
Here am gonna list the code I am using:
PHP code (search.php):
<?php
session_start();
include('connect_mysql.php');
$product_name = 'product_name';
$product_qua = 'product_qua';
$product_price = 'product_price';
$product_image = 'product_image';
$product_des = 'product_des';
if (isset($_POST['keyword']))
{
$search = $_POST['keyword'];
if (!empty($search))
{
$query = "SELECT product_name FROM products WHERE product_name='$search'";
$query_search = mysql_query($query);
echo mysql_num_rows($query_search);
if (mysql_num_rows($query_search) >=1)
{
echo 'Results found: <br>';
while ($query_row = mysql_fetch_row($query_search))
{
echo $query_row['product_name'];
}
while($rows = mysql_fetch_array($query_search))
{ ?>
<table id='display'>
<tr><td><?php echo "<img src=$rows[$product_image] class='grow'>" ?></td></tr>
<tr>
<th></th>
<th><strong>Avalible</strong></th>
<th><strong>Price</strong></th>
<th><strong>Description</strong></th>
</tr>
<tr>
<td width='290px'><?php echo "$rows[$product_name]" ?></td>
<td width='290px'><?php echo "$rows[$product_qua]" ?></td>
<td width='290px'><?php echo "£ $rows[$product_price]" ?></td>
<td width='290px'><?php echo "$rows[$product_des]" ?></td>
</tr>
<tr>
<td><p>Please Login To purchase this item </p><br />Login</td>
</tr>
</table>
<?php
}
} else {
echo 'NO results found.';
}
}
}
?>
HTML code (index.php):
<form action="search.php" method="post">
<input type="text" name="keyword" size="20" placeholder="Search for products...."/>
<input type="submit" value="Search >>" />
</form>
Print screen of current result:
As you have have noticed it also says 3 results have been found which is correct considering i have searched for ever which is a common name of my product but drows up only two tables moreover they are empty.
website url: http://studentnet.kingston.ac.uk/~k1024026/index.php
finally my product table consists of : product_id product_name product_qua product_price product_image product_des product_type attrebiutes/columns
anyone can spot where i might be going wrong with this....?
First, try removing this
while ($query_row = mysql_fetch_row($query_search))
{
echo $query_row['product_name'];
}
I also noticed a few bad typo in your code :
table id="display" an id should be unique. If you iterate over it and still want it to be an id, put display-n instead, n being the unique id of the product for example. (or use class="display" instead of id)
You should take a look at sql injection and how to defeat them.
I might rather do this:
$query = "SELECT product_name FROM products WHERE product_name LIKE %" . $search . "%";
Hope it will help. Then use a foreach loop to run through the result like:
foreach ($search as $key => $result){
echo $result . '<br />';
}
mysql_fetch_row( $query_search) returns a plain array not an associative array but you are trying to access its values using keys - $query_row [ 'product_name' ]. Rather use _fetch_array
There are lots of syntactical errors. There is a space between function name and list of parameters.
Don't use mysql_. They are deprecated (read: dead). Use PDO instead.

Categories