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
";
Related
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] );
}
I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]
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();
So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...
I have a small (42 hours) problem with my code trying to edit article
- just the basic editNews.php
When I choose article to edit the data appears in the forms from the DB and when
I hit "update" it returns no error but the data wasn´t updated
<?PHP
connection to database blah blah
?>
<?php
if(isset($_POST['update']))
{
$newsid = $_POST['newsid'];
$date=$_POST['date'];
$time=$_POST['time'];
$location=$_POST['location'];
$result=mysql_query("UPDATE news SET date='$date',time='$time',location='$location', WHERE newsid=$newsid");
header("Location: listNews.php");
}
}
?>
<?php
$newsid = $_GET['newsid'];
$result=mysql_query("select * from news where newsid=$newsid");
while($res=mysql_fetch_array($result))
{
$date = $res['date'];
$time = $res['time'];
$location = $res['location'];
}
?>
This is the form - just the normal one....
<form method="post" action="editNews.php" name="form1">
each item is like
<input type="text" name="headline" value="<?php echo $location;?>" id="UserName">
and
<input type="hidden" name="newsid" value=<?php echo $_GET['newsid'];?>
<input name="update" type="submit" value="update" />
Most likely there is something that I don´t see but "seeing" has taken almost 2 days now
... Is there a possibility I don´t have "edit" privileges in the mySql?
How do you know there was no error? Your code lacks:
print mysql_error();
Add it right after the UPDATE query.
Also your code is most likely to fail whenever the submitted content itself contains single quotes. To send correct SQL to the database it's advisable to apply mysql_real_escape_string() on all input variables.
Try
$result= mysql_query('UPDATE news SET
date = "'. $date .'",
time = "'. $time. '",
location = "' .$location. '"
WHERE newsid = '.$newsid.';') OR die(mysql_error());