Only getting value of one row back from database - php

I am trying to create a simple cart system for my online shop. In order to store add the items the user selects to the cart, I have created an add to cart button under my items. My goal is that when this button is pressed the uid that is saved in my database, of the item selected is saved on a current session. However, when I press this button, for some reason it is always the id of the third item (cabuid 3) that gets saved onto the session, regardless of which item I add to cart.
Here is my database
index.php file
<form style="border:1px solid #ccc" method="POST" enctype="multipart/form-data">
<?php
if (isset($_POST['add'])){
print_r($_POST['product_id']);
}
include __DIR__.'../includes/dbh.includes.php';
$sql = "SELECT * FROM boots";
$gotResults = mysqli_query($connection,$sql);
if($gotResults) {
if(mysqli_num_rows($gotResults)>0) {
while($row = mysqli_fetch_array($gotResults)){
?>
<div class="row">
<div class="column">
<div class="card">
<img src="images/<?php echo $row['image']?>" style="width:100%">
<div class="container">
<h2>
<?php echo $row['cabname']; ?> </h2>
<p><?php echo $row['cabdescription']; ?></p>
<p><?php echo $row['cabprice']; ?> € </p>
<p><button type="submit" class="button" name="add">Add to cart</button></p>
<input type='hidden' name='product_id' value="<?php echo $row['cabuid']; ?>">
</div>
</div>
</div>
<?php
}
}
}
?>
dbh.includes.php
<?php
$serverName = "localhost";
$dbUsername ="root";
$dbPassword ="";
$dbName = "webvacser";
$connection = mysqli_connect($serverName, $dbUsername, $dbPassword, $dbName);
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
?>

I would make `n` forms, one per iteration of the loop
<?php
include __DIR__.'../includes/dbh.includes.php';
$sql = "SELECT * FROM boots";
$gotResults = mysqli_query($connection,$sql);
if($gotResults) {
if(mysqli_num_rows($gotResults)>0) {
while($row = mysqli_fetch_array($gotResults)){
?>
<div class="row">
<div class="column">
<div class="card">
<img src="images/<?php echo $row['image']?>" style="width:100%">
<div class="container">
<h2> <?php echo $row['cabname']; ?> </h2>
<p><?php echo $row['cabdescription']; ?></p>
<p><?php echo $row['cabprice']; ?> € </p>
<form style="border:1px solid #ccc" method="POST" enctype="multipart/form-data">
<p><button type="submit" class="button" name="add">Add to cart</button></p>
<input type='hidden' name='product_id' value="<?php echo $row['cabuid']; ?>">
</form>
</div>
</div>
</div>
<?php
}
}
}
?>
Now the 3 forms are unique and when you press the button inside any one of them the correct data from the associated hidden input will be sent to the receiving script

Related

(PHP) Shopping Cart

