Update mysql data using php and form - php

I´ve been having a weird problem trying to create a php page that uses html forms to update mysql data.
The idea is to create a page that retrieves all the rows from a "news" table that I have, and inserts all the data into html forms as "default" values, so I can see what is already written before changing whatever I want in this form. Each form is generated exclusively for each row of data retrieved.
For that I use the POST method and two php files, one called "updateNews.php" which retrieves data and renders forms, and another one called "newsUpdater.php" which injects the updated data.
I have two problems here. One, the form doesn´t post the new data written in the form, but instead it posts the original data posted as "default". I guess this is a problem in my form code. I guess I´m not coding "default" values right.
The second problem is pretty strange. I retrieve rows from "news" table in reverse order, but when I "submit" the form associated with a particular row, it posts the data from the first row, not the row I´m interested in.
This is my code in the first php file, which retrieves data and renders forms:
<html>
<head>
<?php
include "connectToNews.php";
mysqli_set_charset($conToNews,"utf8");
$query = mysqli_query ($conToNews, "SELECT * FROM news ORDER BY id DESC");
?>
</head>
<body>
<?php
while ($newsArray = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
echo "<form action='newsUpdater.php' method='post' enctype='multipart/form-data'>";
echo "<p>".$newsArray['id']."</p><br>";
echo "<input name='Id' type='hidden' value='".$newsArray['id']."'>";
echo "<input class='input' name='Fecha' type='text' value='".$newsArray['fecha']."'><br>";
echo "<textarea class='textarea' name='Headline' type='text'>".$newsArray['headline']."</textarea><br>";
echo "<textarea class='textarea' name='Story' type='text'>".$newsArray['story']."</textarea><br>";
echo "<input type='submit' value='Actualizar'><br><br><br>";
echo "</form>";
}
?>
</body>
</html>
So, as you can see, I render a new <Form> for each existing row. I use 2 <input> tags and 2 <textarea> tags. One of the <input> tags is hidden and has he "Id" info associated with the particular row data. In anycase, I use "echo" with this Id data to verify that is retrieving ok (and it is). I use "value" attribute to set the retrieved text as default text in this <input> tags.
In the <textarea> tags, I use the space between the opening tag and the closing tag to locate the "default" text.
At this point, everything renders ok, I get as many forms as there are rows in "news" table and and when i press submit button, it takes me to the second php file.
The second php file is the "data updater". The code is the faollowing:
<html>
<head>
<?php
$Id=$_POST['Id'];
$Fecha=$_POST['Fecha'];
$Headline=$_POST['Headline'];
$Story=$_POST['Story'];
echo "<p>".$Id."</p><br>";
echo "<p>".$Fecha."</p><br>";
echo "<p>".$Headline."</p><br>";
echo "<p>".$Story."</p><br>";
include "connectToNews.php";
mysqli_set_charset($conToNews,"utf8");
$query=mysqli_query ($conToNews, "UPDATE news SET fecha='$Fecha' headline='$Headline' story='$Story' WHERE id='$Id'");
?>
</head>
<body>
<?php
echo "<p>News updated</p><br>";
echo "<p><a href='updateNews.php'>Go back to form</a></p>";
?>
</body>
</html>
As you can see, I´m saving the posted data "$_POST['whatever']" into 4 variables, just to have an easier time writting the future mySql query.
Then, I echo this variables to check what info is really been passed. And this is where it gets weird, because te rendered texts are the ones retrieved from to the first row in my "news" table, no matter which row am I editing in the form or what I´m writting in the form.
The other problem is that, regard of getting the "ok" message related to the updating process, the data never saves to "news" table. Although, I could be wrong, because I´m really injecting the original text from row 1 into row 1, no matter of which row I was really trying to edit.
Could you read my code and tell me if you guys see any problem.
Thanks!!!

