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" ...
Related
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(); }
It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting
I am posting data to PHP from jQuery using data from an HTML form.
Here is the jQuery line that sends the POST
$.post("InsertNewQuestion.php", $("Create_Question_Form").serialize());
Here is the PHP code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("Quizzes",$con);
$Quiz_Name = $_POST['Question'];
echo $Quiz_Name;
$Option_1 = $_POST['Option1'];
echo $Option_1;
$Option_2 = $_POST['Option2'];
echo $Option_2;
$Option_3 = $_POST['Option3'];
echo $Option_3;
$Option_4 = $_POST['Option4'];
echo $Option_4;
$Option_5 = $_POST['Option5'];
echo $Option_5;
$rowIDList = mysql_query("SELECT rowID FROM TestQuiz");
$ColumnValues = array();
$CurrentGreatestRowID = -1;
$LCV = 1;
while($row1 = mysql_fetch_assoc($rowIDList)) {
if ($CurrentGreatestRowID < $row1['rowID']) {
$CurrentGreatestRowID = $row1['rowID'];
}
$LCV++;
}
$CurrentRowID = $CurrentGreatestRowID+1;
$sql = "INSERT INTO TestQuiz (rowID,Quiz_Name,Option_1,Option_2,Option_3,Option_4,Option_5,Option_1_Votes,Option_2_Votes,Option_3_Votes,Option_4_Votes,Option_5_Votes)
VALUES(".$CurrentRowID.",'".$Question."','".$Option1."','".$Option2."','".$Option3."','".$Option4."','".$Option5."',0,0,0,0,0);";
if (mysql_query($sql,$con)) {
echo "Inserted values";
}
else {
echo ("Could not insert values: ". mysql_error());
}
mysql_close($con);
?>
Here is the HTML form
<form id="Create_Question_Form" action="" method="POST">
Question Name: input id="Question" class="Create_Question_Text_Box" type="text" name="Question_Name"><span id="Invalid_1"></span><br>
Option 1: input id="Option1" class="Create_Question_Text_Box" type="text" name="Option_1"><span id="Invalid_2"></span><br>
Option 2: input id="Option2" class="Create_Question_Text_Box" type="text" name="Option_2"><span id="Invalid_3"></span><br>
Option 3: input id="Option3" class="Create_Question_Text_Box" type="text" name="Option_3"><span id="Invalid_4"></span><br>
Option 4: input id="Option4" class="Create_Question_Text_Box" type="text" name="Option_4"><span id="Invalid_5"></span><br>
Option 5: input id="Option5" class="Create_Question_Text_Box" type="text" name="Option_5"><span id="Invalid_6"></span><br>
input type="Submit" id="Question_Submit" value="Create Question"></input>
</form>
Your form selector should be #Create_Question_Form. Note the # indicating that this is an element ID.
$("#Create_Question_Form").serialize()
Update
You are accessing the $_POST values by ID instead of name. Try this:
$Option_1 = $_POST['Option_1'];
$Option_2 = $_POST['Option_2'];
// etc
input type="Submit" id="Question_Submit" value="Create Question"></input>
<input type="Submit" id="Question_Submit" value="Create Question" />
You seem t be missing a bracket
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
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.