I am trying to create a shopping cart with PHP, but, once the user leaves the cart area, all of the products disappear. That's what I'm trying to do:
<?php foreach($almofadas as $almofadas):?>
<form action="cart.php" method="GET">
<div class="base col-6 col-sm-4 col-md-5 col-lg-4 col-xl-4">
<div class="card">
<img src="uploads/<?php echo $almofadas['imagem']; ?>" alt="">
<div class="content-c">
<div class="row-p">
<div class="details">
<span><?php echo $almofadas['pnome'] ; ?></span>
</div>
<div class="price">R$ <?php echo $almofadas['preço'];?> </div>
</div>
<input type="hidden" name="id" value="<?php echo $almofadas['p_id']?>">
<div style="margin-top: 10px;">
<div style="margin-bottom: 5px;"><button class="buttons-1" data-toggle="modal" data-target="#myModal">Detalhes</button></div>
<div><button class="buttons-2" type="submit">Adicionar ao Carrinho</a> </button></div>
</div>
</div>
</div>
</div>
</form>
<?php endforeach; ?>
Now the cart system:
<?php
session_start();
require_once 'conn.php';
$_SESSION['id'] = $_GET['id'];
$result_pedido = "SELECT * FROM tb_produtos WHERE p_id = '{$_SESSION['id']}'";
$resultado_pedido = mysqli_query($conn, $result_pedido);
$pedidos = mysqli_fetch_all($resultado_pedido, MYSQLI_ASSOC);
?>
Here I can only add one product and, I can't save it into a $_SESSION, having said that the product disapears once iI leave the cart.
<?php foreach($pedidos as $pedidos):?>
<tr>
<td>
<div class="cart-img">
<img src="uploads/<?php echo $pedidos['imagem'];?>" width="125px">
</div>
</td>
<td>
<div class="cart-model">
<?php echo $pedidos['pnome'] ; ?>
</div>
</td>
<td>
<div class="cart-quantity">
<input class="i-quantity" type="number" value="1">
</div>
</td>
<td>
<div class="cart-price">
R$<?php echo $pedidos['preço'] ; ?>
</div>
</td>
</tr>
</tbody>
</table>
<?php endforeach; ?>
If you check this line:
$_SESSION['id'] = $_GET['id'];
This mean the "id" in your $_SESSION is always set to $_GET['id'], even if it is empty. So it is reset every time the user visit a page.
You should:
have some mechanism to store your shopping cart content. There is none in your code; and
have a way to check if the user visits a new id before storing it to shopping cart.
For example,
<?php
/**
* This only make sense if this script is called
* by some AJAX / javascript interaction to specifically
* add a new item to cart.
*/
session_start();
require_once 'conn.php';
if (isset($_GET['id']) && !empty($_GET['id'])) {
$_SESSION['id'] = $_GET['id'];
}
$result_pedido = "SELECT * FROM tb_produtos WHERE p_id = '{$_SESSION['id']}'";
$resultado_pedido = mysqli_query($conn, $result_pedido);
$pedidos = mysqli_fetch_all($resultado_pedido, MYSQLI_ASSOC);
// If the user visits a path where the $_GET['id'] have result in
// database and the user specified that he / she want to save something
// to his / her cart.
if (isset($_GET['id']) && !empty($_GET['id']) && !empty($pedidos)) {
if (!isset($_SESSION['cart'])) $_SESSION['cart'] = []; // initialize if not exists.
$_SESSION['cart'] = array_merge($_SESSION['cart'], $pedidos);
}
?>
Note: the quantity should be set to the cart somehow. You need to change the data structure to set or increment the "qty". But this is at least a start.

MySQL on PHP need 2 reloads to update the values

