Hello I'm making a shop in php where I populate the shop with a while loop so all the shop items from my database are displayed. This works fine but I have an issue when I try to update the stock count and money left on the account when I press the buy button.
The $ItemCost variable only saves the last populated item cost and I'm not sure how to save the cost of each item to insert it into the database.
Also the $StockCount variable sets the stockcount to 1.
How can I fix this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "useraccounts";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$GatherItems = "SELECT * FROM shopitems WHERE StockCount > 0 ORDER BY`shopitems`.`Cost` DESC";
$result = $conn->query($GatherItems);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ItemName = $row['ItemName'];
$ItemCost = $row['Cost'];
$ID = $row['ID'];
$StockCount = $row['StockCount'];
$Money = $row['Money'];
echo "<div class='test'>$ItemName</div>";
echo "<div class='test1'>$ItemCost </div>";
echo "<input type='submit' class='btn btn-primary' name='Buy' value='Buy Now'/>";
}
$NewTotal = $Money - $ItemCost;
$Inventory = "UPDATE shopitems SET StockCount = $StockCount-1, Money = $NewTotal WHERE ID = $ID";
if(isset($_POST['Buy'])){
if ($conn->query($Inventory) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $Inventory . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
As #Sean said, you can do this like :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "useraccounts";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['Buy'])){
// update stock and money
$ID = $_POST['ID'];
$Money = $_POST['Money'];
$ItemCost = $_POST['ItemCost'];
$NewTotal = $Money - $ItemCost;
$Inventory = "UPDATE shopitems SET StockCount = $StockCount-1, Money =
$NewTotal WHERE ID = $ID";
if ($conn->query($Inventory) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $Inventory . "<br>" . $conn->error;
}
}
// display items
$GatherItems = "SELECT * FROM shopitems WHERE StockCount > 0 ORDER
BY`shopitems`.`Cost` DESC";
$result = $conn->query($GatherItems);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ItemName = $row['ItemName'];
$ItemCost = $row['Cost'];
$ID = $row['ID'];
$StockCount = $row['StockCount'];
$Money = $row['Money'];
echo "<form method='post' action=''>";
echo "<div class='test'>$ItemName</div>";
echo "<div class='test1'>$ItemCost </div>";
echo "<input type='hidden' name='Id' value='".$ID."'/>";
echo "<input type='hidden' name='Money' value='".$Money."'/>";
echo "<input type='hidden' name='ItemCost' value='".$ItemCost."'/>";
echo "<input type='submit' class='btn btn-primary' name='Buy' value='Buy Now'/>";
echo "</form>";
}
}
$conn->close();
Assuming you don't want ajax, and you don't want js, but only a 'buy' button under each item which will reopen the entire page, then you want something like this. This is pseudo code:
//FIRST we need to process the form:
<?php
if(isset($_POST['submit'])){
$itemId = $_POST['id'];
//do the stuff. Remember about escaping $itemId, or using prepared statements
//select... from where id = $itemId
}
?>
//now get the items:
<?php
$GatherItems = ...
?>
//now the html:
<?php
while($row = $result->fetch_assoc()) {
?>
<form method = 'post'>
<div class='test'><?=$ItemName?></div>
...
<input type = 'hidden' name = 'itemId' value = '<?=$ID?>'>
<input type = 'submit' name = 'submit' value = 'Buy'>
</form>
}
?>
Related
I would like to ask if someone could help me with this problem.
I want to prefill the input and textbox from the SQL database. I have tried it many times and I didn't succeded.
This is the code:
<?php
$servername = "localhost";
$username = "********";
$password = "********";
$dbname = "kucharka";
$id = $_POST['id_recept'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT nazev, popis FROM recepty WHERE id = '.$id.'';
$result = mysqli_query($conn, $query);
if ($result) {
while( $row = mysqli_fetch_array($result) ){
echo "<li><label>Název</label></li>";
echo "<input class='blue' type='text' name='nazev' placeholder='Název'>".$row['nazev']."</input>";
echo "<li><label>Fotografie</label></li>";
echo "<div class='foto'>";
echo "<input type='file' id='real-file' name='foto[]' hidden='hidden' multiple='multiple'>";
echo "<button type='button' id='custom-button' class='blue_foto'>Stiskněte</button>";
echo "<span id='custom-text'>Žádná fotografie.</span>";
echo "</div>";
echo "<li><label>Druh</label></li>";
echo "<div class='select_custom'>";
echo "<select name='druh'>";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT id, druh FROM druh';
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_array($result)) {
echo "<option value=".$row['id'].">".$row['druh']."</option>";
}
}
echo "</select>";
echo "</div>";
echo "<li><label>Popis</label></li>";
echo "<textarea name='text' placeholder='Popis'>".$row['popis']."</textarea>";
echo "<li><input type='submit' name='submit' class='orange_input' value='Potvrďte'></li>";
}
}
?>
Thank you in advance.
Ahhh! You have a While Loop INSIDE a While Loop!!
And both are processing mysqli_fetch_array($result) and therefore the inner loop destroys the $result used in the outer loop.
<?php
$servername = "localhost";
$username = "********";
$password = "********";
$dbname = "kucharka";
$id = $_POST['id_recept'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT nazev, popis FROM recepty WHERE id = '.$id.'';
$result = mysqli_query($conn, $query);
if ($result) {
while( $row = mysqli_fetch_array($result) ){
echo "<li><label>Název</label></li>";
echo "<input class='blue' type='text' name='nazev' placeholder='Název'>".$row['nazev']."</input>";
echo "<li><label>Fotografie</label></li>";
echo "<div class='foto'>";
echo "<input type='file' id='real-file' name='foto[]' hidden='hidden' multiple='multiple'>";
echo "<button type='button' id='custom-button' class='blue_foto'>Stiskněte</button>";
echo "<span id='custom-text'>Žádná fotografie.</span>";
echo "</div>";
echo "<li><label>Druh</label></li>";
echo "<div class='select_custom'>";
echo "<select name='druh'>";
// changed code here
// 1 you dont need to connect twice
//$conn = mysqli_connect($servername, $username, $password, $dbname);
$query = 'SELECT id, druh FROM druh';
// use different var here
// and then use it in the related function calls
$result1 = mysqli_query($conn, $query);
if ($result1) {
// and of course use a different var to hold the row data
// so you dont overwrite that also
while ($row1 = mysqli_fetch_array($result1)) {
echo "<option value=".$row1['id'].">".$row1['druh']."</option>";
}
}
echo "</select>";
echo "</div>";
echo "<li><label>Popis</label></li>";
echo "<textarea name='text' placeholder='Popis'>".$row['popis']."</textarea>";
echo "<li><input type='submit' name='submit' class='orange_input' value='Potvrďte'></li>";
}
}
Seperate issue, you dont appear to have a <form> and </form> tag in this code. Without that the data placed in input fields will never be transmitted as a form to the PHP script for processing
BIG NOTE
Your script is open to SQL Injection Attack.
Even if you are escaping inputs, its not safe!
You should consider using prepared parameterized statements in either the MYSQLI_ or PDO API's instead of concatenated values
So to prepare the relevant dangerous query
$query = 'SELECT nazev, popis FROM recepty WHERE id = ?';
$stmt = $conn->prepare($conn, $query);
$stmt->bind_param('i', $_POST['id_recept']);
$stmt->execute();
$result = $stmt->get_result();
. . .
<?php
$DatabaseServer = "localhost";
$DatabaseUsername = "root";
$DatabasePassword = "root";
$DatabaseName = "demo";
$Connection = mysqli_connect($DatabaseServer, $DatabaseUsername, $DatabasePassword, $DatabaseName);
if ($Connection === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlusers = "select * from user";
$result = mysqli_query($Connection, $sqlusers);
echo "<form method='POST'>";
while($rowuser = mysqli_fetch_array($result)){
$user = $rowuser['FirstName'];
echo "<input type='text' name='firstName' value='$user' readonly>";
echo "<select name='attendanceType'>";
$sqltype = "select * from attendancetype";
$resultaType = mysqli_query($Connection, $sqltype);
while($rowtype = mysqli_fetch_array($resultaType)){
echo "<option>";
echo $rowtype['name'];
echo "</option>";
}
echo "</select>";
echo "<br>";
}
echo "<input type='submit' name='submit' value='submit'>";
echo "</form>";
?>
Users table.
INSERT INTO `user` (`UserID`, `FirstName`, `LastName`, `Email`, `Password`, `City`) VALUES
(7, 'Rahul', 'Rajshekaran', 'Rahul#zzz.xxx', 'Rahul#123', 'Pune'),
(8, 'Mahesh', 'Krishna', 'Mahesh#xxx.xxx', 'Mahesh#123', 'Delhi');
attendancetype table:
INSERT INTO `attendancetype` (`attendanceTypeID`, `name`) VALUES
(0001, 'Present'),
(0002, 'Absent');
How can I inserting data into table on a single submission of form?
your code has one mistake. If you are looping form elements, you must achieve, that every input has the unique name.
$i = 0;
while($rowuser = mysqli_fetch_array($result)){
$user = $rowuser['FirstName'];
echo "<input type='text' name='firstName[".$i."]' value='$user' readonly>";
echo "<select name='attendanceType[".$i."]'>";
$sqltype = "select * from attendancetype";
$resultaType = mysqli_query($Connection, $sqltype);
while($rowtype = mysqli_fetch_array($resultaType)){
echo "<option>";
echo $rowtype['name'];
echo "</option>";
}
echo "</select>";
echo "<br>";
$i++;
}
process form with:
<?php
mysqli_set_charset($Connection, "utf8");
foreach($_POST['firstName'] as $i => $user) {
$sql = "insert into table set attendance_type = '".mysqli_real_escape_string($Connection, $_POST['attendanceType'][$i])."' where user='".mysqli_real_escape_string($Connection, $user)."'";
mysqli_query($Connection, $sql);
}
?>
escapeFunction is used as a refferer to the fact, that you should escape somehow (there are more ways) every input and it needs to be replaced or defined
I have a problem on Deleting my records it delete records but it always delete the first record not the corresponding data that I choose.
function deleterec()
{
$server = "127.0.0.1";
$username = "root";
$password = "";
$database = "inventory";
$conn = new PDO("mysql:host=$server;dbname=$database", $username, $password);
$getstarteds = $conn->prepare("SELECT * FROM record");
$getstarteds->execute();
$displayrecs = $getstarteds->fetch();
if (count($displayrecs) > 0) {
$_SESSION['id'] = $displayrecs['id'];
$checkrec = $conn->prepare("INSERT INTO archive SELECT * from record where id = '" . $_SESSION['id'] . "'");
if ($checkrec->execute()) {
$sql = "DELETE FROM record WHERE id='" . $displayrecs['id'] . "'";
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
echo '<script language="javascript">';
echo 'alert("Record is Deleted")';
echo '</script>';
echo "<script>setTimeout(\"location.href='main.php'\",100);</script>";
}
}
}
here is my page.
enter image description here
here is my view code
$getstarteds = $conn->prepare("SELECT * FROM record");
$getstarteds->execute();
$displayrecs = $getstarteds->fetchAll();
echo"<table class='table table responsive' id='example'>";
foreach($displayrecs as $displayrec)
{
echo"<tr>";
echo"<td>".$displayrec['eq_type']."</td>";
echo"<td>".$displayrec['eq_num']."</td>";
echo"<td>".$displayrec['model']."</td>";
echo"<td>".$displayrec['serial_num']."</td>";
echo"<td>".$displayrec['location']."</td>";
echo"<td>".date("F j, Y",strtotime($displayrec['date_added']))."</td>";
echo"<td><form action='main.php' method='POST'><button name='deletethis' class='btn btn-costume1'><i class='fa fa-times' aria-hidden='true'></i></button><a data-toggle='modal' data-target='#myEdit' class='btn btn-costume3'><i class='fa fa-pencil' aria-hidden='true'></i></a></form></td>";
echo"</tr>";
}
Your select $getstarteds = $conn->prepare("SELECT * FROM record"); without WHERE condition and this line $displayrecs = $getstarteds->fetch(); always get the first record
i'm having some trouble passing Form checkbox array as mysql_query in order to delete multiple rows from table.
The structure is as follows:
HTML
<form action="usunogrod.php" method="POST" enctype="multipart/form-data">
<?php
$ogrodysql = "SELECT id_ogrodu, nazwa FROM ogrody";
$result = mysqli_query($con, $ogrodysql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
}
}
else {
echo "0 results";
}
?>
<br><br>
<input type="submit" value="Usuń zaznaczony ogród."/>
</form>
PHP for processing form in usunogrod.php
<?php
$db_host = 'xxxxx';
$db_user = 'xxxxx';
$db_pwd = 'xxxxx';
$con = mysqli_connect($db_host, $db_user, $db_pwd);
$database = 'xxxxx';
if (!mysqli_connect($db_host, $db_user, $db_pwd))
die("Brak połączenia z bazą danych.");
if (!mysqli_select_db($con, $database))
die("Nie można wybrać bazy danych.");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ogrod_id = trim(sql_safe($_POST['removegarden[]']));
if (isset($_POST['removegarden[]'])) {
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu='$ogrod_id'");
$msg = 'Ogród został usunięty.';
}
elseif (isset($_GET['removegarden[]']))
$msg = 'Nie udało się usunąć ogrodu.';
};
?>
MySQL table
ogrody
# id_ogrodu nazwa
1 garden1
How may i process an array from checkboxes form so that i will be able to pass a query to delete all checked elements?
EDIT:
I have been able to make it work to a moment where it only deleted one of the checked positions, or the other time just got an error saying i can't pass and array to mysqli_query.
I think this should help you:
Change this line:
echo "• " . $row["id_ogrodu"]. " " . $row["nazwa"]. "<input type='checkbox' name='removegarden[]' value=" .$row["id_ogrodu"]." <br><br>";
For this one:
echo '• ' . $row["id_ogrodu"]. ' ' . $row["nazwa"]. '<input type="checkbox" name="removegarden['.$row["id_ogrodu"].']" value="'.$row["id_ogrodu"].'" /> <br/><br/>';
Then this one:
if (isset($_POST['removegarden[]'])) {
To
if (isset($_POST['removegarden'])) {
And finally your query:
$gardens = implode(',',$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN($gardens)");
You can get your data in $_POST['removegarden']. no need [] at last.
Then convert this array to ',' seperated string which can be then used in query
if (isset($_POST['removegarden'])) {
$ids_to_delete = implode(",",$_POST['removegarden']);
mysqli_query($con, "DELETE FROM ogrody WHERE id_ogrodu IN ($ids_to_delete)");
$msg = 'Ogród został usunięty.';
}
i should make a "cheque" and there should be (Index,id,....), but index should reset after 100, but id must be auto_incremented.
Here is my code what i did. I didnt get how can i reset index to 0. I cant even show the indexs value, it shows 0 everytime when i add something.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "dbcar";
$number = "";
$state_number = "";
$model = "";
$status = "";
$conditions = "";
$date = "";
$number_index = "1";
$connect = mysqli_connect($host,$user,$password,$database);
echo "<h1>Report Log </h1>";
$sqlget = "SELECT * FROM carserv ORDER BY date DESC LIMIT 1";
$sqldata = mysqli_query($connect,$sqlget) or die("error");
echo "<table>";
echo"<tr>
<th>INDEX</th>
<th>ID</th>
<th>State Number</th>
<th>Model</th>
<th>Status</th>
<th>Condition</th>
<th>Date</th>
</tr>";
while($row = mysqli_fetch_array($sqldata,MYSQLI_ASSOC)){
echo" <tr><td>";
echo $row['number_index'];
echo" </td><td>";
echo $row['number'];
echo" </td><td>";
echo $row['state_number'];
echo" </td><td>";
echo $row['model'];
echo" </td><td>";
echo $row['status'];
echo" </td><td>";
echo $row['conditions'];
echo" </td><td>";
echo $row['date'];
echo" </td></tr>";
}
echo "</table>";
function getPosts(){
$posts = array();
$posts[0] = $_POST['state_number'];
$posts[1] = $_POST['number'];
$posts[2] = $_POST['model'];
$posts[3] = $_POST['status'];
$posts[4] = $_POST['conditions'];
$posts[6] = $_POST['number_index'];
return $posts;
}
?>
and here is my output: http://imgur.com/GOuCcBU
Take look in your phpmyadmin page there is auto_increment option you need to just have two field check auto increment for id field and for index you just fetch it and save it to db in another field with name number_index(because index is a reserved word).
Reset your db to O by doing something like this is your counter_update.php
if($_POST['index_reset']) {
$index_reset = $_POST[index_reset];
mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql = 'UPDATE counters SET number_index =\'0\' WHERE Page = \'$index_reset\';';
}
And html side something like this
$page_reset = "<form id='Reset' action='counter_update.php' method='post'>
<button type='submit' name='index_reset' value='$formPage'>RESET</button>
</form>";