This question already has an answer here:
How do I insert Data Into database with many Input which has same name?
(1 answer)
Closed 3 years ago.
i was trying to updating multiple MYSQL rows with one submit button,
before i used to create submit for each row, but since i have a lot of rows now i need to update them all together
index.php
<?php
if (mysqli_num_rows($row){
while($row1= mysqli_fetch_assoc($row){
id<input type="text" value="<?php echo $row["id"];?>" name='id' id="id" >
id<input type="text" value="<?php echo $row["name"];?>" name='name' id="name" >
}
<button type="submit" formaction="update.php">
submit
</button>
}
update.php
$id= $_POST['id'];
$name= $_POST['name'];
$sql = "UPDATE `$tabelname` SET
name='$name'
WHERE id='$id'";
its updating the first row only
Assuming that id is the primary key,
In your html, you need to use an array in the name. This allows the form to send it as an array instead of just taking the last value:
<?php while($row1= mysqli_fetch_assoc($row): ?>
<div>
<label>Name: </label>
<input type="text" value="<?=$row["name"]?>" name="name[<?= $row["id"] ?>]" id="name-"<?= $row["id"] ?> " />
</div>
<?php endwhile; ?>
The key here is name=“name[]”. The square brackets make it an array. I’m using the id as the index. (Note that <?= is just a much more concise way of writing <?php echo)
Then, in your php script, the easiest way to show you is to iterate through the array and do an update each time:
$row = $_POST[‘name’];
foreach($row as $id => $name) {
// This is a big No-No!
// $sql = "UPDATE `$tabelname` SET name='$name' WHERE id='$id'";
// use prepared statements. Always.
$sql = "UPDATE `$tabelname` SET name=? WHERE id=?"; // assuming “tabelname” is not user-provided
// database connection up to you
$stmt = $db->prepare($sql);
$stmt->execute( [$name, $id] );
}
Related
I am battling with the below code. The below is intended to:
1) Read data course data from database
2) Display data in a form ready for editing
3) Once edited, on submit, pass edited values to database
The issue I am getting is that I am able to execute 1 and 2 with no issues, but when I pass the edit data to database in step 3, the old values which where presented in step one are instead passed. How to I get the edited values to be passed and not the old values?
Thank you in advance
$readQuery="SELECT * FROM course WHERE course_id={$id}";
$readResult=mysqli_query($connection, $readQuery);
validateQuery($readResult);
while($row=mysqli_fetch_assoc($readResult))
{
$courseId=$row["course_id"];
$courseName=$row["course_name"];
$courseDescr=$row["course_descr"];
$courseCost=$row["course_cost"];
$courseDuration=$row["course_duration"];
}
?>
<form action="course_man.php?page=<?php echo $page?>" &id=<?php echo $id?>" method="post">
<table>
<tr>
<td align="right">
<!--Course ID <input type="text" name="course_id" value="<?php //echo $courseId;?>"/><br/>-->
Course Name <input type="text" name="course_name" value="<?php echo $courseName;?>"/><br/>
Course Description <textarea name ="course_descr" rows="6" cols ="30" ><?php echo $courseDescr;?></textarea><br/>
Course Cost <input type="text" name="course_cost" value="<?php echo $courseCost;?>"/><br/>
Course Duration <input type="text" name="course_duration" value="<?php echo $courseDuration;?>"/><br/>
<input type="submit" name="update" value="Update"/>
</td>
</tr>
</table>
</form>
<?php
}
if(isset ($_POST['update']))
{
$updateQuery="UPDATE course SET ";
$updateQuery.="course_name='{$courseName}', ";
$updateQuery.="course_descr='{$courseDescr}', ";
$updateQuery.="course_cost={$courseCost}, ";
$updateQuery.="course_duration={$courseDuration}, ";
$updateQuery.="WHERE course_id={$id}";
$check = mysqli_query($connection, $updateQuery);
mysqli_error($connection);
}
Go through your code line-by-line. How is the script supposed to get the new values from the form? A sql query is executed in all cases and the variables such as $courseName are set with the old values anyway. Now, when we get to the updating part, variables are still set with old values.
if(isset ($_POST['update']))
{
$updateQuery="UPDATE course SET ";
$updateQuery.="course_name='". $_POST['course_name'] ."', ";
$updateQuery.="course_descr='". $_POST['course_descr'] ."', ";
$updateQuery.="course_cost=". $_POST['course_cost'] .", ";
$updateQuery.="course_duration=". $_POST['course_duration'] .", ";
$updateQuery.="WHERE course_id=". $_POST['course_id'];
$check = mysqli_query($connection, $updateQuery);
mysqli_error($connection);
}
Move this code up before SELECT... query. And do not forget to sanitize user data before putting it into the query! Use mysqli_real_escape_string() http://php.net/manual/en/mysqli.real-escape-string.php or something else.
When you submit form to course_man.php it again fetch data from db and your below variables will be overwritten with db values.
$courseId=$row["course_id"];
$courseName=$row["course_name"];
$courseDescr=$row["course_descr"];
$courseCost=$row["course_cost"];
$courseDuration=$row["course_duration"];
Try this ....
$updateQuery="UPDATE course SET course_name = '$courseName',
course_descr = '$courseDescr',
course_cost = '$courseCost',
course_duration = '$courseDuration'
WHERE course_id = $id
";
I have a created an HTML form where users sign up and input there data into an SQL database. I have then retrieved that data in a webpage where they can view their profile. I have created a page where users can edit there profile by creating a form which updates the value in the SQL database for there user id.
I would like the form to use the current value of the SQL cell as the default for that user to make alterations easier. Example: currently user 7 has their city set as New York, when they visits the edit info page, the city field in the form already hase New York as the default value.
I have no problem getting the SQL info and assigning it to a variable, I just don't understand how to set it as the default value. I am aware of how you set default values for input fields though.
My code:
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
echo mysqli_error();
}
}
?>
<input type="text" name="aboutme" defualt="<?php echo $row['aboutme'] ?>" >
There's no default value for html input.
Input can has value, using attribute value:
<input type="text" name="some_name" value="Some value" />
In your case it's
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> />
Input can also has placeholder - some value that is present in an input, but erased when user starts to edit input's content:
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> placeholder="some value" />
How about
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
?>
<input type="text" name="aboutme" value="<?php echo $row['aboutme'] ?>" >
<?php
echo mysqli_error();
}
}
?>
And here is a good example http://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_pdo
Neither of the answers worked and upon further research and trial and error I created a solution.
I changed the value that was store in the array to just be a normal php variable:
$aboutme = $row['aboutme'];
I then called that variable using the following code:
<input type="text" name="aboutme" value="<?php echo htmlspecialchars($aboutme); ?>" >
Thanks for your help.
I hope you find my answer useful.
Why don't you try using it as a place holder? This will provide editable text.
<input type="text" name="aboutme" placeholder="<?php echo $row['aboutme'];" />
I have a list of 'orders' being pulled out, which consist of product name, description etc, one of the fields is quantity which is in an editable text box, next to that is an update button (which has an unique ID for that row pulled from the DB). Now when the update button is pressed, I want the quantity for that product to be updated. However i'm having problems getting the correct updated quantity to be matched with the ID of that row.
I can see that the problem is me setting the $quantity1 variable with just the last result pulled out inside the IF statement, but I can't think how to get it to relate the row i'm clicking on. Here is part of the code:
echo "<td>".$row['uName']."</td>";
echo "<td>".$row['prodID']."</td>";?>
<form method="post" action="reserved.php">
<td><input name="quantity1" type="text" id="quantity1" size="1" value='<?= $qty ?>' />
<td><input name="order2" id="order2" type="submit" class="button_add" value='<?= $row['ID']?>' /></td><?
echo "</tr>";
}
}elseif(!empty($studyDir) && $rowCount == 0){
?>
<?
}
}
if (isset($_POST['order2'])){
$order2 = $_POST['order2'];
$quantity1 = $_POST['quantity1'];
\\echo $quantity1;
$link3 = mysql_connect('localhost', '******', '******');
$SQL1 = "UPDATE ybsinter_stock.reservedStock SET qty = $quantity1 WHERE ID = '$order2'";
$result1 = mysql_query($SQL1);
mysql_close($link3);
unset($quantity1);
unset($order2);
header("Location:reserved.php");
}
?>
I can't see your form ending i.e. there is no <\form>.
Also note that declaring forms in tables (except entirely enclosed in a td) is bad HTML, run your code through the W3C validator.
Also try PHP heredocs for outputting blocks of HTML with embedded data....
echo <<<EOF
<tr>
<td>{$row['uName']}</td>
<td>{$row['prodID']}</td>
<td>
<form method="post" action="reserved.php">
<input name="quantity1" type="text" id="quantity1" size="1" value="{$qty}" />
// style this button right with CSS if you want ...
<input name="order2" id="order2" type="submit" class="button_add" value="{$row['ID']}" />
</form>
</td>
</tr>
EOF;
The above form will only submit data to your script with the id that you're interested in..
Your SQL query seems roughly correct, but beware of SQL injection - please bind your variables into your queries instead of inserting them. Use the mysqli or PDO libraries instead of the outdated basic mysql functions.
$mysqli = new mysqli( /* your connection params here */ );
$sql1 = 'UPDATE ybsinter_stock.reservedStock SET qty = ? WHERE ID = ?';
$stmt = $mysqli->query( $sql1);
$stmt->bind_param( 'sd', $quantity1, $order2);
$result = $stmt->execute();
I have a problem and I don't know how to sove it.I have an inventory table that contains an id (that is assign to a user)column and id_item column (that is assign to an item from items table) and an items table that also contains an id table.
More specifically this is what my database contains:
items table:
id name
1 Dagger
2 Staff
3 Wood Shield
Each with his unique id.
Inventory table:
id id_item username name
1 3 cristi Wood Shield
2 1 motoc Dagger
2 2 motoc Staff
The id is from every user id and id_item is the item's id from items table.
Problem:
Let's say I'm logged in as motoc who has 2 weapons in his inventory. Til now everything is fine. I want to make a button for every item that he has. The buttons are there but not working properly. When I click the first one is shows me ssss1 which is correct but when I press the second one nothing hapens. I want to show me ssss2 more specifically the next $row1['id_item'].
I really don't know how to solve this.
Thank you.
This is what i've tried:
if (isset($_SESSION['id'])) {
$sth1 = $dbh->prepare("SELECT * FROM inventory WHERE id = ".$_SESSION['id']."");
$sth1->execute();
while($row1 = $sth1->fetch(PDO::FETCH_ASSOC)){
$sth = $dbh->prepare("SELECT * FROM items WHERE id = ".$row1['id_item']."");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$ss = print $row1["id_item"];
?>
<form id='<?php echo $row1["id_item"]; ?>' method="POST" action="" >
<input type="hidden" name="refid" value="add" />
<input type="submit" name="submit<?php echo $row1["id_item"]; ?>" value="Add" />
</form>
<?php
}
if (isset($_POST["submit$ss"])) {
$refid = intval($_POST["refid"]);
$sth1 = $dbh->prepare("SELECT * FROM inventory WHERE id = ".$_SESSION['id']."");
$sth1->execute();
$row1 = $sth1->fetch(PDO::FETCH_ASSOC);
echo "ssss".$row1['id_item'];
}
}
This is a bad way of building your form. Since you're building a "personalized" form for EVERY item, there's no need to create dynamic field names, just a hidden form field:
<form ... >
<input type="hidden" name="id_item" value="<?php echo $row1['id_item'] ?>" />
<input type="hidden" name="refid" value="add" />
<input type="submit" name="submit" value="Add" />
</form>
Then you simply check $_POST['id_item'] in the form handling code, instead of having to look for every single possible submit1, submit2, etc...
As well, your form handling code is running within the same context as the form generation code, before the form has even had a chance to be displayed and get a user click. You should at least have somethign like
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... handle form here ...
echo "ssss...";
}
so the item info retrieval only runs when the form actually HAS been submitted.
Give this a shot. I'm kinda confused on exactly what you want to happen, but I think this will do it.
<?php
if (isset($_SESSION['id'])) {
$sth1 = $dbh->prepare("SELECT * FROM inventory WHERE id = " . $_SESSION['id']);
$sth1->execute();
while ($row = $sth1->fetch(PDO::FETCH_ASSOC)) {
$sth = $dbh->prepare("SELECT * FROM items WHERE id = " . $row['id_item']);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$ss = $row["id_item"];
?>
<form id='<?php echo $ss; ?>' method="post" action="?show">
<input type="hidden" name="item_id" value="<?php echo $ss; ?>" />
<input type="submit" name="submit" value="Add" />
</form>
<?php
}
if (isset($_GET["show"]) && isset($_POST['item_id'])) {
echo "ssss" . $_POST['item_id'];
}
}
I cleaned up some of the code and changed the way the form was built. I also changed the PHP code at the bottom to check for the changes in the form.
I will tell you now though. The way you designed the database should be changed. Keeping that updated will be a pain in the ass. You should use an items table, a users table, and have a pivot table between them since it is a many-to-many relationship.
Have fun!
The way I've structured my form data is by creating them in a while loop, but each time they are created the form will take a unique id.
So my question is, how do I access them individually and update specified data to a MYSQL server.
I've attempted to do it in the code at the end of the script, but I'm not sure how to access the forms individually
<?php
include 'user_data.php';
include 'core.inc.php';
$query = mysql_query("SELECT `post_text` FROM `posts`,`sub_posts` WHERE sub_posts.post_id = posts.id AND sub_posts.user_id='$user_id'");
while($row = mysql_fetch_array($query)){
?><?php echo $row[post_text].'<br>'?>
<form action="<?php $curent_file ?>" method="POST">
<textarea name="answer_field" > </textarea><br />
<input type="submit" value="Submit Answer">
<input type="hidden" name="post_id" value="<?php echo $row['post_id']; ?>" />
</form>
<?php
}//While Loop
if (isset($_POST['answer_field']) && !empty($_POST['answer_field'])){
$answer = mysql_real_escape_string($_POST['answer_field']);
$id = intval($_POST ['post_id']);
$query = "UPDATE `sub_posts` SET `sub_answer`='$answer' WHERE `post_id`='$id'";
}
?>
Only a single form gets posted when clicking the "submit" field. The form name does not get submitted by itself. Instead, you would place the post ID to which the form corresponds as a hidden field:
<input type="hidden" name="post_id" value="<?php echo $row['post_id']; ?>" />
And then later:
$answer = mysql_real_escape_string ($_POST ['answer']);
$id = intval ($_POST ['post_id']);
$query = "UPDATE `sub_posts` SET `sub_answer`='{$answer}' WHERE `post_id`={$id}";
Note that you definitely need to escape the answer before putting it in the query and make sure that the ID is a number. Otherwise, you're opening up your code to SQL injection attacks.