I made a message deleter button, but I need 2 reloads to appear the changes...
(The rest of the code work, so it's normal that I don't show you the rest of the code...)
<?php while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST"><button name="delete<?= $r['id'] ?>">Test</button></form>
<?php
$test = "delete".$r['id'];
if(isset($_POST[$test])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($r['id']));
$success = "Your message was successfully removed !";
}
?>
</div>
</div>
<br>
<?php } ?>
UPDATE:
I added the deleting code at the top of my php code, and it's working, thanks to Ray Andison
By the way thanks to keidakida too; he helped me to find a solution to my value problem. (And I think he don't know that)
Your form doesn't contain any data (the id to be deleted) or action (page to submit data to)?
<form method="POST" action="thispage.php">
<input id="test" name="test" type="hidden" value="<?= $r['id'] ?>">
<input type="submit">
</form>
UPDATED:
<?
if(isset($_POST[id])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST[id]));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()){
echo '
<div class="message" id="'.$r[id].'">
<div class="profile">
<img class="avatar" src="members/avatars/';
if(empty(get_avatar($r[id_author]))){
echo "default.png";
}else{
echo get_avatar($r[id_author]);
}
echo '
" width="150" height="150">
<h3 style="text-align:center;">
'.get_username($r[id_author]).'
</h3>
</div>
<div class="content">
<div class="date">
'.date('d F Y - g:iA', strtotime($r[date_hour_post])).'
</div>
<br>
<br>
'.htmlspecialchars_decode($r[content]).'
<form method="POST" action="thispage.php">
<input id="id" name="id" type="hidden" value="'.$r[id].'">
<input type="submit">
</form>
</div>
</div>';
}
?>
This is how I would code this, you need to change the action="thispage.php" to be the name of itself so it posts to itself, replace with the actual name of your php file
It is because the delete PHP code is at the bottom. Actions such as delete should be at the top of the HTML or while loops before presenting the data. SO try this:
<?php
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
$success = "Your message was successfully removed !";
}
while($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<div class="profile">
<img class="avatar" src="members/avatars/<?php if(empty(get_avatar($r['id_author']))) { echo "default.png"; } else { echo get_avatar($r['id_author']); } ?>" width="150" height="150">
<h3 style="text-align: center;"><?= get_username($r['id_author']) ?></h3>
</div>
<div class="content">
<div class="date">
<?= date('d F Y - g:iA', strtotime($r['date_hour_post'])) ?>
</div>
<br><br>
<?= htmlspecialchars_decode($r['content']) ?>
<form method="POST">
<button type="button" name="delete" value="<?php echo $r['id']; ?>">Test</button>
</form>
</div>
</div>
<br>
<?php
}
?>
But you can do the same functionality without any page reload. Check AJAX PHP
Since it would be better and easier with AJAX, this is how it goes:
main.php
<?php
while ($r = $replies->fetch()) { ?>
<div class="message" id="<?= $r['id'] ?>">
<?php echo htmlspecialchars_decode($r['content']) ?>
<button onclick="delete('<?php echo $r['id']; ?>')">Delete</button>
</div>
<br>
<?php } ?>
<script>
function delete(id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("Delete successfully");
location.reload();
}
};
xmlhttp.open("POST", "delete.php", true);
// Mandatory for simple POST request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send id you want to delete
xmlhttp.send("id=" + id);
}
</script>
And make another PHP file name is delete.php like this:
<?php
include 'YOUR_DB_Connect.php';
if(isset($_POST["delete"])) {
$delete = $db->prepare('DELETE FROM f_messages WHERE id = ?');
$delete->execute(array($_POST['delete']));
}
?>

data insert into database automatically in php