In an UPDATE query the columns being updated must be seperated by commas, this explains why your data is not being updated.
The reason you didnt know for sure that the query was failing, and why, is that you are not testing that the query actually worked or not.
It is always a VERY good idea to test the results of all MYSQLI_ calls so I would add. This will then show you an error message that would help in bebugging
$query=mysqli_query ($conToNews,
"UPDATE news SET fecha='$Fecha',
headline='$Headline',
story='$Story'
WHERE id='$Id'");
if ( $query === FALSE ) {
echo mysqli_error($conToNews);
exit;
}
You have some SQL Injection issues in this code, you should read How can I prevent SQL injection in PHP?

Related

i have a textbox which extract the content of dropdownlist now whenever i change the extracted content it should be saved into database

I have a text box which extracts the content of dropdownlist.Now whenever i extract the content i too need to edit it ana save it into the database.How can i do????
Here is my code:
<?php
require'conn.php';
$select_query="Select dynamictext from tbl_content where type=1";
$select_query_run =mysql_query($select_query);
echo'Dynamictext:';
echo "<select name='dynamic text' id='names' >";
while ($select_query_array= mysql_fetch_array($select_query_run) )
{
$value=$select_query_array["dynamictext"];
echo "<option value='$value' >".htmlspecialchars($select_query_array["dynamictext"])."</option>";
}
echo "</select>";
?>
Based on the clarification I got above from #krisha above, I'm going to take a stab at answering this. You'll want to refer to my comment above, for a definition of (Option A) and (Option B), as I defined them.
Let's assume you've got (Option A) working and that (as far as the select HTML element is concerned), it is functional.
Let's also assume that you know to do the following:
Place the select tag inside of a form tag.
Set the form tag's action and method values.
Place a <input type="submit" value="Submit"> inside of the form tag.
If none of the above made sense, see here.
Once you've done everything above, that will result in the value of the HTML drop-down being available to PHP after the user clicks the Submit button and the page refreshes. How the value of the drop-down is passed through the submit process will depend on the method value you pass to the form tag. I'll assume you use method="get" (which will result in the value of the drop-down appearing in the URL after the refresh). If you want more info on get versus post, see here.
Once the refresh occurs, you use PHP's $_GET[""] to retrieve the value of the HTML drop-down. In your case, you would use $_GET["dynamic text"] (since the name of your select is dynamic text). You could set this value to a variable, like so:
$value_of_select = $_GET["dynamic text"];
At this point, you have the value the user selected from the HTML drop-down. Now, push it to the database. It looks like you already understand how to pass queries to a database. The only difference in this case is that you want to do an insert or an update, not a select.

Translate array into HTML form then submit function

I am a bit at lost as my PHP knowledge is very basic to say the least, but I am learning on the fly.
In a Wordpress plugin, I have the following php function:
$pool->get_leagues( true );
which gives a an array of league values: the id number and the name of the league.
Then there is this function:
$pool = new Football_Pool_Pool;
$pool->update_league_for_user( get_current_user_id(), <<THIS IS WHERE SELECTED ID NUMBER GOES>> );
I need to create an HTML form that lists the available league names that the user on a page can select in either an dropdown form, with radio buttons or plain links, whatever is easiest for the example.
Then, when the user makes a choice and submits the values, the league value should be updated into the database as per the above function.
Here are my total newbe / dummy questions:
How does the PHP look that would create the desired action? where would I put this code? Do I create a whole new PHP page to handle this form, or do I need to enter it into one of the existing php pages somewhere?
Based on answer 1, how does the HTML look that would display the form and call the php once submitted?
If this is easier with javascript, please feel free to share that example.
Help is much much appreciated!
I think you have to create a whole new PHP file. Here the PHP code and the HTML are in a single PHP file.
<?php
if(!isset($_POST['submit'])){
//if the form has not been submitted yet, display the form
echo "<form name='myform' action='' method='POST'>";
//Get array of leagues
$leagues = $pool->get_leagues(true);
//Make a drop down
echo "<select name='league'>";
foreach($leagues as $league){
echo "<option>$league</option>";
}
echo "</select>";
echo "<input type='submit' name='submit' value='Submit'>";
echo "</form>";
}else{
//If the form has been submitted, run the PHP function to update database
$pool = new Football_Pool_Pool;
$pool->update_league_for_user(get_current_user_id(), $_POST['league']);
echo "Database updated!";
}
?>

ID Getting Lost In Loop

I've been working on a way to build an archive for new threads. The over all goal was to make it so that if someone wanted to edit or delete a news thread they could, as well they could save a thread as a draft so that it ain't displayed to the public. I am using MySQL to store all the news threads, and I have it so that it prints out every news feed and the information for it. But when i click the edit button to edit that thread, it ALWAYS uses the id for the last MySQL entry called and NOT the ID I set it to use via a hidden form. Anyways here's the code and all parts to it. I'm so confused, and could really use some help. If you got questions just ask.
Main Script: http://pastebin.com/hn3cgVXu
Article_Post: http://pastebin.com/hhaLkuXe
Article_Archive: http://pastebin.com/X2fDg4dk
The original value for ID is called from the database, and set from article_archive
Display:
http://i25.photobucket.com/albums/c51/dog199200/Untitled-2.png
The Pencil is Edit, Trash Can is Delete. The image clearly shows that the loop is getting the ID, but that specific ID isn't being passed when the edit image is clicked.
In your Article_Archive when you loop through your database results you are naming your hidden input field the same thing for all the results.
<?php
while($row = mysql_fetch_array($news_list)) {
echo "<form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\" id=\"result_".$row['id']."\" name=\"result_".$row['id']."\">";
// ...
echo "... <input type=\"hidden\" name=\"id\" value=\"".$row['id']."\">";
// ...
echo "</form>";
} ?>
You're calling it id, so when you place multiple hidden input fields on the same form it will just grab the last one. Where is the javascript for when you click edit? You won't be able to do a standard form submit with that code since you're overwriting all the input fields with the same name attribute.

How to post a specific record from resultset to another page

I'm a newbie in PHP and i've got stucked into this...
I have a database and a simple search form. I can search without problems using the criteria i want - for example, i fill in as name "Alex" and i can see 5 records in my resultset with this criteria. So far so good...
Here's the problem : I need to create a Link / Button - whatever - and Post/Get the values for the specific record that i'll choose. When the resultset contains only one record found, i have no problems - everything works fine. But, whenever the resultset returns more than 1 records, the Post/Get method grabs the data for the last record.
Let me show you what i'm doing here... Here's the data i'm retrieving :
while ($row= mysql_fetch_array($result)) {
$my_id = $row["ID"];
$my_name = $row["name"];
$my_profession = $row["profession"];
echo "<div align='center'><tr>
<td><div align='center' style='color:white;'><font size='2' face='Arial'>$my_id</div></td></font>
<td><div align='center' style='color:white;'><font size='2' face='Arial'>$my_name</div></td></font>
<td><div align='center' style='color:white;'><font size='2' face='Arial'>$my_profession</div></td></font>
<td><div align='center' style='color:white;'><font size='2' face='Arial'><form action='person_info.php' method='POST'><input type='hidden' name='PersonID' value='$my_id' /><input type='hidden' name='PersonName' value='$my_name' /><input type='hidden' name='PersonProfession' value='$my_profession' /><input type='submit' value='Show' /></div></td></font>
.....
Here's the code for person_info.php :
$my_id = $_POST["PersonID"];
$my_name = $_POST["PersonName"];
$my_profession = $_POST["PersonProfession"];
echo "
<div align='center'><font size='4' face='Georgia' style='color:red';><b>$my_id, $my_name, $my_profession</b></font></div>
If there's only one record involved, everything works great. If there's more than one, i get the last one's details. For example, from the resultset :
1 Alex Unemployed
2 Alex Carpenter
3 Alex Gardener
... the record that will be posted finally is the "3 Alex Gardener".
Any ideas ?
Thanks in advance!
If that is the exact code you are using, it doesn't look like you are closing your form. So when you click the submit button, it's grabbing all of the data and then overwriting it each time until it gets to the last one.
Throw a:
</form>
At the end there and it should clear it up.
is personID, personname and personProffesion always the name of the input? it looks like you base the value on the database entry that is currently pulled in but If you are not using a unique name that will cause an issue.
If you are using the same name for each set of hidden inputs there is no way for to tell them apart when you pass them with Post or Get, your name field should be unique, the last entry is the only one that is going through because as each one is added its essentially overwriting the past entries.
let me know if that works for you, I hope you get it figured out!
EDIT:
The easiest way to make each entry go to a unique page is using a GET (as mentioned by Paul Weber) multiple forms with post work but it gets messy quick:
while ($row= mysql_fetch_array($result)) {
$my_id = $row["ID"];
$my_name = $row["name"];
$my_profession = $row["profession"];
echo'Name Your Link';
}
the code above would create a link that passes the required information as a get you can then pull it out on the somepage.php its also a lot cleaner then the forms.
If you can use get, you can pass the Parameters just by appending them to the Url.
So you could go
Save
If you cannot use Get, you could either seperate the Forms, creating a Form tag around all the Input elements, so only the ones in the current scope would be submitted. Which would mean you would create a new Form for every Line.
Alternatively use JQuery to do a post.

Help with deleting items in a list, using PHP

I have a list of email addresses in a table, which is populated via an SQL query. Next to each email address, I've placed a submit button which I want to use to delete the email address that appears in that particular table row.
I thought of appending the email address to the name of each delete button, with the hope that it will take me in the right direction.
while($row = mysql_fetch_array($result))
echo "<tr><td>".$row['email_adress']."</td><td><input type=\"submit\" value=\"Delete\" name=\"delete".$row['email_adress']."\"></td></tr>";
I'm wondering how to use the delete button for each entry. Any help?
I think the issue is that you are attempting to use submit buttons to contain data when submit buttons are not meant to contain data. Well they can and people do use them that way, but I prefer to use submit buttons to determine how to handle the data rather than to be the data in the submit. There are two basic methods that I think would be a fair extension to what you are trying to do.
1.) Use links to issue the delete
2.) Use the submit button to issue the delete, but include a hidden form field to contain the email address to delete.
In the case of using a link you don't have to deal with a form, but I don't know about the rest of the page. If you are sending any other data, then a form is the ideal way. If you are just sending a single piece of data to delete the email, then I suggest a link. My recommendation come from a functional perspective. You might have a UI reason to a button that I don't know about.
In the case of using a form, the hidden field should contain the primary key (untested):
while($row = mysql_fetch_array($result)) {
echo "<tr>
<td>".$row['email_adress']."</td>
<td><form action="some/uri/to/something">
<input type=\"hidden\"
name=\"emailAddress\" value=\"{$row['email_adress']}\"/>
<input type=\"submit\" value=\"Delete\"
name=\"delete".{$row['email_adress']}."\">";
</form>
</tr>
</td>";
}
You have to create a form around each submit else every hidden field in the form would be submitted telling you nothing about which email to delete. You can do many more things with the submit by using Javascript, but the simple method would be to just use a link -- forget about forms.
If a button is absolutely a must, you could output a small form for each button and add a hidden field containing the id (or email, if you insist). The form would submit the id or address in the hidden field, which you pick up in your processing script and run your delete query.
edited to remove a portion of the answer that was determined to be an unwise method
so I've been messing around with this code trying to get a "prefetch browser add-on" to trigger something and kill my database... but I havn't been able to trigger anything yet... but I'd sure like to.
<?php
//CREATE AND POPULATE DB
if(!file_exists('a.sqlite')){
$db = new SQLite3('a.sqlite');
$db -> exec("CREATE TABLE test (idx INTEGER PRIMARY KEY, number INTEGER NOT NULL);");
for($i=0;$i<9;$i++){
$db -> exec("INSERT INTO test (number) VALUES (".(rand(1000,9999)).");");
}
}else{
$db = new SQLite3('a.sqlite');
}
//PERFORM DELETE FROM HREF
if(isset($_REQUEST['delete'])){
$db -> exec("DELETE FROM test WHERE idx = ".$_REQUEST['delete'].";");
}
//SHOW CONTENTS OF BASE OR DELETE DB FILE
$result = $db->query('SELECT * FROM test');
while ($row = $result->fetchArray()) {
echo "<a href='test.php?delete=".$row['idx']."'>".$row['number']."</a></br>";
}
?>
Yes, you could do it like this but that would require to either execute the query again on the form's target page and then check for every combination of "delete".$row['email_adress'] or use a construction like this:
foreach ($_REQUEST as $key => $dummy)
if (substr($key,0,6) == 'delete')
delete_entry(substr($key,6));
However, if you simply swap value and name...
<input type=\"submit\" name=\"Delete\" value=\"".$row['email_adress']."\">
...you can just check $_REQUEST['Delete'] to find out which address button has been clicked.
... I'm still not sure about displaying peoples emails on web pages unless it's company internal.. I gather we are in a secure company back office?
I'd go for the:
<a href=my_page.php?delete_email_id=456>email</a>
probably with some annoying javascript for the confirm
email
and catch it with a
if(isset($_REQUEST['delete_email_id']){ SQL UPDATE ENTRY...}
at the top of my_page.php

Categories