I am creating a website in which I need to sell products. I am stuck at the product page of the website.
The big e-commerce website like amazon.com must have a template of the product page and they dynamically load all the data including image of product, price, reviews from the database. I also want to create a similar product page where on clicking a link of product, it automatically loads all the images, price and info stored in the database and show it.
If another product is clicked, everything loads on that very same html/php template page and I don't have to make different page for different products. How can I do that?
I have been searching for a solution to this for many days, but I don't know what exactly to search for to get the answer.
Create a php page, say, load_products.php and pass get parameters like load_products.php?product_id=1.
Change the id (as per the database setup) and get the corresponding product details from database.
Edit : Detailed Answer
Database
Table: table_products
+--------------------------+---
| id | name | details | ...
+--------------------------+---
| 1 | Product1 | Details1 | ...
| 2 | Product2 | Details2 | ...
...
+--------------------------+---
I shall show you how it is done with MySQL database.
PHP Code
load_products.php
// Establish connection to database
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('products_database_name');
// Display All the Products
$res=mysql_query("SELECT * FROM table_products");
echo "<table>";
while($row=mysql_fetch_array($res))
{
$id=$row["id"];
$name=$row["name"];
echo "<a href='load_products?id=$id'>$name</a>";
}
// Display the details of a particular product based on the input click from user
if(isset($_GET["id"]))
{
$id=$_GET["id"];
$res=mysql_query("SELECT * FROM table_products WHERE id=$id");
echo "<table>";
while($row=mysql_fetch_array($res))
{
$details=$row["details"];
$name=$row["name"];
echo "<tr><td>$name</td><td>$details</td></tr>";
}
echo "</table>";
}
A really bare bones implementation, yet fully working and you can see the output on your localhost in 15 minutes. You can build on top of this.
You can search for : Loading images from database, javascript, jquery to enhance the website interface, using ajax on top of this and so on..
Please find the Improved version
products.php page
// Establish connection to database
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('products_database_name');
// Display All the Products
$res=mysql_query("SELECT * FROM table_products");
$productsPerRow = 4;
$columnWidth = (int)(100 / $productsPerRow);
$count = 0; //count product displayed
echo "<table>
<tr>";
while($row=mysql_fetch_array($res))
{
$count++;
$id = $row["id"];
$name = $row["name"];
$image = $row["image"]; //image name with extension, upload it in the images folder
echo "<td width='" . $columnWidth ."' >
<img src='images/" . $image ."' border='0'/><br />
<a href='load_product.php?id=$id'>$name</a>
</td>";
if($count%$productsPerRow==0)
echo"</tr><tr>";
}
//close empty cells
if ($count % $productsPerRow > 0) {
echo "<td colspan='" . ($productsPerRow - ($count % $productsPerRow)) .
"'> </td></tr>";
}
//close table
echo "</table>";
load_product.php page
// Establish connection to database
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('products_database_name');
// Display the details of a particular product based on the input click from user
if(isset($_GET["id"]))
{
$id=$_GET["id"];
$res=mysql_query("SELECT * FROM table_products WHERE id=$id");
echo "<table>";
while($row=mysql_fetch_array($res))
{
$details=$row["details"];
$name=$row["name"];
echo "<tr><td>$name</td><td>$details</td></tr>";
}
echo "</table>";
}
Related
I'm not sure how well i'll be able to explain this, but here goes.
I have a website for attractions. Let's say that one of my categories is Historical villages.
When the user opens the Historical villages page he gets a list of villages displayed from the database. The way I display them is: Name plus a picture of the attraction.
What I want to do is unable the user to click on of the villages (by making the name and picture a clickable link) and the user to be redirected to a page that will run a php script that will display more information from the database about the selected village. That way I will only have one page for all attractions that will display different information every time a user selects something different, instead of hardcoding all the pages.
This is my code displaying the lits of villages:
$sql = "SELECT `Name`, `Location`, `Description`, `Airport`, `imglink`, `pagelink` "
. "FROM `attractions` "
. "WHERE `Category`='HistV'";
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['Name'];
echo "<img src='" . $row['imglink'] . "'>";
}
Do any of you have any suggestions on how to make this output a link and the make it run the PHP to show the users selection?
Your while condition changed to like this,
while ($row = mysql_fetch_assoc($result)) {
/* For example ,
$row['pagelink'] must contains the pagelink as belowed here
/viewVillage.php?village_id=1
/viewVillage.php?village_id=2 and so on. */
echo "<a href='" . $row['pagelink'] . "'>"
. $row['Name'] .
. "<img src='" . $row['imglink'] . "'>
</a>";
}
This will generate your list of villages like this,
<a href="/viewVillage.php?village_id=1">
Village name 1
Village Image 1
</a>
<a href="/viewVillage.php?village_id=2">
Village name 2
Village Image 2
</a>
<a href="/viewVillage.php?village_id=3">
Village name 3
Village Image 3
</a>
.....
When you click on any of the link, it will redirected to viewVillage.php page. Now you can get the particular village using $_GET['village_id']
viewVillage.php
if(isset($_GET['village_id']]) && $_SERVER['REQUEST_METHOD'] == 'GET' ) {
$villageId = $_GET['village_id'];
// Then do your stuff over here
}
On your current page
while ($row = mysql_fetch_assoc($result)) {
/* For example ,
$row['pagelink'] should be a village id */
echo "<a href='/attractions.php?village=" . $row['pagelink'] . "'>"
. $row['Name'] .
. "<img src='" . $row['imglink'] . "'>
</a>";
}
Now it would print something like
Vilage Name <img src="urltoimage">
When you click on this link you will be sent to a file called "attractions.php"
Create this file in the same directory and it should have the following php in it
<?php
$villageId = $_GET['village']; //this gets the id of the village from the url and stores
//it in a variable
//now that you have the id of the village, perform your sql lookup here
//of course you will have to fill this is, as I don't know your actual table fields and names
$sql = "SELECT * FROM Attractions WHERE villageID = `$villageID`";
//now perform the query, loop through and print out your results
?>
Does this make sense?
I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.
Hello my fellow coding buddies.
I need some help, i've got this problem.
I have this database, and i want to retrive this data into my code via JS.
My database info:
create table datadatabase (
id int(10) not null AUTO_INCREMENT PRIMARY KEY,
name varchar(25) not null default '',
text longtext(25) not null default '',
image blob not null );
And i want the data into these fields.
<img src="<?php echo $img ?>"/>
<h3> <?php echo $text.','.$name ?> </h3>
But the problem is, the text & image is a slider and i want retrive new data everytime there is a function click on the "Next" button & the ID should be random so the first slides could be id 99 and the next slide could be 158 and so on.
$('.Next').click(function(e) {
e.preventDefault();
Slide.appendSlide('<img src"<?php echo $img ?>"/><h3> </h3>')
})
How should i approach this? AND Thanks you so much. :)
First of all, it is not a good practice to store images in databases, but if you want to do this you need to create a script that output an specific image from the db (i.e. by ID) and then output the raw data with the specific content-type. (I also recommend to insert the type of the image in one of the database fields).
url: /image.php?id=5
image.php
<?php
$id = isset($_GET['id'])?intval($_GET['id']):0;
$query = mysql_query("SELECT img FROM datadatabase WHERE id = '$id'");
$row = mysql_fetch_array($query);
if($type=="pjpeg")
$type="jpeg"; // the type could change depending on the database image type
header("Content-type:$type");
echo $row['image'];
?>
for the other fields , just read the database as usual. The result:
<img src="http://..../image.php?id=<?php echo $id ?>"/>
<h3> <?php echo $text.','.$name ?> </h3>
$('.Next').click(function(e) {
e.preventDefault();
Slide.appendSlide('<img src"http://..../image.php?id=<?php echo $id?>"/><h3> </h3>')
});
It is recommended as well implementing cache and image resizing before upload to avoid server payload.
There are others approaches like base64. I prefer by myself using the filesystem with image metadata instead of using only the database for image storage to make it scalable.
Insert.php :
$bin_string = file_get_contents($_FILES["file"]["name"]);
$mysqli->query("INSERT INTO upload(image) VALUES ('" . $bin_string . "')");
Retrieve.php?id=1 :
$result = $mysqli->query("SELECT * FROM upload id=1");
$output_bin_string = $result["image"];
header("Content-Type: image/png");
header("Content-Length: " . strlen($output_bin_string ));
echo $output_bin_string;
Access Via Js :
<img src="Retrieve.php?id=1" />
First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>
I have a table generated from some PHP code that lists a SMALL amount of important information for employees. I want to make it so each row, or at least one element in each row can be clicked on so the user will be redirected to ALL of the information (pulled from MySQL database) related to the employee who was clicked on. I am not sure how would be the best way to go about this, but I am open to suggestions. I would like to stick to PHP and/or JavaScript. Below is the code for my table:
<table>
<tr>
<td id="content_heading" width="25px">ID</td>
<td id="content_heading" width="150px">Last Name</td>
<td id="content_heading" width="150px">First Name</td>
<td id="content_heading" width="75px">SSN</td>
</tr>
<?php
$user = 'user';
$pass = 'pass';
$server = 'localhost';
$link = mysql_connect($server, $user, $pass);
if (!$link){
die('Could not connect to database!' . mysql_error());
}
mysql_select_db('mydb', $link);
$query = "SELECT * FROM employees";
$result = mysql_query($query);
mysql_close($link);
$num = mysql_num_rows($result);
for ($i = 0; $i < $num; $i++){
$row = mysql_fetch_array($result);
$class = (($i % 2) == 0) ? "table_odd_row" : "table_even_row";
echo "<tr class=".$class.">";
echo "<td>".$row[id]."</td>";
echo "<td>".$row[l_name]."</td>";
echo "<td>".$row[f_name]."</td>";
echo "<td>".$row[ssn]."</td>";
echo "</tr>";
}
?>
</table>
EDIT
Ok, after modifying what #DrColossos posted I have been able to get my links to work correctly, but now I'm having trouble with the uniqueness part. Below is the code I am now using to create my table:
echo "<td>".$row[id]."</td>";
echo "<td>".$row[l_name]."</td>";
echo "<td>".$row[f_name]."</td>";
echo "<td>".$row[ssn]."</td>";
This makes all of the elements of a row hyperlink to Edit_Employee.php?**id**. For instance if the id was one the hyperlink would be Edit_Employees.php?1. Now what do I need to do in my Edit_Employee.php page to get or recognize the id in the link, because it is that id that is unique and that is what I need to base my MySQL search on.
EDIT
Figured it out. This did the trick:
$id = $_GET['id'];
I found that creating my links as I did makes the id a global variable which PHP can pull from the hyperlink. I used the code above in the page that the hyperlink points to and I was able to get what I wanted. Not too hard, but frustrating if you don't know how it is done!
You can already create an unique link with the "ID" of each employee.
You could do the following:
echo "<td><a href="employee.php?id=\"" . $row['id'] . "\">" . $row['id'] . "</td>";
or more readable
echo "<td><a href="employee.php?id=\"{$row['id']}\">{$row['id']}</td>";
Then you can use the employee.php to display it's detail (the id will be in $_GET['id'], see here). Don't forget to check the value of $_GET['id'] before you process it, since it can contain harmfull data (e.g. SQL-Injection).
BTW, the HTML attribute 'id' that you use in the table id="content_heading" is supposed to be unique on the site, just as a site note.