I have a problem which is the user when write in my comments form is insert successfully but when I refresh the page it will insert the last comments again , I read the solution in this link how to stop data automatically insert into database in php
but does not work for me
this is my codes I would appreciate for your help :)
file viewhospital.php contain include comments.php file
--look at the bottom of the codes--
<?php
include ('header.php');
if(!isset($_GET['hospital_id'])){
echo '<div class="alert alert-danger" role="alert"><b>You should choose hospital before opening this page!</b></div>';
include ('footer.php');
die();
}
include ('setting.php');
$sql = 'select * from hospital where hid = '. $_GET['hospital_id'];
$result = $conn->query($sql) or die(mysql_error($conn));
$hospital = null;
if ($result->num_rows > 0) {
$hospital = $result->fetch_assoc();
} else {
die('Could not find hospital!');
}
$sql = 'select * from doctor where hospital_id = '. $_GET['hospital_id'];
$doctor_result = $conn->query($sql) or die(mysql_error($conn));
$conn->close();
?>
<div class="row">
<div class="col-md-6">
<p class="text-center">
<img src="<?php echo $hospital['image']; ?>" class="img-thumbnail" style="height: 400px;">
</p>
</div>
<div class="col-md-6">
<p class="text-center">
<img class="img-thumbnail" src="https://maps.googleapis.com/maps/api/staticmap?center=<?php echo $hospital['location']; ?>&zoom=13&size=400x400&maptype=roadmap&markers=color:blue%7Clabel:S%7C<?php echo $hospital['location']; ?>&key=AIzaSyD59nHXpZgqZwjJvsAcPe2CYcIEWoaQ9yY" style="height: 400px;">
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h1 class="page-header">
<?php echo $hospital['name']; ?>
</h1>
<p>
<?php echo $hospital['description']; ?>
</p>
<p>
Address: <?php echo $hospital['address']; ?>
</p>
<p>
Phone: <?php echo $hospital['phone']; ?>
</p>
<p>
Go To Hospital
</p>
<p>
Online Appointment
</p>
</div>
</div>
<!--<div class="row">
<div class="col-md-12 text-center">
<div class="btn-group" role="group" aria-label="...">
<a type="button" class="btn btn-info">Edit</a>
<a type="button" class="btn btn-danger">Remove</a>
<a type="button" class="btn btn-primary" href="doctor_form.php?hospital_id=<?php echo $hospital['hid']; ?>">Add Doctor</a>
</div>
</div>
</div>-->
<div class="row">
<div class="col-md-12">
<table class="table table-striped">
<caption>Doctors:</caption>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Field</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if ($doctor_result->num_rows > 0) {
while($row = $doctor_result->fetch_assoc()) {
?>
<tr>
<th scope="row">
<?php echo $row['did'];?>
</th>
<td>
<?php echo $row['name'];?>
</td>
<td>
<?php echo $row['field'];?>
</td>
<td>View</td>
</tr>
<?php
}
}else{
?>
<tr>
<th scope="row"></th>
<td>No doctors found</td>
<td></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<?php
include ('comments.php');
include ('footer.php');
?>
the comments.php file
<?PHP
# comments PHP code
date_default_timezone_set('Asia/Riyadh');
function setComments (){
if (isset($_POST['submitComments'])){
include('setting.php');
//$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments ( date, message) VALUE ( '$date', '$message')";
$result = mysqli_query($conn,$sql);
}
}
function getComments (){
if (isset($_POST['submitComments'])){
include('setting.php');
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while ($row = $result->fetch_assoc()){
echo "<div class='comments-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}
}
echo "
<form action='".setComments ()."' method='POST'>
<input type='hidden' name='uid' value=''>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message' class='form-control' rows='3'></textarea>
<br>
<button type='submit' name='submitComments' class='btn btn-primary'>Comments</button>
</form>
<br><br>
";
getComments ();
?>
When you refresh in the browser, you send the last request again. That request was the POST of the form. So the user (browser) is telling the code to insert another comment.
Generally this is handled by redirecting after posting a form, rather than re-displaying the form again. Move all of your logic for (and only for) inserting the new content to its own PHP file (something like addComment.php) and have the form post to that file. Then in that file ensure that there is no actual output except perhaps to display an error message if something goes wrong?) and just a redirect back to the page:
header("Location: viewhospital.php");
This will instruct the browser in the response to make a new GET request for viewhospital.php. So if the user reloads the browser, all they're doing is repeating that GET request.

Dynamic Html pages from Mysql with PHP

I'm working on a website with php and mysql and have some problems to generate web pages URL from database rows.
I have only 3 page connection.php (mysql connection) index.php (where show al products/contents thumbnails with button with product details URL) and details.php where i want show info for single product.
from index.php i add a link to redirect to details.php page with this:
<a href="details.php?id=<?php echo $row['ID']; ?>"
it's work but Big problem is in details.php because the script don't show a single products details, but show all products, please someone can help me? Thank you
index.php code
......other html code......
<div class="row">
<?php
require_once 'connection.php';
$query = "SELECT * FROM campi_name";
$stmt = $DBcon->prepare( $query );
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<div class="col-sm-4 col-md-3">
<div class="thumbnail">
<img src="<?php echo $row['Thumbnail']; ?>" alt="<?php echo $row['Title']; ? >">
<div class="caption">
<h4><?php echo substr($row['Title'], 0, 30); ?></h4>
<p><?php echo $row['Brand']; ?></p>
<?php echo $row['ID']; ?>
<p>Cofronta Dettagli</p>
</div>
</div>
</div>
<?php
}
?>
......other html code......
connection.php code
$DBhost = "localhost";
$DBuser = "root";
$DBpass = "";
$DBname = "prodotti";
try {
$DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex){
die($ex->getMessage());
}
?>
details.php code
......other html code......
<div class="container">
<div class="row">
<?php
require_once 'connection.php';
$query = "SELECT * FROM campi_name";
$stmt = $DBcon->prepare( $query );
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<div class="col-sm-4 stylerow">
<a href="<?php echo $row['AffiliateLink']; ?>" class="thumbnail">
<img src="<?php echo $row['Thumbnail']; ?>" alt="<?php echo $row['Title']; ? >">
</a>
</div>
<div class="col-sm-8 stylerow">
<h2><?php echo $row['Title']; ?></h2>
<p><?php echo $row['Brand']; ?></p>
<button type="button" class="btn btn-primary btn-lg">Amazon</button>
</div>
</div>
</div><!-- /.container -->
......other html code......
Add
$id=$_GET['id'];
edit following line in your code
$query = "SELECT * FROM campi_name";
To
$query = "SELECT * FROM campi_name where id="'.$id.'" ";

PHP Session data gets lost after page refresh

I am working on this product page. Basically it shows a product by ID and gives you the option to add it to your cart. My problem is that the data stored in $_SESSION gets lost every time I refresh the page.
<?php
include 'scripts\init.php'; // contains session_start(); and the functions
if(!IsProductIdSafeAndExisting())
{
session_write_close();
header("Location: shop.php");
die();
}
if(isset($_POST['quantity'])) // adds current item to cart but gets lost after refresh
AddItemToCart($_GET["id"],$_POST['quantity']);
$id = $_GET["id"];
$name = GetProductField($id,"name");
$image = GetProductField($id,"image");
$price = GetProductField($id,"price");
$stock = GetProductField($id,"stock");
$details = GetProductField($id,"details");
$total_products = GetTotalProducts();
$total_price = GetTotalProductsPrice();
LoadHeaderByTitle($name." | Magazin Vinuri");
?>
<body>
<div id="page">
<?php LoadNavigationBy(""); ?>
<div id="body">
<div class="header">
<div>
<h1><?php echo $name; ?></h1>
</div>
</div>
<div class="singlepost">
<div class="featured">
<img src="images/<?php echo $image; ?>" alt="">
<h1><?php echo $name.' - '.$price.' lei'; ?></h1>
<span>Mai sunt <?php echo '<strong>'.$stock.'</strong>'; ?> bucati ramase.</span>
<p><?php echo $details; ?></p>
<div class="additem">
<center>
<form method="POST" action="product.php?id=<?php echo $id; ?>">
<input type="text" name="quantity" value="Cantitate" onblur="this.value=!this.value?'Cantitate':this.value;" onfocus="this.select()" onclick="this.value='';">
<input type="submit" value="Adauga" id="submit">
</form>
</center>
</div>
</div>
<div class="sidebar">
<h1>Cosul tau</h1>
<img src="images/cart.png" alt="">
<h2><?php echo $total_price; ?> lei</h2><br>
<p>Momentan aveti <strong><?php echo $total_products; ?></strong> produse in cos. Pentru a edita lista de produse dati click pe butonul de mai jos.</p>
vezi cumparaturi
</div>
</div>
</div>
<?php include 'scripts\overall\foot.php' ?>
init.php
<?php
session_start();
require 'database\connect.php';
require 'functions\general.php';
require 'functions\engine.php';
?>
the problem was that I stored product ids like this $_SESSION[10]=something; which was wrong because it the same as $_SESSION['10']=something; so i changed it to $_SESSION['id_10']=something; and now it works

Categories