update database by text box based on the checked box's - php

**Hi
i have been working on this php code .
I want to update the quantity that belongs to the checked box .
but the exact problem with my code is :if I have for example 3 checkboxs and when I enter the quantity for them all in the same time the updates are done correctly and if I only update the first quantity with out the other 2 the update is done correctly also ,But when I update the second or the third alone not in the same time it takes the quantity of the old value of the first :""(
so how can I change my code so I can update all the items or only the checked items.
here is my code to display the checkbox's with the quantity.
in the file manage_items.php :**
<?php
$DB_HOST ='localhost';
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='dks';
$con= mysql_connect($DB_HOST ,$DB_USER , $DB_PASSWORD);
if(!$con){
die('Failed to connect to server :'.mysql_error());
}
$db=mysql_select_db($DB_DATABASE);
if(!$db){
die("unable to select database");
}?>
$qry="SELECT * FROM catalog";
$result= mysql_query($qry);
if($result){
while($info = mysql_fetch_array($result))
{
print "<h3> cat:".$info['name']."</h3><div>";
$qryitem="SELECT * FROM item WHERE Id=". $info['Cid'];
$resultitem=mysql_query($qryitem);
if($resultitem){
?>
<form method="post" action="manage_item_action.php">
<?php
while($info=mysql_fetch_array($resultitem))
{
?>
<input type="checkbox" name="op[]" value="<?php echo $info['Id'];?>"/><?php echo $info['name'];?>
<label> Quantity <input type="text" name="Quantity[]" value="<?php echo $info['Quantity'];?>"/></label>
<br/>
<?php
}
}
else echo "There are no items.";
print "</div>";
}
}
?>
</div>
<input type="submit" value="update" name="submit"/>
</form>
and here is the excution of update
in the file manage_item_action.php
<?php
$DB_HOST ='localhost';
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='dks';
$con= mysql_connect($DB_HOST ,$DB_USER , $DB_PASSWORD);
if(!$con){
die('Failed to connect to server :'.mysql_error());
}
$db=mysql_select_db($DB_DATABASE);
if(!$db){
die("unable to select database");
}
$options=$_POST['op'];
$qun=$_POST['Quantity'];
$size =count($options);
for($i =0; $i<$size; $i++)
{
//$qryop="UPDATE item SET Quantity =".$qun."WHERE Id =".$options[$i]."';";
$resultop=mysql_query("update item set Quantity='".$qun[i]."'where Id='".$options[$i]."'");
}
if($resultop){
header("location: manage_items.php");}
else echo "there was an error"
?>
i dunno how to fix the problem !
but i think my main problem is that all the textbox's have the same name .
so when i send it to the other file for ecution it just take it as it is the last one .
help me please :$
*UPDATED*
*The Solution*
so I solved the problem of my code and its only needed the textbox to be disabled before checkin the checkbox so the array doesn't have any null index..only have the entered values without any nulls
:))

You need to give the 'Quantity' input field a unique name or cast it as an array for every checkbox listed, else when submitted the receiving form will take the last value for 'Quantity' as gospel.

That's because in your input form box, you have:
Quantity <input type="text" name="Quantity" ...
So, with each of the quantity inserted, the forwarded values are being updated. And the last value inserted into Quantity box will be taken in update. Instead, change this form input to this:
<!-- This will forward an array to php script -->
Quantity <input type="text" name="Quantity[]"...
and then, in your updation query, change to:
$resultop=mysql_query("UPDATE item SET Quantity='" . $qun[$i] . "'where Id='".$options[$i]."'");

Related

Populating HTML Dropdown List using PHP/MYSQL

