Translate array into HTML form then submit function - php

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!";
}
?>

Related

Update mysql data using php and form

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?

Mulitple event trigger different PHP file at the same form

I have this code:
echo "<form action='activity1.php' method='post'>";
echo "<input type='checkbox' name='checkbox_test[]' value='1'>aaa";
echo "<input type='checkbox' name='checkbox_test[]' value='2'>bbb";
echo "<input type='checkbox' name='checkbox_test[]' value='3'>ccc";
echo "<br><br>";
echo "<input type='submit' name='activity1' value='Activity1'>";
echo '</form>';
This will results 3 checkboxes and 1 summit button. The selection will be handled by acvitity1.php.
I would like to add another submit button for each checkbox line something like this:
echo "<form action='activity1.php' method='post'>";
echo "<input type='checkbox' name='checkbox_test[]' value='1'>aaa "."<input type='submit' name='activity2' value='Activity2'><br>";
echo "<input type='checkbox' name='checkbox_test[]' value='2'>bbb "."<input type='submit' name='activity2' value='Activity2'><br>";
echo "<input type='checkbox' name='checkbox_test[]' value='3'>ccc "."<input type='submit' name='activity2' value='Activity2'><br>";
echo "<br><br>";
echo "<input type='submit' name='activity1' value='Activity1'>";
echo '</form>';
If the user press the activity2 buttons, how can i pass the value another php file (for ex activity2.php) ?
So how can I put a form into another form ?
Think about a table / form where you can select any line for delete (activity1), and buttons for the end of each line to edit the table row where the button has pressed (activity2).
Thank you!
Post edit:
As I am unable to comment, I was unable to ask for clarification. You said:
Ammadu: after pressing activity2 buttons the page get (needs to be) redirected to another page (activiy2.php). At activity2.php i want to catch checkbox_test[] value with $_POST.
In that case, AFAIK, you can not explicitly redirect the request to activity2.php as form nesting is not allowed and "Activity2" submit buttons will always POST to activity1.php. The simplest thing you can do is check which submit button POST-ed the request and react acorrdingly (code for checking the POST variable is shown below in the pre-edit section).
Pre-edit:
Your questions seems a little bit unclear to me, but I'll try to answer it based on what you wrote at the end of the question:
Think about a table / form where you can select any line for delete (activity1), and buttons for the end of each line to edit the table row where the button has pressed (activity2).
Also, I am no professional, merely a student, and an amateur programmer.
I had a similar problem while attending web programming course at my college. Specifically, there were table rows with checkboxes at the end of the each row for deleting the rows and the "Edit" button next to each of them. There was a "Delete" button below the table that was used to call the script that would remove the rows that were marked for deletion. We were using some dirty, dirty hacks to make that work.
You asked about form nesting, quick Googling revealed that form nesting is not a valid code.
Unless you really need to do your tasks in a separate PHP script I would suggest checking the POST variable to see which button was used to POST the form data to the server:
<?php
if (isset($_POST['activity1'])) {
//code for activity1 button
}
elseif (isset($_POST['activity2'])) {
//code for activity2 buttons
}
?>
This approach is also causing another problem - there is no easy way to identify which row that button belongs to. What you can do is dynamically name the buttons in the process of creation for each row (activity2_1, activity2_2...) and then create a loop in the PHP script that would check which button was clicked, which is a very ineffective way of doing things. That was the dirty hack I used back when studying WP course.
What I would go for are simple anchors. You can create them inside a PHP loop like this:
<?php
//...rest of the code in the loop...
echo 'Edit';
//...rest of the code in the loop...
?>
The script activity2.php should then perform a simple GET check and do the rest of the job:
<?php
if (isset($_GET['rowID'])) {
//activity code
}
?>
If you really need to use the buttons:
You can style the anchors using CSS to look like and behave like buttons and then use the code shown above;
...or, if you are allowed, you can use simple JavaScript code that you can generate inside the PHP loop in the same manner, like this (out of my head) and then echo it:
<?php
//...rest of the code in the loop...
echo '<input type="button" onclick="location.href="/activity2.php?rowID=' . $your_row_id . '";" value="Edit" >';
//...rest of the code in the loop...
?>
Hope this helps.

I have a short html form with a php for loop which allows the user to build the same form up to ten times on the page

