I am having the hardest time figuring out something that I think should be simple. I need to update multiple rows in my database with one submit button. I have it working with a submit for each row now, but I need to combine it. Here's what I'm trying. Where have I gone wrong? (I've been going off of multiple tutorials I found online and I think I have things all mixed up).
Here's the form:
<?php foreach ($teams as $team):
$id[]=$team['id'];?>
<form action="?update" method="post">
<div class="team-box">
<h2><?php echo $team['name'] ?></h2>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo $team['name'] ?>" />
<label for="name">Match Wins:</label>
<input type="text" name="mwins" value="<?php echo $team['mwins'] ?>" />
<label for="name">Match Losses:</label>
<input type="text" name="mlosses" value="<?php echo $team['mlosses'] ?>" />
<label for="name">Match Ties:</label>
<input type="text" name="mties" value="<?php echo $team['mties'] ?>" />
<label for="name">Game Wins:</label>
<input type="text" name="gwins" value="<?php echo $team['gwins'] ?>" />
<label for="name">Game Losses:</label>
<input type="text" name="glosses" value="<?php echo $team['glosses'] ?>" />
<input type="hidden" name="id" value="<?php echo $team['id'] ?>" />
</div>
Here's the PHP to handle the UPDATE:
try
{
foreach($_POST['id'] as $id) {
$sql = 'UPDATE teams SET
name = "' . $_POST['name'.$id] . '",
mwins = "' . $_POST['mwins'.$id] . '",
mlosses = "' . $_POST['mlosses'.$id] . '",
mties = "' . $_POST['mties'.$id] . '",
gwins = "' . $_POST['gwins'.$id] . '",
glosses = "' . $_POST['glosses'.$id] . '"
WHERE id = "' . $_POST['id'.$id] . '"';
$pdo->exec($sql);
}
}
catch (PDOException $e)
{
$error = 'Error adding submitted team: ' . $e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
Thanks in advance!
There are a couple of things that need fixing.
The FORM must be outside the foreach.
The '...name="name" value="...', to agree with the _POST code, should read instead:
... name="name" value="...
This way, a single POST will submit, say,
name123="Rangers"
mwins174="123"
Then you need all IDs. You can do that by issuing, in the foreach, this:
<input type="hidden" name="id[]" value="<?php print $team['id']; ?>" />
This will result in HTML:
<input type="hidden" name="id[]" value="123" />
...
<input type="hidden" name="id[]" value="456" />
and in $_POST['id'] being an array containing 123, 456 and so on.
You could also put in HTML:
<input type="text" name="name[<?php print $team['id']; ?>]" value="...
so that $_POST['name'] would be a vector with the same keys as the values of id, and therefore:
foreach($id as $team_id)
{
// Pseudocode
UPDATE... SET name=$name[$team_id]... WHERE id = $team_id;
}
This way you have one SUBMIT, and multiple UPDATEs.
Since all your field names change for each UPDATE query, you will need to execute separate queries as you already do. I don't think you would be able to perform a single UPDATE query.
I don't understand, what's wrong with executing several update queries?
Related
My database manages to retrieve values when I navigate from the previous page.
When I click the 'Update Product' button, the line Update product appears. What I want is when I click the 'Update Product' button, and have modified a record beforehand, I would hope to update the database with the values as well and a confirmation message is displayed to confirm this.
Code:
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductCostPrice">ID</label>
<input id="updateFormProductCostPrice" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text"
value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductDescription">Producer</label>
<input id="Producer" name="productDescription" type="text"
value="<?php echo $productDetails["Producer"]; ?>">
</div>
<div>
<label for="updateFormProductPrice">Year Published</label>
<input id="updateFormProductPrice" name="YearPublished" type="text"
value="<?php echo $productDetails["YearPublished"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductEan">Price:(£)</label>
<input id="updateFormProductEan" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
PHP:
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) {
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductManagement "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p>Updated</p>";
}
}
}
}
So I need the database to update what new value I have entered and it once the 'Update product' Button is pressed, the original value appears and the value is not updated on the database. Why is this? I don't get any error messages. Thanks
The error is that you dont POST the ID but you GET the ID value. input boxes with the readonly attribute don't post values.
change:
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
to:
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
Edit: Total changes to make to make this work:
HTML:
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductID">ID</label>
<input id="updateFormProductID" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text"
value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductProducer">Producer</label>
<input id="updateFormProductProducer" name="Producer" type="text"
value="<?php echo $productDetails["Producer"]; ?>">
</div>
<div>
<label for="updateFormProductYearPublished">Year Published</label>
<input id="updateFormProductYearPublished" name="YearPublished" type="text"
value="<?php echo $productDetails["YearPublished"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductPrice">Price:(£)</label>
<input id="updateFormProductPrice" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
PHP:
if (((!empty($_GET["mode"])) && (!empty($_GET["ID"]))) && ($_GET["mode"] == "update")) {
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) {
if ((!empty($_GET["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearPublished"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
$query = "UPDATE ProductManagement "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearPublished = '" . $_POST["YearPublished"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE ID=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) {
echo "<p>Updating failed.</p>";
} else{
echo "<p>Updated</p>";
}
}
}
}
Try setting the name and id of your input fields to the same respective values. I see you call id from one and name from another input field in your php and it might be causing the function to fail.
Like so for example:
<label for="ID">ID</label>
<input id="ID" name="ID" type="text" readonly value="<?php echo $productDetails["ID"]; ?>">
you should be fine using $_POST[], since the method of your form is POST. (If you change it to GET it will put all the values in the url)
I start with the following:
<form action="" method="post" enctype="multipart/form-data" id="form">
<?php foreach($attributes as $attribute){ ?>
<input type="checkbox" name="attribute[][attr_id]" value="<?php echo $attribute['attribute_id']; ?>">
<input type="text" name="attribute[][attr_name]"> value="<?php echo $attribute['attribute_name']; ?>">
<?php } ?>
</form>
So each $attribute has a checkbox and a text input; whenever someone would check (one or more boxes) and would insert text (only to the checked items) I want to get in the DB the [attr_id] and the [attr_name] for the specific item.
So I continue with the following:
if(isset($_POST['attribute'])){
foreach($_POST['attribute'] as $attribute){
$attr_id = $attribute['attr_id'];
$attr_name = $attribute['attr_name'];
"INSERT INTO " . DB_PREFIX . "attribute_xref SET productid = '" . $productid . "', attribute_id='". $attr_id ."', attribute_name='" . $attr_name . "'";
}
}
But, the result is a little different as of I would have expected. Every time a box is checked and its text input is typed, their values are sent to two different DB rows:
productid -- attribute_id -- attribute_name
10 -- 102 -- empty
10 -- 0 -- somename
On the above second row the attribute_id has zero value for not being checked.
I cannot get the whole picture where is my mistake.
Finally. The tricky answer was to add an identical numerical index to the associative inputs like this:
<form action="" method="post" enctype="multipart/form-data" id="form">
<?php foreach($attributes as $attribute){ ?>
<input type="checkbox" name="attribute[i][attr_id]" value="<?php echo $attribute['attribute_id']; ?>">
<input type="text" name="attribute[i][attr_name]"> value="<?php echo $attribute['attribute_name']; ?>">
<?php } ?>
</form>
where "i" in my case would take the variable number from 'attribute_id':
<input type="checkbox" name="attribute[<?php echo $attribute['attribute_id']; ?>][attr_id]" value="<?php echo $attribute['attribute_id']; ?>">
<input type="text" name="attribute[<?php echo $attribute['attribute_id']; ?>][attr_name]"> value="<?php echo $attribute['attribute_name']; ?>">
Hopefully my answer would help somebody in the future, too.
I try to send couple values from html form into database but variables are empty.
If I print variables in php area like echo $ad1_uid; I get the value.
After sending - all values are empty:
author_uid=&state=complete&mail=&user_uid=
Where could be a reason?
<form action="" method="get">
<input type="hidden" value="<?php ''.$ad1_uid; ?>" name="author_uid">
<input type="hidden" value="complete" name="state">
<input type="hidden" value="<?php ''.$user->mail; ?>" name="mail">
<button name="user_uid" type="submit" value="<?php ''.$user->uid; ?>">Zapisuje się</button>
</form>
<?php
}
$wyslany_user_uid = $_GET['user_uid'];
$wyslany_author_uid = $_GET['author_uid'];
$wyslany_mail = $_GET['mail'];
$wyslany_state = $_GET['state'];
var_dump($wyslany_mail);
mysql_query("INSERT INTO `krajeto_demo`.`registration1`
(user_uid, author_uid, mail, state ) VALUES (
'" . $wyslany_user_uid . "', '" . $wyslany_author_uid. "', '" . $wyslany_mail . "','" . $wyslany_state . "'
");
?>
To output the value of $ad1_uid in the form, try this instead:
<input type="hidden" value="<?= $ad1_uid; ?>" name="author_uid">
Or this if your setting don't
<input type="hidden" value="<?php echo $ad1_uid; ?>" name="author_uid">
Your PHP is not set to echo data into the form.
I've fixed those and added a debug clause to run. Just set to false once you've ran it to output data.
<form action="" method="get">
<input type="hidden" value="<?php echo $ad1_uid; ?>" name="author_uid">
<input type="hidden" value="complete" name="state">
<input type="hidden" value="<?php echo $user->mail; ?>" name="mail">
<button name="user_uid" type="submit" value="<?php echo $user->uid; ?>">Zapisuje się</button>
</form>
<?php
}
$debug = true;
if ($debug === true)
{
echo '<hr />
<h4>Debug Area</h4>
<pre>';
print_r(array($_GET, $_POST));
echo '</pre>
<hr />';
}
$wyslany_user_uid = $_GET['user_uid'];
$wyslany_author_uid = $_GET['author_uid'];
$wyslany_mail = $_GET['mail'];
$wyslany_state = $_GET['state'];
mysql_query("INSERT INTO `krajeto_demo`.`registration1` (user_uid, author_uid, mail, state ) VALUES (
'" . $wyslany_user_uid . "', '" . $wyslany_author_uid. "', '" . $wyslany_mail . "','" . $wyslany_state . "'
");
Try that and let me know what is echo'd to you.
this script displays data from a specific email address which the user enters.
the snippet of code below displays the data in a textfield at the top of the page however I want to display the data in a textfield in the body of text.
echo '<input name="login" type="text" value="' . $result['name'] . '>';
What do I change in the above code to enable me to do this.
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="orders"; // Table name
$email = $_POST['textfield'];
$db = new PDO('mysql:host='.$host.
';dbname='.$db_name.
';charset=UTF-8',
$username, $password);
$stmt = $db->prepare('SELECT * FROM `orders` WHERE `email`=:email LIMIT 1');
$stmt->bindValue(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount()>0)
{
echo '<input name="login" type="text" value="' . $result['name'] . '>';
}
else
{
echo "Email not found in the database!";
}
?>
form:
<form id="form_53" name="login" action="test.php">
<input type="submit" value="Track">
<input type="text" username="textfield" value="">
<input type="text" name="name" value="<?php echo $result['name']?>"> //I want to display results here
</form>
if both the code exists in the same file.. this will work
<input type="text" name="name" value="<?php echo $result['name']?>">
and if you want to check if there are rows returned you can use
<input type="text" name="name" value="<?php echo ($stmt->rowCount()>0) ? $result['name'] : "" ?>">
edited the code so that you know what exactly you want to do
First: Replace this code
if($stmt->rowCount()>0)
{
echo '<input name="login" type="text" value="' . $result['name'] . '>';
}
else
{
echo "Email not found in the database!";
}
just keep $result = $stmt->fetch(PDO::FETCH_ASSOC); and
if($stmt->rowCount()<=0) echo "Email not found in the database!";
Second: now in HTML section
<input type="text" name="name" value="<?php echo ($stmt->rowCount()>0) ? $result['name'] : "" ?>">
As long as you don't clobber $result you can do:
<input type="text" name="name" value="<?php echo $result['name']; ?>"> //I want to display results here
echo '<input name="login" type="text" value="' . $result['name'] . '">';
Just add a double quote to the echo'd string.
It's pretty easy to accomplish. Of course make sure that the $results array is included in the session for the desired HTML page that you are working on.
<form id="form_53" name="login" action="test.php">
<input type="submit" value="Track">
<input type="text" username="textfield" value="">
<input type="text" name="name" value="<?php echo $results['name']?>"> //I want to display results here
</form>
I have a list
Each row has a common input field "sort_order" that's stored in MySQL db.
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I want to be able to change the sort order inline, without going into the edit form.
How do I get all the values into the database. I think I need to loop through each row adding the sort_order[row_id] and value to an array. But I am stuck on how to achieve this.
all the values are posting according to firePHP. sort_order[50] 1, sort_order[51] 2 etc.
New Attempt at explaining:
I have a list view with 2 input fields.
<input name="cat_id" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
I have a function that's called on post in the controller:
public function sortOrderUpdate(){
//collect the values of cat_id and sort_order from each input into a array
//$this->request->post['sort_order']
//$this->request->post['cat_id']
//send to the model
$this->model_cat->updateCatSortOrder($sortorderarray);
}
And the database model file function:
public function updateCatSortOrder($sortorderarray){
foreach((int)$sortorderarray as $sort){
$this->db->query("UPDATE cat SET sort_order='" . (int)$sort['sort_order'] . "' WHERE cat_id = '" . (int)$sort['cat_id'] . "'");
}
}
Whats the best way to achieve this?
Just use empty square brackets:
<input type="text" name="sort_order[]" value"<?php echo $sort_order; ?>" />
You can then access the input as an array, saving you from building it yourself. It'll be stored as $_POST['sort_order'] (or $_GET, depending on the method attribute specified in your <form> tag).
On a related note, you should probably escape $sort_order when echoing it:
<input type="text" name="sort_order[]" value"<?php echo htmlspecialchars($sort_order); ?>" />
i would not recommend using [ ] in html names.
<input type="text" name="sort_order_<?php echo $row_id; ?>" value"<?php echo $sort_order; ?>" />
say, you have 50 input fields, when posted, you can build an array this way:
$sortorder = array();
for($i=0; $i<50; $i++){
$sortorder[] = $_REQUEST['sort_order_' . $i];
}
Ok this seems to work:
<input name="cat_id[]" type="hidden" value="<?php echo $cat['cat_id']; ?>" />
<input name="sort_order[]" type="text" value="<?php echo $cat['sort_order']; ?>" size="3" />
Controller:
public function updateCatSortOrder(){
$sortvals = $this->request->post['sort_order']; //$this->request->post same as $_POST
$row = $this->request->post['cat_id'];
$n = count($this->request->post['cat_id']);
$sortorder = array();
for($i=0; $i<$n; $i++){
$sortorder[] = array(
'cat_id' => $row[$i],
'sort_order' => $sortvals[$i]
);
}
$this->model_cat->updateCatSortOrder($sortorder);
}
Model:
//UPDATE CAT SORT ORDER
public function updateCatSortOrder($sortorder){
foreach($sortorder as $sort){
$this->db->query("UPDATE cat SET sort_order='" . $this->db->escape($sort['sort_order']) . "' WHERE cat_id = '" . $this->db->escape($sort['cat_id']). "'");
}
}