I was practicing using HTML/PHP/MySQL, and was working on a small project.
I wanted to create a page that would allow the user to add records to a MySQL table. The user would enter the values via an HTML form. This data would then be posted to a php script to perform the actual INSERT INTO.
The database is for a shop, and has 2 tables, product and manufacturer. When adding a product, I must also add a code for the manufacturer. I want to populate a dropdown list, showing the names of manufacturers (taken from the manufacturers table).
I am attempting to embed this PHP code into an HTML file. Here is the code:
<form action="" method="post">
<fieldset>
<legend>Enter Product Details:</legend>
Product Name:<input type="text" name="productName"><br>
Product Price:<input type="text" name="Price"><br>
<?php
$host="localhost";
$user="root";
$pass="";
$db="computer_shop";
$conn=mysqli_connect($host,$user,$pass,$db) or die ("Couldn't connect");
$sql="SELECT * FROM manufacturer";
$result=mysqli_query($conn,$sql) or die ("Could not execute query!");
if(!$result){
echo"Error with results";
}
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$code=$row["Code"];
$name=$row["Name"];
echo"<select name='select'>";
echo"<option value=" .$code.">".$name."</option>" ;
<echo"</select>";
}
echo "<br>";
} else {
echo "0 results";
}
mysqli_close($conn);
?>
<input type="submit" value="Submit">
</fieldset>
</form>
When I attempt this, it doesn't go well. When I load the page, the initial part of the form (with input boxes for name and price are fine), but the drop down list is a mess, and I see the code: "0) { while($row = mysqli_fetch_assoc($result)) { $code=$row["Code"]; $name=$row["Name"]; echo" along with a drop down list showing only $name, and then the submit button. So the HTML file is displaying part of the actual PHP code.
My question is, how do I fix this so that the drop down list will display the values from the mysql database? I have been looking through various sites, trying different things, but I keep getting a similar problem. Should I flip things, and embed the HTML inside a PHP file instead?
In general this code is not a good practice. Make sure that this code is in a .php file and your web server supports php.
Other than that, I think that the following script will solve your problem.
if (mysqli_num_rows($result) > 0) {
//open the select tag before the loop
echo"<select name='select'>";
//populate the select
while($row = mysqli_fetch_assoc($result)) {
$code=$row["Code"];
$name=$row["Name"];
echo"<option value=" .$code.">".$name."</option>" ;
}
//close the select tag after the loop
echo"</select>";
echo "<br>";
} else {
echo "0 results";
}

Insert an array and show value in PhpMyAdmin

I am using checkboxes to see if a user wants "Breakfast,Dinner and Supper"
This is my code for that
<div id="checkboxesFood">
<p>Please select if you want breakfast, dinner and supper</p>
<input type="checkbox" class="food" name="foodboxes[]" value="Breakfast"/>Breakfast
<input type="checkbox" class="food" style="margin:0 0 0 19%;" name="foodboxes[]" value="Dinner"/>Dinner
<input type="checkbox" class="food" style="margin:0 0 0 19%;" name="foodboxes[]" value="Supper"/>Supper
</div>
I'm using PHP to connect to a DB and store the value there.
This is my PHP code
$username = $_POST['userName']; //Username
$view = $_POST['roomChoice']; //View Of Room
$paymentMethod = $_POST['payment']; //How user want's to pay
$selectedFood = $_POST['foodboxes']; //Food they have selected(Breakfast, Dinner or Supper)
//$foodData = array($selectedFood);
$con = new mysqli('localhost','username','mypw','DB');
if($con->connect_error){
die("Connection failed: " .$con->connect_error);
}
//$implodedData = implode(",",$foodData);
$sql = "INSERT INTO Hotellbokning(Name,Room,Food,Payment) VALUES('$username','$view','$implodedData','$paymentMethod')";
if($con->query($sql) == true){
echo "You did it John!";
}
else{
echo "Error: " . $sql . "<br/>" .$con->error;
}
Just ignore the variables that is not an issue. When I insert this array $selectedFood into my DB, I recieve the value "Array" on my Food-field.
Is there a way to see the value of this array(the three values Breakfast,Dinner and Supper) in PhpMyAdmin, or is it only possible to echo them out from my DB?
P.S. I tried using implode but it didn't work. I've also tried $foodData = array($selectedFood) But it didn't work either.
You're imploding the wrong thing. $selectedFood is already an array, you don't need to wrap it in another array. So it should be:
$implodedData = implode(',', $selectedFood);
Then you can store $implodedData in the database.
However, putting comma-separated lists in a database is generally poor design. You should use a relation table with a separate row for each item.

Unable to update a record after choosing an option from a drop down menu

