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.
Related
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?
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.
I am trying to write a wordpress plugin and I have hit a bump. I am new to PHP (coded in Java before) and javascript so I am not sure whats the best way to solve my problem.
The Background
I have some data in a mySQL DB that I am using (each row has a unique ID and some other information I have added). I am able to search the DB using
$headss = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}costumesdb WHERE location = 'head'", ARRAY_A);
And display some of the information to the user using (this is one of 5 different drop-downs but they are all created in the same way)
Head: <select name="head">
<?php foreach ($heads as $head) { ?>
<option value="<?php echo $head['pieceName'] ?>"><?php echo $head['shopName'] . " - " . $head['pieceName'] ?></option>
<?php } ?>
</select>
For the moment I want the user to be restricted to choosing information that is already in the system.
The problem
The DB contains 2 pieces of information that the user does not need to know to fill in the form (a website URL and a picture URL). I need these 2 pieces of information once the form is submitted (I need to write some more code for that) to the server which spits out another page with the 2 URL's in it.
Whats the best way to send the data back to a PHP script? Am I able to access the row of data that the user has selected in the drop down and send the unique ID for that row back or do I need to do something else?
Edit:
This is the script that I am using to submit the code:
$('#createacostume').form({
success:function(data){
$.messager.alert('Info', data, 'info');
}
});
'
And then the page to display the information returned is:
$cname = $_POST['cname'];
$head = $_POST['head'];
echo "Data Returned Name $cname head $head
I think this is what you are asking:
User has to choose an item from a drop down and submit a form. You have to display the website URL and the image for that item in a second page. You want to know how this is typically accomplished.
If that's the case, you should pass the row id of the item to the second page like so:
<option value="<?php echo $head['ROW_ID'] ?>"><?php echo $head['shopName'] . " - " . $head['pieceName'] ?></option>
Then use the ROW_ID in the second page to access the data from the database and print out the website URL and the image.
Submit the first form (without the two field), INSERT the data into the database, get the ID of insert.
Pass the ID to the next page which would set the ID into a hidden form field (or GET or POST parameter, plenty of choices) of the new form (with the two fields and just UPDATE the database upon submitting the second form.
If you like to show the original data in the second form, just pull the data from the database and use it to render the form instead of passing just the ID into a hidden field.
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
I have a database which holds the residents of each house in a certain street. I have a 'house view' php web page which can display an individual house and residents when given the house number using 'post'. I also have a 'street view' web page which gives a list of houses. What I want to know is if you can have links on the street view which will link to the house view and post the house number at the same time without setting up a form for each?
Regards
If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:
function formSubmit(house_number)
{
document.forms[0].house_number.value = house_number;
document.forms[0].submit();
}
Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:
<form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">
<?php
foreach ($houses as $id => name)
{
echo "$name\n";
}
?>
</form>
That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavaScript submits the form.
I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:
<a href="house.php?id=<?php echo $house_id;?>">
<?php echo $house_name;?>
</a>
Then in house.php, you would get the house id using $_GET['id'], validate it using is_numeric() and then display its info.
You cannot make POST HTTP Requests by some_script
Just open your house.php, find in it where you have $house = $_POST['houseVar'] and change it to:
isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']
And in the streeview.php make links like that:
Or something else. I just don't know your files and what inside it.
This is an old thread but just in case anyone does come across i think the most direct solution is to use CSS to make a traditional form look like an anchor-link.
#ben is correct you can use php and javascript to send a post with a link, but lets ask what the js does -- essentially it creates a form with style='display:none' sets an input/text line with value='something' and then submits it.
however you can skip all this by making a form. setting style='display:none' on the input/text lines (not the form itself as above) and then using CSS to make the button look like a normal link.
here is an example is i use:
in PHP Class,
public function styleButton($style,$text){
$html_str = "<form id='view_form' action='".$_SERVER['REQUEST_URI']."' method='post' >";
$html_str .= "<input style='display:none;' name='list_style' type='text' value='".$style."' >";
$html_str .= "<input id='view_button' type='submit' value='".$text."' >";
$html_str .= "</form>";
return $html_str;
}
Then in the CSS id="view_form" set "display:inline;"
and in the CSS id="view_button" set to something like: "background:none;border:none;color:#fff;cursor:pointer"
I would just use a value in the querystring to pass the required information to the next page.
We should make everything easier for everyone because you can simply combine JS to PHP
Combining PHP and JS is pretty easy.
$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = $house_number; document.forms[0].submit();</script>";
Or a somewhat safer way
$house_number = HOUSE_NUMBER;
echo "<script type='text/javascript'>document.forms[0].house_number.value = " . $house_number . "; document.forms[0].submit();</script>";
This post was helpful for my project hence I thought of sharing my experience as well.
The essential thing to note is that the POST request is possible only with a form.
I had a similar requirement as I was trying to render a page with ejs. I needed to render a navigation with a list of items that would essentially be hyperlinks and when user selects any one of them, the server responds with appropriate information.
so I basically created each of the navigation items as a form using a loop as follows:
<ul>
begin loop...
<li>
<form action="/" method="post">
<input type="hidden" name="country" value="India"/>
<button type="submit" name="button">India</button>
</form>
</li>
end loop.
</ul>
what it did is to create a form with hidden input with a value assigned same as the text on the button.
So the end user will see only text from the button and when clicked, will send a post request to the server.
Note that the value parameter of the input box and the Button text are exactly same and were values passed using ejs that I have not shown in this example above to keep the code simple.
here is a screen shot of the navigation...
enter image description here