I am doing a simple php cart. Basically is for learning purpose and I am trying to search solution for my question. However, i am not sure what is the keyword for my question. Hence, I post it here.
echo "<p>Product A | <a href='product.php?id=a'>Add to Cart</a></p>";
echo "<p>Product B | <a href='product.php?id=b'>Add to Cart</a></p>";
echo "<p>Product C | <a href='product.php?id=c'>Add to Cart</a></p>";
Basically, every product shares the same landing page -> product.php just like normal shopping cart. So when user clicks product A "Add to Cart", it will land on produt.php?id=a , if product B, then will be produt.php?id=b . My questions is how to make the url sth like I mentioned?
Please refer to a screenshot.
Since the id
parameter is in the url it is called a GET
parameter. You can access to GET parameters using the global variable $_GET
.
In product.php
you should have something like:
if(isset($_GET['id'])){
$id = $_GET['id'];
if($id=='a'){
// do something
}
else if($id=='b'){
// do something else
}
}
if(isset($_GET['id'])){
if(is_numeric($_GET['id']))
{
$id = $_GET['id'];
if($id=='a')
{
}
else if($id=='b')
{
// do something else
}else
{
echo "product does not exists";
}
}
else{
echo "product does not exists";
}
}else
{
echo "product does not exists";
}
Try the following:
// Show all products
$q = mysqli_query( $con, "SELECT `id` FROM `products`" );
if( mysqli_num_rows( $q ) > 0 ) { // Check if there are results
while( $row = mysqli_fetch_assoc( $q ) ) {
echo '<p>Product A | <a href="product.php?id='.$row['id'].'">Add to Cart</a></p>';
}
}
In product.php
function productExists( $id ) {
if( !empty( $id ) ) {
$q = mysqli_query( $con, "SELECT `id` FROM `products` WHERE `id` = $id");
if( mysqli_num_rows( $q ) > 0 ) {
return true;
} else {
return false;
}
} else {
return false;
}
}
function productData( $id ) {
if( !empty( $id ) ) {
$q = mysqli_query( $con, "SELECT `id`, `product_name`, `product_price`, `product_quantity`, `product_image` FROM `products` WHERE `id` = $id");
if( mysqli_num_rows( $q ) > 0 ) {
$data = array(); // Store data
while( $row = mysqli_fetch_assoc( $q ) ) {
$data[] = $row;
}
if( !empty( $data ) ) { // Make sure all data is gathered before proceeding
return $data;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
if( !empty( $_GET['id'] ) ) { // empty does the same as isset() but also checks if the value is not empty
$id = (int)mysqli_real_escape_string( $con, $_GET['id'] );
if( productExists( $id ) ) {
$data = productData( $id );
echo 'Product: '.$data['product_name']; // Etc.
} else {
echo 'Product doesn\'t exists';
}
}
When adjusting some of the code you're also able to get the other columns