The $i variable is each field and is populated in the 'inp' boxes which are just input boxes and sboxes which are just select boxes. There is only one form when the page loads and it has all the criteria for a trainer to be added. The trainer name would be trainer_name1 on the first form. If they chose to hit the new button they could fill out the information for another trainer, the input box for the second form for 'name' would just be trainer_name2 and all the other fields are named respectively to what they are in the form. As new forms are built in just adds the next consecutive number onto the end of whatever the field might be named.
Here is my code:
<fieldset><legend>Trainer Request</legend></fieldset>
<tr><td><input type='button' onClick="if (show_item(1,10, 0)) { this.style.display = 'none'; }" value='New'></td></tr>
<?php
$contact_array = array('ACCEPTED TRAINING','DECLINED TRAINING','LEFT MESSAGE FOR TRAINING ACCEPTANCE',
'NEED TO CONTACT TO SEE IF INTERESTED',
'NEED PAPERWORK/TRAINING',
'NEED SIGNED CONTRACT AND PAPERWORK',
'NEED TO COMPLETE TRAINING');
for ($i = 10; $i > 0; $i=$i-1)
{
echo "<table id='hidden$i' style='display:none;'><tr>";
echo "<td>Date</td><td>Status</td></tr>";
echo "<tr><td>"; inp("date$i"); echo "</td><td>";
sbox("contact$i", $contact_array, 0, 'wide2');
echo "</td></tr>
<tr><td>Facility</td><td>";
inp("facility$i",50); echo "</td></tr>";
echo "<tr><td>Trainer Name</td><td>";
inp("trainer_name$i",35);
echo "<tr><td>Distance From</td><td>";
sbox("distance_from$i", array('1','2','5','10','15','20','25','30','40','50','60','70','80','90','100'));
echo "</td></tr>
<tr><td>Phone</td><td>";
inp("phone$i",13,'phone');
echo "</td><tr><tr><td>Email</td><td>";
inp("email$i",50);
echo "</tr><tr><td>Address 1</td><td>";
inp("addr1$i",50);
echo "</tr><tr><td>Address 2</td><td>";
inp("addr2$i",10);
echo " City ";
inp("city$i",20);
echo "</td></tr><tr><td>State</td><td>";
inp("state$i",2);
echo " Zip ";
inp("zip$i",'zip');
echo "</td></tr><tr><td>Notes</td><td>";
tbox("notes$i", 40, 3);
echo "</td></tr></table>";
}
?>
<script type='text/javascript'>
show_item(1,10,1);
</script>
As you can see down here I'm building a link which would name the link whatever the trainer name is, in this case trainer_name1 is Tim Jackson, so i've just built a hyperlink with his name.
<?php
// print_r ($_GET);
echo sendback_link($_GET['trainer_name1'], 'ACS/TrainerLookup', 'trainer_id=trainer_code&trainer_name=trainer_name');
?>
I'm confused on how to add a dynamic link like this into the for loop so as the form builds 1 - 10 each trainer_name2, trainer_name3, trainer_name4 etc etc. will have their names hyperlinked.
I'm thinking I create a new variable for the number 1-10 and append it onto the $_GET[trainer_name$].. something like that?
I hope that makes sense and any help would be greatly appreciated.
If I understood your question correctly, you are trying to add more content or replace content on a webpage that has already been generated with PHP.
I think what you are trying to do can be achieved using AJAX.
AJAX is a technique for creating dynamic webpages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
In your case, the process can be described in 3 steps:
the browser making a new request to your server (using javascript)
the server processes the request and sends some information back to the browser
the browser deals with that information (again using javascript) and then updates part of the webpage
There is an example here that shows how you can dynamically change the webpage contents.
Although, if you are allowed to, I would suggest that you use a javascript framework like jQuery which simplifies the whole process (google it for download and instructions on how to use).
You can read about using AJAX with jQuery here and reading the examples that follow to better understand how you can use it.
If you are going to try and use AJAX with jQuery or simply AJAX I suggest that you try it on a test page to get a simple working example, then adding a few things and checking to see if everything works as expected. When the test page is working as expected, import the code to your page.
This is how I would do it, there may be better or easier ways to do it.

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 do you post data with a link

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

Categories