sir ,
I have two textbox in my form.
My data is like...
column1 price
501 1
502 2
503 3
504 1
505 2
506 3
507 1
like wise...
I need to update all value of price column from inputed textbox value.
for Ex Inputted values in textbox like
monthtextbox = 1
pricetextbox = 50 then
update all 1 with 50 in price column.
below is my code but this is not updating any values.plz suggest me an update statement.
<?php
$errors = array();
if(isset($_POST['update']))
{
$month = $_POST['month'];
$price = $_POST['price'];
$modified = date("Y-m-d H:i:s");
$updaterow = $database->updateRow("UPDATE scheme_master SET price = :price WHERE price = :price",
array(':price'=>$price,':price'=>$month,':modified'=>$modified));
$_SESSION['message'] = "Data Updated Successfully";
}
?>
<form name="frm2" method="post" action="">
<div id="page-wrap">
<table height="50">
<tr>
<td width="8%">Enter Month :</td>
<td width="19%"><input type="text" name="month" class="" required = "" /></td>
<td width="11%">Enter Price :</td>
<td width="20%"><input type="text" name="price" class="" required = ""/></td>
<td width="12%" height="45"><input type="submit" name="update" value="Save"/></td>
</tr>
</table>
</div>
</form>
Change price column with month in where condition and also an array.
this will update all values and work for you.
<?php
$errors = array();
if(isset($_POST['update']))
{
$month = $_POST['month'];
$price = $_POST['price'];
$updaterow = $database->updateRow("UPDATE scheme_master SET price = :price WHERE price = :month",
array(':price'=>$price,':month'=>$month));
$_SESSION['message'] = "Data Updated Successfully";
}
?>
Related
Good afternoon,
I am building a journal, in which I have separate divs.
Each div element displays a different log, with data specific to each log in the div.
For each of the logs, I have a submit button that allows the form to be updated and edited.
What is happening, is that when I submit the form, it is updating each entry in my database, rather than just 1 single entry.
I know that the trouble is with my foreach loop, but I am unsure how to remedy this.
Any assistance or pointers would be greatly appreciated.
Code below:
<?php
$sqlGrow = "SELECT * FROM grow_details ";
$query = $conn->query($sqlGrow);
$grows = array();
while ($grow = mysqli_fetch_assoc($query) ) {
$grows[] = $grow;
}
foreach($grows as $grow) {
$id = $grow['id'];
$growName = $grow['name'];
?>
<div class="container">
<div class="details">
<h2><?php echo $grow['name']; ?></h2>
<p class="growNum">Grow #: <?php echo $id; ?></p>
<table class="growDetails">
<form method="POST" action="">
<tr>
<td class="label_growDetails"><label for="datePlanted">Date Planted:</label></td>
<td><input type="text" name="edit_datePlanted" id="edit_datePlanted" value="<?php echo $grow['datePlanted']; ?>" />
</tr>
<tr>
<td class="label_growDetails"><label for="strain">Strain:</label></td>
<td><input type="text" name="edit_strain" id="edit_strain" value="<?php echo $grow['strain']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="toMaturity">Days to mature:</label></td>
<td><input type="text" name="edit_toMaturity" id="edit_toMaturity" value="<?php echo $grow['toMaturity']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="type">Type:</label></td>
<td><input type="text" name="edit_type" id="edit_type" value="<?php echo $grow['type']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="gender">Gender:</label></td>
<td><input type="text" name="edit_gender" id="edit_gender" value="<?php echo $grow['gender']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="medium">Medium:</label></td>
<td><input type="text" name="edit_medium" id="edit_medium" value="<?php echo $grow['medium']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="watts">Watts:</label></td>
<td><input type="text" name="edit_watts" id="edit_watts" value="<?php echo $grow['watts']; ?>" /></td>
</tr>
<tr>
<td class="label_growDetails"><label for="lightType">Light Type:</label></td>
<td><input type="text" name="edit_lightType" id="edit_lightType" value="<?php echo $grow['lightType']; ?>" /></td>
<td class="edit"><input type="submit" name="submit_editGrowDetails" id="submit_editGrowDetails" value=" Save Edits " /></td>
</tr>
</form>
</table>
</div>
And the PHP for the submit button:
<?php
if(isset($_POST['submit_editGrowDetails'])){
$edit_datePlanted = mysqli_real_escape_string($conn, $_POST['edit_datePlanted']);
$edit_strain = mysqli_real_escape_string($conn, $_POST['edit_strain']);
$edit_toMaturity = mysqli_real_escape_string($conn, $_POST['edit_toMaturity']);
$edit_type = mysqli_real_escape_string($conn, $_POST['edit_type']);
$edit_gender = mysqli_real_escape_string($conn, $_POST['edit_gender']);
$edit_medium = mysqli_real_escape_string($conn, $_POST['edit_medium']);
$edit_watts = mysqli_real_escape_string($conn, $_POST['edit_watts']);
$edit_lightType = mysqli_real_escape_string($conn, $_POST['edit_lightType']);
$name = $grow['name'];
$edit_growDetails = "UPDATE grow_details
SET datePlanted = '$edit_datePlanted',
strain = '$edit_strain',
toMaturity = '$edit_toMaturity',
type = '$edit_type',
gender = '$edit_gender',
medium = '$edit_medium',
watts = '$edit_watts',
lightType = '$edit_lightType'
WHERE name = '$name'; ";
$query_edit_growDetails = $conn->query($edit_growDetails);
if($query_edit_growDetails) {
echo '<p class="success" id="success">Successfully updated log for '.$name.'! <a class="refresh" href="journal.php">Refresh</a></p>';
} else {
echo '<p class="error" id="error">There was an error: '. $conn->error .'</p>';
}
}
?>
You should always update by the ID of the table, not the name because some may have the same name.
Let's say you have:
ID | Name
1 | Test 1
2 | Test 2
3 | Test 1
With the update query you have now, if you update "Test 1", it will update both "Test 1" with ID 1 and 3.
To fix this, on you html form, you should put a hidden field under the form like so:
<form method="POST" action="">
<input type="hidden" value="<?php echo $grow['id']; ?>" name="edit_id">
...
...
rest of code
This will echo out the id of the item you are editing.
Then on you php side, you should do this:
<?php
if(isset($_POST['submit_editGrowDetails'])){
$edit_datePlanted = mysqli_real_escape_string($conn, $_POST['edit_datePlanted']);
$edit_strain = mysqli_real_escape_string($conn, $_POST['edit_strain']);
$edit_toMaturity = mysqli_real_escape_string($conn, $_POST['edit_toMaturity']);
$edit_type = mysqli_real_escape_string($conn, $_POST['edit_type']);
$edit_gender = mysqli_real_escape_string($conn, $_POST['edit_gender']);
$edit_medium = mysqli_real_escape_string($conn, $_POST['edit_medium']);
$edit_watts = mysqli_real_escape_string($conn, $_POST['edit_watts']);
$edit_lightType = mysqli_real_escape_string($conn, $_POST['edit_lightType']);
$id = mysqli_real_escape_string($conn, $_POST['edit_id']);
$name = $grow['name'];
$edit_growDetails = "UPDATE grow_details
SET datePlanted = '$edit_datePlanted',
strain = '$edit_strain',
toMaturity = '$edit_toMaturity',
type = '$edit_type',
gender = '$edit_gender',
medium = '$edit_medium',
watts = '$edit_watts',
lightType = '$edit_lightType'
WHERE id = '$id'; ";
$query_edit_growDetails = $conn->query($edit_growDetails);
if($query_edit_growDetails) {
echo '<p class="success" id="success">Successfully updated log for '.$name.'! <a class="refresh" href="journal.php">Refresh</a></p>';
} else {
echo '<p class="error" id="error">There was an error: '. $conn->error .'</p>';
}
}
?>
I think your problem is with the following line in your submit handler:
$name = $grow['name'];
Where this $grow is referenced from i cannot see, but you should add the name in as a hidden input in your form. That way the handler knows which tuple to update. For example:
<input type="hidden" value="<?php echo $grow['name']; ?>" name="grow_name">
You can then access it via like any other piece of data from the form, i.e.
$name = mysqli_real_escape_string($conn, $_POST['grow_name']);
Some more advice:
Instead of using raw queries, you should use prepared statements with parameters, they are much safer.
Instead of updating by name, update by id. Even if the name is also unique. An id will generally have a primary key index making the query a lot faster.
The fact that the code actually updated all the entries in the database indicates to me that your handler is actually inside the for loop, that is definitely not what you want, move it out of the. With this update it will work, but if you don't move it out of the loop, it will launch a query for each tuple.
Finally #Carlos, #Riggsfolly, i'm not trying to copy your answers. Just thought i could structure the answer better.
I create if statement inside while loop .
And I have three rows of data in table like below
row 1 : **timeout 0830 , timein 1030**
row 2 : **timeout 1230 , timein 1300**
row 3 : **timeout 1400 , timein 1730**
The problem is , the output show like this
Time added ! Duplicate Time added
And the data still added in the 1st and 3rd row. I don't know why.
What I want is to display errors if any one of the rows is duplicate without adding the data.
Let say I input data for the 2nd row which is 1230 and 1300. I want the output to appear as:
Duplicate
And 1st and 2nd row will not adding any data since one the rows is duplicate.
Any solution ?
<?php
$connect = mysqli_connect("localhost", "root", "", "movementandroid");
global $connect;
if(isset($_POST['Submit'])){
$user_id = $_POST['user_id'];
$timeout = $_POST['timeout'];
$timein = $_POST['timein'];
$sql = "SELECT * FROM table WHERE user_id='$user_id'";
$get = mysqli_query($connect, $sql);
if($get && mysqli_num_rows($get) > 0 ){
while($run2 = mysqli_fetch_assoc($get)){
$timeout_new = $run2['timeout'];
$timein_new = $run2['timein'];
if(($timeout >= $timeout_new) && ($timein <= $timein_new)){
echo "Duplicate !";
}
else{
$add = "INSERT INTO table (timeout, timein)
VALUES ('$timeout', '$timein')";
$addDateTime = mysqli_query($connect,$add);
echo "Time added !";
}
}
mysqli_free_result($get);
}
}
?>
<form action="dd.php" method="post">
<table>
<tr>
<td><i class="fa fa-unlock-alt"></i> </td>
<td>User ID : </td>
<td><input type ="text" name="user_id" size="30"></td>
</tr>
<tr>
<td><i class="fa fa-unlock-alt"></i> </td>
<td>Time out : </td>
<td><input type ="text" name="timeout" size="30"></td>
</tr>
<tr>
<td><i class="fa fa-unlock-alt"></i> </td>
<td>Time in : </td>
<td><input type ="text" name="timein" size="30"></td>
</tr>
</table>
<p><input class="btnSuccess" type ="submit" name="Submit" value="Submit"> </p>
</form>
Try to do the timeout timein comparison in a database level and not php.
Change your code to something like this to see if it works:
<?php
$connect = mysqli_connect("localhost", "root", "", "movementandroid");
global $connect;
if (isset($_POST['Submit'])) {
$user_id = $_POST['user_id'];
$timeout = $_POST['timeout'];
$timein = $_POST['timein'];
$sql = "SELECT * FROM table WHERE user_id='{$user_id}' AND timeout >= {$timeout} AND timein <= {$timein}";
$get = mysqli_query($connect, $sql);
if($get && mysqli_num_rows($get) > 0 ){
echo "Duplicate !";
} else {
$add = "INSERT INTO table (timeout, timein)
VALUES ('{$timeout}', '{$timein}')";
$addDateTime = mysqli_query($connect, $add);
echo "Time added !";
}
mysqli_free_result($get);
}
?>
I'm trying to create a form which allows you to update a database table using php.
I'm kinda new to PHP so excuse me if I make a stupid mistake in the code.
This is my edit.php code:
<html>
<head>
</head>
<body>
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM cats");
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<?php
while($row = mysqli_fetch_array($result))
{
$name = $row['name'];
$email = $row['email'];
$rank = $row['rank'];
$birth = $row['birth'];
$joined = $row['joined'];
$steamid = $row['steamid'];
?>
<td width="100"></td>
<td><?=$name?></td>
</tr>
<tr>
<td width="100">Email</td>
<td><input name="emailid" type="text" value="<?=$email?>"></td>
</tr>
<tr>
<td width="100">Rank</td>
<td><input name="rankid" type="text" value="<?=$rank?>"></td>
</tr>
<tr>
<td width="100">Birth</td>
<td><input name="birthid" type="text" value="<?=$birth?>"></td>
</tr>
<tr>
<td width="100">Joined</td>
<td><input name="joinedid" type="text" value="<?=$joined?>"></td>
</tr>
<tr>
<td width="100">Steamid</td>
<td><input name="steamidid" type="text" value="<?=$steamid?>"></td>
</tr>
<?php } ?>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
if(isset($_POST['update']))
{
$name = $row['nameid'];
$email = $row['emailid'];
$rank = $row['rankid'];
$birth = $row['birthid'];
$joined = $row['joinedid'];
$steamid = $row['steamidid'];
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
$retval = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
echo "Updated data successfully\n";
}
mysqli_close($con);
?>
</body>
</html>
It shows the table and information but the updating isn't working.
Updated data successfully
I've checked the database but it's not updating anything.
Dear i think you change the record based on Name because you can use $name in where clause and you can also change the Name than never true where clause so that your query execute successfully but not effected on any of the row.
you want to get for editable record and that's unique id base update row it will defiantly work.
Try to use PHP PDO database access functions, your code as it stands is vulnerable to SQL-Injection! PDO will also make debugging and working with the database much easier.
I think your check for "update" in $_POST is not working because update is not a field inside your form but the submit button itself, try to check for one of the fields instead.
Informations:
With mysqli_error() you need to write about which connection you want to get errors, like this:
mysqli_error($con);
With mysqli_query() you need to give two parameters, connection and query like this:
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
How to debug:
If you want to check that UPDATE query return any error you can do something like this:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
You can try to debug your query with something like this:
$sql = "UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';";
echo $sql; // this output write in your phpMyadmin to check if there are any errors.
$update = mysqli_query($con, $sql);
Other problem we got:
1. I think also you should have else in your code, f.ex.:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
} else {
echo "Updated data successfully\n";
}
2. You are not getting data from $_POST it should be like:
$name = $_POST['nameid']; // not $row['nameid']
$email = $_POST['emailid'];
$rank = $_POST['rankid'];
$birth = $_POST['birthid'];
$joined = $_POST['joinedid'];
$steamid = $_POST['steamidid'];
More about used functions:
PHP: mysqli::$error
PHP: mysqli::query
In your case it is Procedural style
When I enter a video ID and the length of loan and then hit button FindDetails my form will show the name of the video, it's price to hire and the total cost of hire.
This causes two problems:
Submitting the form wipes video ID and the length of loan. Rats!
I cant adjust how many days I want to borrow a video and watch
the cost of the loan automatically adjust.
NB I include all php script as I will actually need to submit the form to write details of the reservation in a csv file. I'm not sure if this will stop a work around solution.
PHP:
<?php
if (isset($_POST['FindDetails'])) {
$ID = $_POST['videoID'];
$Days = $_POST['days'];
//Open the CSV file
$file_handle = fopen("video.csv", "r");
//loop until hit the last line feof)
while (!feof($file_handle))
{
//put data in each line [0],[1] etc into a variable.
$info = fgetcsv($file_handle);
// Check its the one we want.
if($info[0]==$_POST["videoID"])
{
$videoName = "$info[2]";
$videoCost ="$info[4]";
$costOfHire= $videoCost*$Days;
}
}
fclose($file_handle);
}
if (isset($_POST['submit'])) {
$ID = $_POST['videoID'];
$VideoName = $_POST['videoName'];
$VideoCost = $_POST['videoCost'];
$Days = $_POST['days'];
$Total = $_POST['total'];
$DateFrom = $_POST['date_from'];
$DateTo = $_POST['date_to'];
$StudentName = $_POST['studentName'];
//Saving loan details
$csv_file = 'loans.csv';
if (is_writable($csv_file)) {
if (!$csv_handle = fopen($csv_file,'a')) {
// this line is for troubleshooting
echo "<p>Cannot open file $csv_file</p>";
exit;
}
$csv_item = "\"$ID\",\"$VideoName\",\"$VideoCost\",\"$Days\",\"$Total\",\"$DateFrom\",\"$DateTo\",\"$StudentName\"\n";
if (is_writable($csv_file)) {
if (fwrite($csv_handle, $csv_item) === FALSE) {
//for testing
//echo "Cannot write to file";
exit; }
}
fclose($csv_handle);
}
}
if (isset($_POST['submit'])) {
echo "<p style='padding: .5em; border: 2px solid red;'>Thanks for booking the Video. Please collect from E24 on the date ordered.</p>";
}
?>
HTML:
Loans
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Enter the Video ID below
<table id="tables" class="form" style="width:100%;">
<tr>
<td>Video ID</td>
<td><input type="text" value="" name="videoID" id="videoID" placeholder= "Enter A Number between 1 and 8"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="FindDetails" id="FindDetails" value="Search Video" /></td>
</tr>
<tr>
<td>Video Name</td>
<td><input type="text" value="<?php echo (isset($videoName))?$videoName:'';?>" name="videoName" id="videoName"/></td>
</tr>
<tr>
<td>Video Rental Cost (per day)</td>
<td><input type="text" value="<?php echo (isset($videoCost))?$videoCost:'';?>" name="videoCost" id="videoCost"/></td>
</tr>
<tr><td></td><td></td></tr>
<tr>
<td>Number of days</td>
<td><input type="text" value="" name="days" id="days" placeholder= "Enter the number of days you wish to borrow the video for" /></td>
</tr>
<tr>
<td>Total cost</td>
<td><input type="text" value="<?php echo (isset($costOfHire))?$costOfHire:'';?>" name="total" id="total"/></td>
</tr>
Part 1
I assume the HTML and PHP portions presented are in the same file.
You use <?php echo (isset($costOfHire))?$costOfHire:'';?> for example to access variables set in the PHP code.
Why not use <?php echo (isset($ID))?$ID:'';?> to simply recycle the submitted video ID? Then do the same for the length of loan variable.
Part 2
Here is one way live loan cost calculation could work. The javascript will go between <script></script> tags in the <head> of the document.
function updateLoanCost(loanPeriod) {
var costDisplayEl = document.getElementById("loanCostDisplay");
var dollarsPerDay = 3;
costDisplayEl.innerText = "$" + loanPeriod * dollarsPerDay;
}
Enter a number of days <br />
<input type = "number" id = "test" onchange = "updateLoanCost(this.value);"/>
<div id = "loanCostDisplay"></div>
I'm trying to insert data to database.
There is no error, but the database is still not being updated.
In the database, the product table contains:
productid, categoryid, productname, productimage, stock, price
and the detailsales table contains:
transactionid, productid, and quantity
The update one is working, but the insert one is not working at all.
Here is my code:
<form action="doShop.php" method="post">
<table border="1">
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Product Image</td>
<td>Price</td>
<td>Product Stock</td>
<td> Quantity</td>
</tr>
<?php
$query = mysql_query("SELECT * FROM Product");
while($row = mysql_fetch_array($query)){
?>
<tr>
<td><input type="text" value="<?=$row['ProductID']?>" name="productid"></td>
<td><?=$row['ProductName']?></td>
<td><img src="image/<?=$row['ProductImage']?>"></td>
<td><?=$row['Price']?></td>
<td><input type="text" value="<?=$row['Stock']?>" name="stock"></td>
<td><input type="text" name="quantity"></td>
</tr>
<?php
}
print mysql_error();
?>
</table>
<table>
<tr><input type="submit" value="Submit"></tr>
</table>
</form>
Here is the doShop code:
<?php
include("connect.php");
$id=$_REQUEST['productid'];
$quantity=$_REQUEST['quantity'];
$stock = $_REQUEST['stock'];
mysql_query("insert into DetailSales(ProductID, Quantity)values('".$id."','".$quantity."')");
mysql_query("update product set stock = $stock - $quantity where detailsales.productid = product.productid");
header("location:shopcart.php");
?>
Can anyone help me?
You were trying to carry out calculations inside your query, instead I created a separate variable called $total to handle that for, you.
Like this:
$total = $stock - $quantity;
Instead of this:
SET stock = $stock - $quantity
So, change the doshop code to this:
<?php
include("connect.php");
$id = $_REQUEST['productid'];
$quantity = $_REQUEST['quantity'];
$stock = $_REQUEST['stock'];
$total = $stock - $quantity;
mysql_query("INSERT INTO DetailSales(ProductID, Quantity)
VALUES ('".$id."','".$quantity."')") or die(mysql_error());
mysql_query("UPDATE product SET stock = '$total'
WHERE detailsales.productid = product.productid")
or die(mysql_error());
header("Location: shopcart.php");
mysql_query("update product set stock = $stock - $quantity where detailsales.productid = product.productid");
I believe this line is wrong and should be
mysql_query("update product set stock = ".($stock - $quantity)." where detailsales.productid = product.productid");
Try this way instead;
$sql = ("insert into DetailSales(ProductID, Quantity)values('".$id."','".$quantity."')");
$res = mysql_query($sql);
if($res) {
mysql_insert_id();
} else {
die(mysql_error());
}