I am working on a project. What I need to do is basically enter some info into a form, have that form save it into a database, display the data, and then be able to edit the data. So far, I am able to do everything except edit the data. I've tried using $_GET to get the ID of the particular "bug" I need to edit, and I am able to do that, and get all of the information but I am not sure how to edit that particular ID in my database. Here is my handler: http://pastebin.com/mR6QWpJ7 and my form:
<form action="week10handle.php" method="POST">
<fieldset width="300px">
<legend width="300px"><b>Add a bug report</b></legend>
Product Name:<br/><input type="text" name="product_name"><br/>
Product Version: <br/><input type="text" name="product_version"><br/>
Hardware Type: <br/><input type="text" name="hardware"><br/>
Operating System: <br/><input type="text" name="os"><br/>
Frequency: <br/><input type="text" name="frequency"><br/>
Proposed Solutions: <br/><textarea name="solutions"></textarea><br/>
<input type="submit" value="Submit">
</fieldset>
</form>
Here is where I obtain the get data in my edit form page so far, but as of right now, I am not sure how to edit a particular ID in the database.
$getbug = htmlspecialchars($_GET["bugid"]);
if (!empty($getbug)){
$getbuginfo = mysql_query("SELECT * FROM `bugs` WHERE `id`= '$getbug'");
if ($getbuginfo = mysql_fetch_assoc($getbuginfo)){
$edit_product_name = $getbuginfo['product_name'];
$edit_prod_version = $getbuginfo['product_version'];
$edit_hardware = $getbuginfo['hardware_type'];
$edit_os = $getbuginfo['os'];
$edit_frequency = $getbuginfo['frequency'];
$edit_solutions = $getbuginfo['solutions'];
?>
<form action="week10handle.php" method="POST">
<fieldset width="300px">
<legend width="300px"><b>Edit bug <?php echo $getbug;?></b></legend>
Product Name:<br/><input type="edit" name="product_name" value="<?php echo $edit_product_name;?>"><br/>
Product Version: <br/><input type="edit" name="product_version" value="<?php echo $edit_prod_version;?>"><br/>
Hardware Type: <br/><input type="edit" name="hardware" value="<?php echo $edit_hardware;?>"><br/>
Operating System: <br/><input type="edit" name="os"value="<?php echo $edit_os;?>"><br/>
Frequency: <br/><input type="edit" name="frequency"value="<?php echo $edit_frequency;?>"><br/>
Proposed Solutions: <br/><textarea name="solutions"><?php echo $edit_product_name;?></textarea><br/>
<input type="submit" value="Submit">
</fieldset>
</form>
EDIT: Here is my update php code, but it is still not working, when I submit my form, it refreshes the page, but it doesn't update the database:
<?php
if (mysql_connect('localhost','root','') && mysql_select_db('bug_reports')){
$errors = array();
if (isset($_POST['product_name'], $_POST['product_version'],$_POST['hardware'],$_POST['os'],$_POST['frequency'], $_POST['solutions'])){
$product_name = mysql_real_escape_string(htmlentities($_POST['product_name']));
$product_version = mysql_real_escape_string(htmlentities($_POST['product_version']));
$hardware = mysql_real_escape_string(htmlentities($_POST['hardware']));
$os = mysql_real_escape_string(htmlentities($_POST['os']));
$frequency = mysql_real_escape_string(htmlentities($_POST['frequency']));
$solutions = mysql_real_escape_string(htmlentities($_POST['solutions']));
$getbug = mysql_real_escape_string(htmlentities($_POST['bugid']));
if (empty($product_name) || empty($product_version) || empty($hardware) || empty($os) || empty($frequency) || empty($solutions)){
$errors[] = 'All fields are required.';
}
if (!is_numeric($product_version) || !is_numeric($frequency)){
$errors[] = 'Product version and frequency must both be numbers';
}
if (empty($errors)){
$update = "UPDATE `bugs` SET `product_name` = '$product_name', `product_version = '$product_version', `hardware_type = '$hardware', `os` = '$os', `frequency` = '$frequency', `solutions` = '$solutions' WHERE `id` = $getbug";
if ($update = mysql_query($update)){
header('Location: week10handle.php');
} else{
$errors[] = 'Something went wrong, please try again.';
}
} else{
foreach($errors as $error){
echo '<p><strong>'.$error.'</strong></p>';
}
}
}else{
$getbug = htmlspecialchars($_GET["bugid"]);
}
if (!empty($getbug)){
$getbuginfo = mysql_query("SELECT * FROM `bugs` WHERE `id`= '$getbug'");
if ($getbuginfo = mysql_fetch_assoc($getbuginfo)){
$bugid = $getbuginfo['id'];
$edit_product_name = $getbuginfo['product_name'];
$edit_prod_version = $getbuginfo['product_version'];
$edit_hardware = $getbuginfo['hardware_type'];
$edit_os = $getbuginfo['os'];
$edit_frequency = $getbuginfo['frequency'];
$edit_solutions = $getbuginfo['solutions'];
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<fieldset width="300px">
<legend width="300px"><b>Edit bug <?php echo $getbug;?></b></legend>
Product Name:<br/><input type="edit" name="product_name" value="<?php echo $edit_product_name;?>"><br/>
Product Version: <br/><input type="edit" name="product_version" value="<?php echo $edit_prod_version;?>"><br/>
Hardware Type: <br/><input type="edit" name="hardware" value="<?php echo $edit_hardware;?>"><br/>
Operating System: <br/><input type="edit" name="os"value="<?php echo $edit_os;?>"><br/>
Frequency: <br/><input type="edit" name="frequency"value="<?php echo $edit_frequency;?>"><br/>
Proposed Solutions: <br/><textarea name="solutions"><?php echo $edit_product_name;?></textarea><br/>
<input type="hidden" name="bugid" value="<?php echo $bugid;?>" >
<input type="submit" value="Update">
</fieldset>
</form>
<?
}else{
echo "something went wrong";
}
}else{
echo "No bug found.";
}
}else
echo 'Could not connect at this time.';
?>
A typical way to detect an update, as opposed to an insert, would be to check for a value for id. So, in your edit form add a hidden field to pass the id to the handler and then in your handler you can decide whether to process it as insert or update based on the presence of the id field.
if (isset($_GET['id']) {
// do update
$sql = 'UPDATE `bugs` SET ... WHERE id = ' . intval($_GET['id']);
} else {
// do insert
$sql = 'INSERT INTO `bugs` VALUES ....';
}
UPDATE `bugs` SET `product_name` = '...', `product_version` = '...', ... WHERE `id` = $bugid;
Where the "..." will be replaced with newly $_POST-ed values for each column
Related
I am working on a page that I need to be able to update single records from my MySQL database using PHP. Can someone please help me? When I try to update one record all my other records are updated.
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p><strong>ID:</strong> <?php echo $id; ?></p>
<strong>Name: *</strong> <input class="form-control" type="text" name="name" value="<?php echo $name; ?>" /><br/>
<strong>Month: *</strong> <input class="form-control" type="text" name="month" value="<?php echo $month; ?>" /><br/>
<strong>event1: *</strong> <input class="form-control" type="text" name="event1" value="<?php echo $event1; ?>" /><br/>
<strong>event2: </strong> <input class="form-control" type="text" name="event2" value="<?php echo $event2; ?>" /><br/>
<strong>event3: </strong> <input class="form-control" type="text" name="event3" value="<?php echo $event3; ?>" /><br/>
<strong>event4: </strong> <input class="form-control" type="text" name="event4" value="<?php echo $event4; ?>" /><br/>
<strong>timesub: </strong> <input class="form-control" type="text" name="timesub" value="<?php echo $timesub; ?>" readonly /><br/>
<p>* Required</p>
<input type="submit" name="submit" value="Submit" class="btn btn-info">
<input type=reset name="reset" value="Reset" class="btn btn-danger">
</div>
</form>
That is my form, and then I follow it with this code:
<?php
}
include('db_connect.php');
if (isset($_POST['submit'])) {
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$month = mysql_real_escape_string(htmlspecialchars($_POST['month']));
$event1 = mysql_real_escape_string(htmlspecialchars($_POST['event1']));
$event2 = mysql_real_escape_string(htmlspecialchars($_POST['event2']));
$event3 = mysql_real_escape_string(htmlspecialchars($_POST['event3']));
$event4 = mysql_real_escape_string(htmlspecialchars($_POST['event4']));
$timesub = mysql_real_escape_string(htmlspecialchars($_POST['timesub']));
// check thatfields are filled in
if ($name == '' || $month == '' || $event1 == '' || $timesub == ''){
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, $error);
} else {
// save the data to the database
mysql_query("UPDATE announcement SET name='$name', month='$month', event1='$event1', event2='$event2', event3='$event3', event4='$event4', timesub='$timesub'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
} else
// if the form hasn't been submitted, get the data from the db and display the form
{// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0) {
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM announcement WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row) {
// get data from db
$name = $row['name'];
$month = $row['month'];
$event1 = $row['event1'];
$event2 = $row['event2'];
$event3 = $row['event3'];
$event4 = $row['event4'];
$timesub = $row['timesub'];
// show form
renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, '');
} else {// if no match, display result
echo "No results!";
}
} else {// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
I got the code from: http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/
Great article!
Thanks in advance for the help.
First of all stop using mysql_* its deprecated and closed in PHP 7. You can use mysqli_* or PDO.
Whats wrong with your query:
This is very important, if you not use WHERE CLAUSE in your UPDATE STATEMENT than it will update the all rows.
You must need to add WHERE CLAUSE in your query at end, something like:
WHERE id = '$id'
Also note that, your code is open for SQL INJECTION, you must need to prevent with SQL INJECTION, you can learn about the prepared statement. This post will help you to understand: How can I prevent SQL injection in PHP?
*If you want to know How mysqli_* works, this document will help you: http://php.net/manual/en/book.mysqli.php
If you want to work on PDO, you can follow this manual: http://php.net/manual/en/book.pdo.php
Take a close look at your query:
mysql_query("UPDATE announcement SET name='$name', month='$month', event1='$event1', event2='$event2', event3='$event3', event4='$event4', timesub='$timesub'")
Your query is missing a WHERE clause. Without a WHERE clause, your query will update all rows in the table announcement. You need to add something like:
WHERE id='$id'
This will restrict the update to only the row you want to update.
I have an administrator.php which displays 300 records from a table called 'player'. Next to each record, there is an edit option which redirects you to edit.php and the 15 columns of that record (including the primary key - playerid) is displayed inside text boxes. Line of code below:
<a href='edit.php?playerid=".$query2['playerid']."'>Edit</a>
On edit.php you are able to change data of these columns. Upon submit, an update query is sent to update the table but unfortunately, it's not working. My error message continues to display ("testing for error..."); not sure why.
//Setups up the database connection
$link = mysql_connect("localhost", "root", "");
mysql_select_db("fantasymock", $link);
if(isset($_GET['playerid'])) {
$playerid = $_GET['playerid'];
//Query to display results in input box
$query1 = mysql_query("SELECT * from player WHERE playerid = '$playerid'");
$query2 = mysql_fetch_array($query1);
}
if(isset($_POST['submit'])) {
$playerid = $_POST['playerid'];
$preranking = $_POST['preranking'];
$playerlast = $_POST['playerlast'];
$playerfirst = $_POST['playerfirst'];
$position = $_POST['position'];
$battingavg = $_POST['battingavg'];
$run = $_POST['run'];
$homerun = $_POST['homerun'];
$rbi = $_POST['rbi'];
$sb = $_POST['sb'];
$win = $_POST['win'];
$save = $_POST['save'];
$strikeout = $_POST['strikeout'];
$era = $_POST['era'];
$whip = $_POST['whip'];
//Query to update dB
$query3 = mysql_query("UPDATE player SET playerid='$playerid', preranking='$preranking', playerlast='$playerlast', playerfirst='$playerfirst', position='$position', battingavg='$battingavg', run='$run', homerun='$homerun', rbi='$rbi', sb='$sb', win='$win', save='$save', strikeout='$strikeout', era='$era', whip='$whip' WHERE playerid='$playerid'");
header("Location: administrator.php");
} else {
echo "Testing For Error....";
}
?>
<form action="" method="POST">
Player ID:<input type="text" name="playerid" value="<?php echo $query2['playerid'];?>"/> <br/>
Preranking:<input type="text" name="preranking" value="<?php echo $query2['preranking'];?>"/> <br/>
Last Name:<input type="text" name="playerlast" value="<?php echo $query2['playerlast'];?>"/> <br/>
First Name:<input type="text" name="playerfirst" value="<?php echo $query2['playerfirst'];?>"/> <br/>
Position:<input type="text" name="position" value="<?php echo $query2['position'];?>"/> <br/>
Batting Avg:<input type="text" name="battingavg" value="<?php echo $query2['battingavg'];?>"/> <br/>
Runs:<input type="text" name="run" value="<?php echo $query2['run'];?>"/> <br/>
Homeruns:<input type="text" name="homerun" value="<?php echo $query2['homerun'];?>"/> <br/>
Rbi:<input type="text" name="rbi" value="<?php echo $query2['rbi'];?>"/> <br/>
Sb:<input type="text" name="sb" value="<?php echo $query2['sb'];?>"/> <br/>
Wins:<input type="text" name="win" value="<?php echo $query2['win'];?>"/> <br/>
Saves:<input type="text" name="save" value="<?php echo $query2['save'];?>"/> <br/>
Strikeouts:<input type="text" name="strikeout" value="<?php echo $query2['strikeout'];?>"/> <br/>
Era:<input type="text" name="era" value="<?php echo $query2['era'];?>"/> <br/>
Whip:<input type="text" name="whip" value="<?php echo $query2['whip'];?>"/> <br/>
<br>
<input type="submit" name="submit" value="submit">
</form>
FYI: Every column in the table and tablename is spelled correctly, I've triple checked before posting. And I'm aware of MySQL injection. Can someone see a problem? Thank you in advance!
EDIT: I just added an additional if statement if($query3) and it now works.
You are checking for POST variables, but you are getting to edit.php through a GET request. There isn't anything on $_POST. Therefore it drops down to the else of your if block and prints out Testing For Error...
Your script in getting into the else part. That means there nothing it is getting as $_POST['submit']. Make sure that your submit button must have a name attribute as submit.
<input type="submit" name="submit" value="" />
please check what showing in error.log file. You may insert these lines at your edit.php file
error_reporting(E_ALL);
ini_set('display_errors', 1);
to display error.
Replace your else part by this for more detailed mysql errors
else{ echo "Testing For Error...." .mysql_error(); }
I can't change the information from my database.
I'm trying to update information from my database. But it's not working.
The user just need to put one existing ID from the table, and it will update the information from the specific column, in this case, it's a column called "titulo".
Here my page code:
<?php
if(isset ($_POST['submit']))
{
include("../classes/administrador/Administrador.class.php");
$Administrador = new Administrador();
if ($Administrador->atualizarCD($_REQUEST['id'],$_REQUEST['titulo']))
{
echo "It works !!!<br>";
} else {
echo "its not working<br>";
}
$Administrador->endAdministrador();
}
else{
?>
<b>Alterar CD</b><br><br>
<form name="form3" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<b>ID</b>:
<input type="text" name="id" size="3">
<br>
<br>
<b>Titulo</b>:
<input type="text" name="titulo">
<br>
<input type="submit" name="submit" value="submit">
</form>
<p> </p>
<?php
}
?>
And my function code:
function atualizarCD($id, $titulo) {
$sql= "UPDATE `cds` SET `titulo` = '$titulo' WHERE `ID` = '$id";
if($this->bd->executarSQL($sql)) return true;
else return false;
}
You have missed to add ' end of the query
$sql= "UPDATE `cds` SET `titulo` = '$titulo' WHERE `ID` = '$id' ";
I am trying to create a form that will edit rows from my db table. (Based on some code I got from a StackOverflow page.)
I am able to populate the form with relevant data, but when I submit the form, the row isn't updated. In fact, some of my columns are deleted.
What did I do wrong?
edit.php
<?php
$UID = (int)$_GET['f'];
$query = mysql_query("SELECT * FROM user_feeds WHERE feed_id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$feedtitle = $row['feed_title'];
$feedurl = $row['feed_url'];
$feedorder = $row['feed_order'];
$feedowner = $row['feed_owner'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$UID;?>">
Title:<br /> <input type="text" name="ud_feedtitle" value="<?=$feedtitle?>"><br>
URL: <br /> <input type="text" name="ud_feedurl" value="<?=$feedurl?>"><br>
Order: <br /> <input type="text" name="ud_feedorder" value="<?=$feedorder?>"><br>
Owner:<br /> <input type="text" name="ud_feedowner" value="<?=$feedowner;?>"><br>
<input type="Submit">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</div>
</body>
</html>
update.php
<?php
$ud_ID = $_REQUEST["ID"];
$ud_feedtitle = $_POST["feed_title"];
$ud_feedurl = $_POST["feed_url"];
$ud_feedorder = $_POST["feed_order"];
$ud_feedowner = $_POST["feed_owner"];
$query = "UPDATE user_feeds SET feed_title = '$ud_feedtitle', feed_url = '$ud_feedurl', feed_order = '$ud_feedorder', feed_owner = '$ud_feedowner', WHERE feed_id = '$ud_ID'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
Reason:
The name of the input field is the same name by which $_POST is populated. The variables you are currently requesting :
$_POST["feed_title"];, $_POST["feed_url"];, $_POST["feed_order"];, $_POST["feed_owner"];
are all empty as they don't exist. When updating, you are replacing the values in your table with blank values.
Solution:
In your update.php, the following should be there instead.
$ud_ID = $_POST["ID"];
$ud_feedtitle = $_POST["ud_feedtitle"]; //corresponding to <input type="text" name="ud_feedtitle" ...
$ud_feedurl = $_POST["ud_feedurl"]; //corresponding to <input type="text" name="ud_feedurl" ...
$ud_feedorder = $_POST["ud_feedorder"]; //corresponding to <input type="text" name="ud_feedorder" ...
$ud_feedowner = $_POST["ud_feedowner"]; //corresponding to <input type="text" name="ud_feedowner" ...
I have looked everywhere here in Stackoverflow and I´ve searced 16.493 sites on Google but no answers to the most basic thing in php (edit record)
I´ve managed to code the most complicated stuff - but this is like a cancer and would also help others.
I have to files - edit.php - and update.php
edit.php works and it retrieves the data from the record
Here is the edit.php
<?php
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$UID = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM cloudbig WHERE id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$fs = $row['fs'];
$texti = $row['texti'];
}
?>
<form name="form1" method="post" action="update.php">
<input type="text" name="fs" value="<?php echo $texti ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
<?php
}
?>
and here is update.php
<?php
$id = $_REQUEST["id"];
$fs = $_POST["fs"];
$texti = $_POST["texti"];
mysql_connect('localhost', 'user', 'pass') or die(mysql_error());
echo "MySQL Connection Established! <br>";
mysql_select_db("db") or die(mysql_error());
echo "Database Found! <br>";
$query = "UPDATE cloudbig SET fs = '$fs', texti = '$texti' WHERE id = '$id'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
I´ve done a whole news/online magazine site in php but simple edit.php function is a problem
I think that the short answer is that you never post the "id" up to the update.php script. Your form needs to look like this:
<form name="form1" method="post" action="update.php">
<input type="hidden" name="id" value="<?php echo $UID ?>">
<input type="text" name="fs" value="<?php echo $fs; ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
which will send the id into the POST array where it can be accessed by $id = $_REQUEST["id"];
You can also accomplish this by sending it via _GET by modifying the form action:
<form name="form1" method="post" action="update.php?id=<?php echo $UID ?>">
<input type="text" name="fs" value="<?php echo $fs; ?>" size="60">
<textarea rows="8" name="texti" id="userName" cols="60"><?php echo $texti ?></textarea>
<input type="submit" name="save" value="submit" />
</form>
which will put it in the $_GET array where it will also be seen in the $_REQUEST array.
Lastly, there are some MAJOR ISSUES with your code:
First and foremost, it is subject to SQL injection! You MUST escape
your variables before passing them into a MySQL query.
Second. As pointed out by iDifferent, you appear to bve echoing the wrong value into the fs field (you're setting it equal to the texti field)
Third, why do you have this loop?
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$fs = $row['fs'];
$texti = $row['texti'];
}
If you're fetching by ID you should never have duplicates. Make sure that ID is a primary key and there is no reason to check for multiple rows.