Assignment background :
I have a drop down menu which I am populating from a database. Based on the option user choses from the drop down , I need to update the chosen record. Now some information on the databases and the record types : There are 5 types of complaints : Electrical, Mechanical , Telephone , Fire System and Priority. Each of these complaints can have a status of either "open" or "close". So when the user chooses "Electrical type" , all the "open" complaint-id's (complaint id is a field in the same record) of electrical types will appear. Once the admin chooses the id, the corresponding record is to be updated to change the status to "close".
Now my problem :
I am able to display all the complaint ids , but upon choosing the concerned id and hitting the submit button , the status of the record does not change to "close".
The code
$user="root";
$password="";
$database="complaint_data";
$localhost="localhost";
mysql_connect($localhost,$user,$password);
#mysql_select_db($database) or die("Unable to open database");
echo ('<form action="" method="post"><br>');
echo ('<center><select name = "complaint"></center>');
echo ('<option value ="Electrical"> Electrical </option>');
echo ('<option value ="Mechanical"> Mechanical </option>');
echo ('<option value ="Telephone"> Telephone </option>');
echo ('<option value ="Fire"> Fire </option>');
echo ('<option value ="Priority"> Priority </option>');
echo ('<center><input type="submit" name="Submit" ></center>');
echo ('</form>');
if(($_SERVER["REQUEST_METHOD"]=="POST") and (!empty($_POST['Submit']) ) ){
$t=$_POST['complaint'];
switch ($t) {
case "Electrical":
$q="SELECT `complaintid` , `comment` FROM `complaints` WHERE `status`='open' and `type`='Electrical' ORDER BY `id` DESC";
$sql=mysql_query($q);
$count=mysql_num_rows($sql);
if($count!=0) {
echo ('<form action="" method="post"><br>');
echo ('<center><select name = "complaint1"></center>');
while($row=mysql_fetch_array($sql)) {
$cmp=$row['complaintid'];
echo "<option value =\"$cmp\"> $cmp </option> <br>";
}
echo ('</select>');
echo ('<center><input type="submit" name="Submit1" ></center>');
echo ('</form>');
if(($_SERVER["REQUEST_METHOD"]=="POST") and (!empty($_POST['Submit1'])) ) {
$cmpi=$_POST['complaint1'];
echo $cmpi;
$query="UPDATE complaints SET status='close' WHERE complaintid=`$cmpi` ";
mysql_query($query);
}
}
if($count=='0') {
echo "No record of electrical type found";
}
mysql_close();
break;
By the way I have included only the snippet for Electrical type, once it works I shall copy it to other types too ! TIA :)
Try this:
$query="UPDATE complaints SET status='close' WHERE complaintid=$cmpi";
removed ` surrounding $cmpi.

PHP can't update SQL

I'm using a php part in my site, where I have a textarea that get a text from a database. The user can edit this text and after he finish press the save button, and using UPDATE I will change the text in the database.
Here is my code:
<?php
$con=mysqli_connect("localhost","userdb","codedb","projectdb");
mysqli_set_charset($con, 'utf8');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$myQueryfac="SELECT text FROM main WHERE id=1";
$result = mysqli_query($con,$myQueryfac);
while($row = mysqli_fetch_array($result)) {
$t1=$row['text'];
}
$form="<form action='adminindex.php' method='post'>
<textarea name='area1' maxlength='1500' cols='50' rows='10'>$t1</textarea>
<input type='submit' name='enter' value='Save'>
</form>";
if($_POST['enter']) {
$t1=$_POST['area1'];
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
}
echo $form;
mysqli_close($con);
?>
My problem is in the UPDATE query it seems like it ignores $t1 and nothing change in database. But if I put something random in there, "RANDOM TEXT", change it successful.
This is how you do it:
test.php
// DB Connect
$con=mysqli_connect("localhost","userdb","codedb","projectdb");
mysqli_set_charset($con, 'utf8');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Handle POST
if (count($_POST))
{
// Save In DB
mysqli_query($con, sprintf("UPDATE main SET `text`='%s' WHERE id=%d",
mysqli_real_escape_string($con, $_POST['area1']),
1)); // id
// Success
echo "<p>Data updated.</p>";
}
// Load Existing Data
$myQueryfac="SELECT `text` FROM main WHERE id=1";
$result = mysqli_query($con, $myQueryfac);
$row = mysqli_fetch_array($result);
// Display Form
echo "<form action='test.php' method='post'>
<textarea name='area1' maxlength='1500' cols='50' rows='10'>". $row['text'] ."</textarea>
<input type='submit' name='enter' value='Save'>
</form>";
// DB Close
mysqli_close($con);
?>
What I've changed
Moved the post hander up (above the select statement), so that if an update occurs, the form will show the latest updated data
Your update query was treating the id as string, I formatted it to be a digit (%d)
Removed the while loop, you don't need it as it is a single row being returned
added sql-injection prevention (using sprintf and mysqli_real_escape_string)
added backticks `` around the db field name text (wasn't sure if this is a reserved word, because it's one of the sql data types)
Try to do
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id=1");
Instead
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
It could be the WHERE condition that bring your problems
You are checking the $_POST array for a value not existing. enter is your submit button and will not send a value.
Try this:
if($_POST['area1']) {
$t1=$_POST['area1'];
mysqli_query($con,"UPDATE main SET text='$t1' WHERE id='1'");
}

having trouble getting selected value from php dynamic selection option

I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>

Categories