i have had made a number of changes to the below program but am really stumped on my last task- i need a multiple attribute to pull multiple 'teams' data (points,goal difference etc) with php form. i can get single teams to work but not multiple. see screen attached and heres my code below.
![enter image description here][1]
<html>
<head>
<style>
.red {color: red}
</style>
<title>Table</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ){
$tablesPage = "http://www.bbc.com/sport/football/tables";
if(!empty($_POST["team"])){
$teamData= getTeamData($_POST["team"] , $tablesPage); //get associative array of team data
if(!empty($_POST["data"]) && $_POST["data"] == "results"){
echo getResults($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "position"){
echo getPosition($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){
echo getPoints($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){
echo getDifference($teamData);
}
}
}
function getPosition($teamData){
/*This function takes an array of team data and returns a string containing the name of the team and its position in the leauge */
return "Team ". $teamData["team"] ." are currently number " . $teamData["position"] . " in the league " ;
}
function getResults($teamData){
/*This function takes an array of team data and returns a string containing the results of the team */
return $teamData["team"] ." have won " . $teamData["won"] . " , drawn " . $teamData["drew"] . " , and lost " . $teamData["lost"] . " games to date " ;
}
function getPoints($teamData){
/*This function takes an array of team data and returns a string containing the points and calculates the old two points system */
$oldpoints = $teamData["won"] * 2 + $teamData["drew"];
return $teamData["team"] ." have " . $teamData["points"] . " points under the current system " . "<br> Under two points for a win they would have " . $oldpoints ;
}
function getDifference($teamData){
/*This function takes an array of team data and returns a string containing the name of the team and its goal difference in the leauge */
return $teamData["team"] ." goal difference is " . $teamData["difference"] . " at the moment " ;
}
function getTeamData($team, $tablesPage){
/* This function takes a webpage url and the name of a team as two string arguments. e.g. getTeam(""http://www.bbc.com/sport/football/tables", "liverpool")
It returns an array of data about the team.
You don't need to understand what this function does just that it returns an array which contains keya and values. The values map to the following keys:
"position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points"
*/
$html = new DOMDocument();
#$html->loadHtmlFile($tablesPage); //use DOM
#$xpath = new DOMXPath($html); //use XPath
$items = $xpath->query('//td/a[text()="' . $team . '"]/../..'); //get the relevant table row
$values[] = array();
foreach($items as $node){
foreach($node->childNodes as $child) {
if($child->nodeType == 1) array_push($values, $child->nodeValue); //KLUDGE
}
}
$values[2] = substr($values[2], -1); //KLUDGE
$values = array_slice( $values, 2, count($values)-4); //KLUDGE
$keys = array("position", "team", "played", "won", "drew", "lost", "for", "against", "difference", "points");
return array_combine($keys, $values);
}
?>
<br>
Select a team and a data item about that team
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<select name="team[]" multiple="multiple" size="3">
<option value=""></option>
<option value="Everton">Everton</option>
<option value="Arsenal">Arsenal</option>
<option value="Chelsea">Chelsea</option>
<option value="Man Utd">Man Utd</option>
<option value="Liverpool">Liverpool</option>
</select>
<select name="data">
<option value="position">position</option>
<option value="results">results</option>
<option value="two points for a win">two points for a win</option>
<option value="goal difference">goal difference</option>
<select>
<input type="submit" value="Get Data"></input>
</select>
</form>
</body>
</html>
Here is the code that you need to replace. I have left the 'debug' code in so you can see what is happening. just delete it when you are done.
Removed debug code.
Tested code: PHP 5.3.18 on windows xp.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" ){
$tablesPage = "http://www.bbc.com/sport/football/tables";
if(!empty($_POST["team"])){
// remember that the $_POST['team'] is an array of team names
foreach($_POST['team'] as $currentTeam) {
$teamData= getTeamData($currentTeam , $tablesPage); //get associative array of team data
if(!empty($_POST["data"]) && $_POST["data"] == "results"){
echo getResults($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "position"){
echo getPosition($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "two points for a win"){
echo getPoints($teamData);
} else if(!empty($_POST["data"]) && $_POST["data"] == "goal difference"){
echo getDifference($teamData);
}
echo '<br />';
} // end currentTeam
}
}
Related
How can I retrieve selected value after form submision inside looped HTML select? I managed to solve the problem with manual if statements, but thats not dynamic.
I'm also storing previously submited value inside a cookie. I use self page form submit.
I managed to retrieve previous value from radio button:
<input type="radio" name="spol" value="moški" checked="checked" <?php if (isset($_POST['spol']) && $_POST['spol'] == 'moški') {
echo ' checked="checked"';
} ?>>
But can't find a way to do this inside foreach loop
<!---Cookie "keks" is storing previous submited string-->
<select name="status">
<?php
$_COOKIE['keks'];
$statusi = ["Dijak", "Študent", "Zaposlen", "Brezposelni"];
$counter= 0;
foreach ($statusi as $status) {
$counter++;
if ($counter == 2) {
echo "<option value=" . $status . " selected>" . $status . "</option>";
} else {
echo "<option value=" . $status . ">" . $status . "</option>";
}
}
?>
</select>
As stated in html comment, $_COOKIE['keks']; is storing the last value.
You might want to store that value into a variable or use it as is. and then, compare it against the current iteration of your loop.
$lastValue = $_COOKIE['keks'];
// some code
foreach ($statusi as $status)
{
if ($status == $lastValue)
// mark the option as selected
else
// don't mark it
}
I have a little problem here. I have a list, which is:
<form action="display.php" method="post">
<select name="holiday">
<option value="month">Kiekvieno mėnesio skaičiavimas</option>
<option value="day">Kiekvienos dienos skaičiavimas</option>
</select>
<br> <br>
<input type="submit" name="select" value="Pasirinkti" />
</form>
What I need to do is that when the user selects value ="month", php code would do one action, and when the user selects value ="day", php code would do another action?
My php code looks like this:
<?php
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
}
else if ($selectedValue == $_POST['month']) {
$todaysDate = new DateTime();
while ($employee = $select->fetch()){
$employmentDateValue = new DateTime($employee['employment_date']);
// Comparing employment date with today's date
$differenceBetweenDates = date_diff($employmentDateValue, $todaysDate);
$workMonths = $differenceBetweenDates->y * 12 + $differenceBetweenDates->m;
$holidayDays = $workMonths *4;
echo "<tr>";
echo "<td>".$employee['name']."</td>";
echo "<td>".$employee['surname']."</td>";
echo "<td>".$employee['employment_date']."</td>";
echo "<td>".$workMonths."</td>";
echo "<td>".$holidayDays."</td>";
echo "</tr>";
}
}
else {
echo "Lalalala";
}
?>
I've tried to do so with $_POST['select'], but it doesn't work. Thanks for any help guys
<?php
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
if ($selectedValue == 'month') {
}
else if ($selectedValue == 'day') {
}
else{
echo "Lalalala";
}
}
?>
You need to do $_POST['holiday'], so change:
if($_POST['select']){
// Storing selected value in a variable
$selectedValue= $_POST['holiday'];
}
to
if($_POST['holiday']){
// Storing selected value in a variable
$selectedValue = $_POST['holiday'];
}
You also need to change the line:
else if ($selectedValue == $_POST['month']) {
So it's not part of the original if statement:
if ($selectedValue == 'month') {
// your code
}
else {
echo "Lalalala";
}
First of all, sorry if this is worded poorly, as I'm a beginner at code.
I'm currently working on an online computer science course, however I'm quite confused on how to do one small part. We need to use arrays for this activity, where the user has multiple selections and each different selection has a different/unique text output. Everything works fine, except I need an option to choose a random selection, however I'm a bit confused on how to make it. You can see from my code the options 1-8. I want it to randomly select one of the selections.
Here's my code:
<?php
$train[0] = "Canada";
$train[1] = "Sahara Desert";
$train[2] = "Russia";
$train[3] = "Chernobyl";
$train[4] = "United States";
$train[5] = "North Korea";
$train[6] = "Germany";
$train[7] = "Hawaii";
?>
<!DOCTYPE html>
<html>
<head>
Took out everything here, it's not important.
</head>
<body>
<center>
<h1>Vacation Time!</h1>
<h4>You and your family just won the lottery! You all want to go on vacation, but nobody can agree where to go. Inside each train cart has a card with a location written on it. Whatever you find is where you're going! </h4>
<form name="form1" action="activity-2-7-arrays-a.php" method="post">
<label>Which cart on the train do you want to choose?</label>
<br>
<select name="cart" required>
<option value="1">First Cart</option>
<option value="2">Second Cart</option>
<option value="3">Third Cart</option>
<option value="4">Fourth Cart</option>
<option value="5">Fifth Cart</option>
<option value="6">Sixth Cart</option>
<option value="7">Seventh Cart</option>
<option value="8">Eight Cart</option>
<option value="show">Show all options</option>
<option value="any">Choose Randomly</option>
<br>
</select><br/>
<input type="submit" name="subButton" class="subButton" value="Go!"/><br/>
</form>
<h1><u>Final Results</u></h1>
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
$roll = rand(1,9);
if($cart == show) {
for($x = 1; $x <= 9; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
}
return;
}
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
return;
if ($cart == $roll) {
}
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll] . "! Have fun! </h2>";
?>
I'm sure it's a bit messy, also. Hopefully you understand what I mean. If you're able to explain the answer to me that would be extremely helpful. Thank you :)
You are randomly generating a value regardless of the user choice and comparing it with user's selection and other weird things.
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
$roll = rand(1,9);
You are generating a random value before even checking if user selected 'Choose randomly' and why generate a random between 1 and 9? Your $train array starts with index 0 and ends with index 7.
if($cart == show) {
String needs to be quoted.
for($x = 1; $x <= 9; $x++) {
Again looping $x from 1 to 9 makes no sense because of your array indexes.
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
Will fail when $x reaches 8 since last index in $train is 7.
}
return;
}
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
return;
So if user didn't select 'Show all options' you show him his chosen location. If user chose 'Select Randomly' this will fail since $cart would have value 'any' and $train['any'] does not exist.
Here is code with correct logic.
<?php
if($_POST['subButton']) {
$cart = $_POST['cart'];
if ($cart == 'any') {// Check if user selected 'Choose Randomly'
$roll = rand(0, 7);
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll] . "! Have fun! </h2>";
}
else {
if ($cart == 'show') { // If user selected 'Show all options'
echo "<p> You could have ender up in... </p>";
for($x = 0; $x <= 7; $x++) {
echo "<h2> " . $train[$x] . "</h2>";
}
}
else { // User selected cart so show him chosen location
echo "<h2>"."Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
}
}
?>
Here is some problems in the code
from where and why we return?
no closing html-tags
I would change the last part of php-code like that:
<?php
if ($_POST['subButton']) {
$cart = $_POST['cart'];
$value = intval($cart);
$roll = mt_rand(1, 8); // mt_rand() has more entropy than rand()
if ($cart == 'show') {
// show target locations (according the OP-source)
for($x = 1; $x <= 8; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x-1] . "</h2>";
}
} else if ($value > 0 && $value <= 8) {
echo "<h2>"."Well, it looks like you're going to " . $train[$value-1] . "! Have fun! </h2>";
// idk why it needed, but move it here
if ($value == $roll) {
}
} else if ($cart == 'any') {
echo "<h2>"."Can't handle the pressure? You were selected to go to " . $train[$roll-1] . "! Have fun! </h2>";
} else {
// $_POST['cart'] has something wrong
}
}
?>
<!-- lines below was added to close html-tags -->
</body>
</html>
What you're looking for is array_rand():
$random = array_rand($train);
Instead of rand() use mt_rand() because the PHP DOCUMENTATION literally says
mt_rand — Generate a better random value
Regarding your php code, you have a lot of errors. This is how your bottom php code should look:
<?php
if($_POST['subButton'])
{
$cart = $_POST['cart'];
$roll = mt_rand(0,7);
//0-7 because those are the values you inserted into
//the $train[] array
if($cart == 'show') {
//another correction here, it has to be 0-7
for($x = 0; $x <= 7; $x++) {
echo "<p> You could have ender up in... </p>";
echo "<h2> " . $train[$x] . "</h2>";
}
}
else if ($cart!='any')
{
"<h2>Well, it looks like you're going to " . $train[$cart] . "! Have fun! </h2>";
}
else //took out return and placed an else
{
echo "<h2>Well, it looks like you're going
to " . $train[$cart] . "! Have fun! </h2>";
}
?>
I have a order form with inputs like this:
<input type="text" name="booking[Sandwich][Roastbeef][qty]" />
<input type="text" name="booking[Sandwich][Cheese][qty]" />
<input type="text" name="booking[Pizza][Classic][qty]" />
<input type="text" name="booking[Pizza][Special][qty]" />
<input type="text" name="booking[Coffee][qty]" />
I'm having trouble looping through the arrays correctly.
Here is what kind of output I would like to have:
<h2>Sandwich</h2>
<p><strong>Roastbeef:</strong> 10</p>
<p><strong>Cheese:</strong> 5</p>
<hr>
<h2>Coffee</h2>
<p><strong>Quantity:</strong> 15</p>
If all the pizza input is empty, the heading "Pizza" should not be printed! The same with the "coffee" or "Sandwich" group. If the order does not contain anything in the group, the heading should not be printed.
I can't write specific tests for every input, as I have 200 of them.
Here is what I have tried to do:
$booking = $_POST['booking'];
//First check if there is one or more input that is not empty
if (!empty($booking)) {
foreach ($booking as $type => $items) {
if (count(array_filter($items))) {
$order .= "<hr>\n<h2>" . ucfirst($type) . ":</h2>\n";
}
foreach ($items as $name => $qty) {
if ($qty > "0"){
$order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qty . "</p>\n";
}
}
}
}
This code only works when the array has a length of two keys. I can't seem to wrap my brain around as how to deal with other lengths. Any help would be great!
Edit:
With the answer from #treegarden, I have almost what I need. Now I just need to have some sort of check if the "group" is empty, then the <h2> should not be printed. if (count(array_filter($entry))) works in not printing any thing if the group is empty, but just for those input that only have two keys.
if (!empty($booking)) {
foreach($booking as $key=>$entry) {
if (count(array_filter($entry))) {
echo "<h2>$key</h2>"; //Should only be printed if one or more inputs in the group are not empty
foreach($entry as $key=>$subEntry) {
if(is_array($subEntry) && $subEntry['qty'] > 0) {
echo "<p><strong>$key:</strong>" . $subEntry['qty'] . "</p>";
} elseif(!is_array($subEntry) && $subEntry > 0) {
echo "<p><strong>Quantity:</strong> $subEntry</p>";
}
}
echo '<hr/>';
}
}
}
Maybe try recursion, from example snippet:
<?php
class RecursiveArrayOnlyIterator extends RecursiveArrayIterator {
public function hasChildren() {
return is_array($this->current());
}
}
?>
else a simple forward way is to assume you have three or more nested loops,
keep checking is $value in $kv using is_array(), which is done by invoking a function.
Try this
$booking = $_POST['booking'];
if (!empty($booking)) {
foreach ($booking as $type => $items) {
if (count(array_filter($items))) {
$order .= "<hr>\n<h2>" . ucfirst($type) . ":</h2>\n";
}
foreach ($items as $name => $qty) {
if (is_array($qty)) {
foreach ($qty as $qt) {
if ($qty > "0"){
$order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qt. "</p>\n";
}
}
} else {
if ($qty > "0"){
$order .= "<p><strong>" . ucfirst($name) . ":</strong> " . $qty . "</p>\n";
}
}
}
}
}
Okay so I am developing a search engine for a non-profit group using MYSQL and PHP. The data appears fine from all the other fields. But when I try to get data from a drop down select box the data doesn't appear.
I know my code is pron to SQL injections however there isn't any important data kept on the server, it just info about treatments and research studies.
I would like to do it with a function. I was also wondering if there is anyway to retrieve data from multiple boxes. Like I have a keyword search and a drop down combo box both of them are set. How do I retrieve data from both columns in the database using the function I have? Thanks
Here is my code if you guys could help me that would be great thanks
The code for the html box
Broad Research Topic <select name="Treatment1">
<option value="Other">
Other
</option>
<option value="Treatment">
Treatment
</option>
<option value="PracticalCure">
Practical Cure
</option>
The php code to check if it is set
if (isset($_GET['Treatment1']) && in_array($_GET(['Treatment1']),
array('Treatment', 'PracticalCure', 'Other')) {
$state = $_GET['Treatment1'];
Investigator6($state); }
}
The Function Investigator6
function Investigator6($state)
{
$state = trim($state);
$state = preg_replace('/\s+/', ' ', $state);
//seperate multiple keywords into array space delimited
$keywords = explode(" ", $state);
//Clean empty arrays so they don't get every row as result
$keywords = array_diff($keywords, array(
""
));
//Set the MySQL query
if ($state == NULL or $state == '%') {
} else {
for ($i = 0; $i < count($keywords); $i++) {
$query = ("SELECT * FROM Studies1 WHERE BroadResearchTopic LIKE
' %$keywords[$i]%'");
}
//Store the results in a variable or die if query fails
$result = mysql_query($query) or die(mysql_error());
}
if ($state == NULL or $state == '%') {
} else {
//Count the rows retrived
$count = mysql_num_rows($result);
echo $count;
}
//If search variable is null do nothing, else print it.
if ($state == NULL) {
} else {
echo "You searched for <b><FONT COLOR=\"blue\">";
foreach ($keywords as $value) {
print "$value ";
}
echo "</font></b>";
}
echo "<p> </p><br />";
echo "</center>";
//If users doesn't enter anything into search box tell them to.
if ($state == NULL) {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
b</font></b><br /></center>";
} elseif ($state == '%') {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
</font></b><br /></center>";
//If no results are returned print it
} elseif ($count <= 0) {
echo "<center><b><FONT COLOR=\"red\">Your query returned no results from the
database.</font></b><br /></center>";
//ELSE print the data in a table
} else {
//Table header
echo "<center>";
echo "</center>";
//Colors for alternation of row color on results table
$color1 = "#d5d5d5";
$color2 = "#e5e5e5";
//While there are rows, print it.
while ($row = mysql_fetch_array($result)) {
//Row color alternates for each row
$row_color = ($row_count % 2) ? $color1 : $color2;
//table background color = row_color variable
echo "<td style = \"padding: 10px\">" . $row['BroadResearchTopic'] . "</td>";
$row_count++;
if ($state == NULL or $state == '%') {
} else {
//clear memory
mysql_free_result($result);
}
}