Please point me in the right direction here Im trying to do the following:
Multiple select boxes are generated for each eventid
User choose who they think will win each event
The name of each selectBox is the event id assigned to variable $id
At end of while loop I want to extract the array $id value in For loop, however im getting error "undefined offset & invalid argument" on my for loop...
Here is my form
$i=0;//counter
while($row=mysql_fetch_array($result)){
$team1 = $row['team1'];
$team2 = $row['team2'];
$id[$i]= $row['event_id'];
echo'<h3>'.$team1.' VS '.$team2.'</h3>';
echo'<select name="'.$id[$i].'">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
$i++;
}//while
Here is my for loop giving error, I suspect problem is in the
$_POST['$id']...
if(isset($_POST['submit'])){
foreach($_POST[$id] as $eventId => $winner){
echo'<h3>'.$eventId.'</h3>';
}//for loop
}//end isset
Any help will be greatly appreciated
$id is defined as an array here$id[$i]= $row['event_id'];. Arrays can not be used as a key in a foreach array or otherwise.
This is what is causing you an error on this line
foreach($_POST[$id] as $eventId => $winner){ //$id is an array of values
echo'<h3>'.$eventId.'</h3>';
}//for loop
You have to make a second foreach statement for the $id then use the id values in your current foreach statement.
foreach( $id as $key => $val ) {
foreach( $_POST[$val] as $eventId => $winner){
You don't know what the event_id values are on the action page, so I think you'll have to query for those again something like:
if(isset($_POST['submit'])){
/* do your query here */
$data = array();
while($row=mysql_fetch_array($result)){
$data[] = $_POST[$row['event_id']];
}
foreach($data as $key => $value){
print_r($_POST[$value]);
echo "<br>";
}
}
Related
Here's my Query
$rows = $mydb->get_results("SELECT title, description
FROM site_info
WHERE site_id='$id';");
I get something like:
Title1 Desc1
Title2 Desc2
etc.
I want to put that data in array so I do:
$data = array();
foreach ($rows as $obj) {
$data['title'] = $obj->title;
$data['description'] = $obj->description;
}
When I do:
print_r($data);
I only get title and description of first item... Please help :/ I checked and my query returns all what i want to be in array not only the first row.
You are over-writing array indexes each time in iteration.You need to create new indexes each time when you are assigning the values to array.
So either do:-
$data = array();
foreach ($rows as $key=>$obj) { // either use coming rows index
$data[$key]['title'] = $obj->title;
$data[$key]['description'] = $obj->description;
}
Or
$data = array();
$i=0; //create your own counter for indexing
foreach ($rows as $key=>$obj) {
$data[$i]['title'] = $obj->title;
$data[$i]['description'] = $obj->description;
$i++;// increase the counter each time after assignment to create new index
}
For display again use foreach()
foreach ($data as $dat) {
echo $dat['title'];
echo $dat['description'];
}
If the eventual goal is simply to display these values, then you shouldn't bother with re-storing the data as a new multi-dimensional array.
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id='$id';");
If $id is user-supplied data or from an otherwise untrusted source, you should implement some form of sanitizing/checking as a matter of security. At a minimum, if the $id is expected to be an integer, cast it as an integer (an integer doesn't need to be quote-wrapped).
$rows = $mydb->get_results("SELECT title, description FROM site_info WHERE site_id = " . (int)$id);
When you want to display the object-type data, just loop through $rows and using -> syntax to echo the values.
echo "<ul>";
foreach ($rows as $obj) {
echo '<li>' , $obj->title , ' & ' , $obj->description , '</li>';
}
}
echo "</ul>";
If you have a compelling reason to keep a redundant / restructured copy of the resultset, then you can more simply command php to generate indexes for you.
foreach ($rows as $obj) {
$data[] = ['title' => $obj->title, 'id' => $obj->id];
}
The [] is just like calling array_push(). PHP will automatically assign numeric keys while pushing the associative array as a new subarray of $data.
I'm trying to update the fields on my database with the ff code:
<?php
session_start();
include ('../../class/connection.php');
$sql = "UPDATE reservationmenutable SET service = ? WHERE id = ?";
$statement = $conn->prepare($sql);
foreach ($_POST["hidden_id"] as $key => $db_id) {
foreach ($_POST["service_id"] as $key => $service_key) {
$statement->execute([$service_key, $db_id ]);
}
}
?>
the POST values are arrays so I had to loop them to get to them one by one right, but I'm confused on how to do it.
I'm trying to use the contents of hidden_id[] for the second loop. I thought about using a variable then increment it one by one but that would not match since each service has a corresponding id on database, ideas would appreciated. thanks :)
Just use the $key ot hidder_id as the index of service_id
hope it helps
$serviceKeys = array_keys($_POST["service_id"]);
foreach ($_POST["hidden_id"] as $key => $db_id) {
$statement->execute([$serviceKeys[$key], $db_id ]);
}
I have spent a lot of time trying to find ways to do the following, and have researched as much as I can but am still stuck.
I have a table 'pool_a' that at the minute has 2 columns - team_id and team_name.
I need to echo the id and the name into a nested foreach loop.
Now I can do this if I am just worried about the name, but now my query includes the ID too, I can't work out how to get both bits of data for each row in my table.
Here's how I get it to work with team_name...
for ($i=0;$i<$num;$i++) {
$team=mysql_result($result,$i,'team_name');
$team_names[$i] = $team;
echo $team . "<br>";
}
foreach ($team_names as $team) {
foreach ($team_names as $opposition) {
if ($team != $opposition) {
echo "<tr><td>" . $team . "<td><input type=\"text\"<td>versus<td><input type=\"text\">" . $opposition . "</tr>";
}
}
}
This is great, and outputs the correct fixture list and with input boxes for scores, but I need to add a hidden data input with team_id as the value. For example:
Here is what I have so far. Note that I have been learning about PDO's and new 5.5 techniques, so you will notice my style of code will be different in the next snippet.
require_once "pdo_enl_connect.php";
$database=dbNB_connect();
$query=$database->query ("SELECT team_id, team_name from pool_a");
while ($row = $query->fetch(PDO::FETCH_NUM)) {
printf ("%s %s<br>", $row[0], $row[1]);
$teams=array($row[0], $row[1]);
}
foreach ($teams as $key=>$value) {
echo "$key and $value<br>";
}
$database=NULL;
The output I get for the foreach loop is
0 and 5
1 and Silhouettes //silhouettes being the last team in the table.
ANy help would be much appreciated, and please let me know if I can edit my question to make it clearer in any way.
Thanks
Your while loop should look like this:
$teams = array();
while ($row = $query->fetch(PDO::FETCH_NUM)) {
// $row and array($row[0], $row[1]) are the same here
$teams[] = $row;
}
You need to initialize $team = array(); before your loop.
Then add your tuple to the teams array by doing either array_push($teams, array($row[0], $row[1])); or $teams []= array($row[0], $row[1]);`
Ok, I have this code
<?php //getting values
$column1 = $params->get('param1','');
$column2 = $params->get('param2','');
$column3 = $params->get('param3','');
$column4 = $params->get('param4','');
$column5 = $params->get('param5','');
//setting array and filter the empty values
$getvalues = array($column1,$column2,$column3,$column4,$column5);
$values = array_filter($getvalues); ?>
then I am using these values inside a foreach
<?php foreach ( $values as $key=>$value ) : ?>
<div><?php echo $value; ?></div>
<?php endforeach; ?>
It does the job, but after the loop, it adds the last item's value. Why?
After a foeach loop the used $key and $value variables are still alive and holds their last values so i think you are using the $value somewhere else in you code whithout rewriting it's value.
Call unset($value) and unset($key) after the loop and watch the PHP errors i think you will face some if the error reportnig is set to the most strict mode.
Say i am having set of rows in a table and each row is having a column called city with some values assigned to it
iam iterating through the result set and i need to assign the list of city values of each row in to an array only unique
foreach($res as $row){
$cities =array();
$cities[] = $row['city'];
//when i say
var_dump($cities);
//Iam not able to get array .how do i do that
$maincities = array('A','B',C)
}
You're resetting $cities to a new array for each row you loop through. Better would be:
$cities = array();
foreach ($res as $row)
{
if ( ! in_array($row['city'], $cities)) {
$cities[] = $row['city'];
}
}
You should but $cities =array();before the foreach loop. Now you are erasing the array at each iteration.
Regards,
Alin
You empty the $cities variable every time in the loop.
It is probably a lot better practise to only have unique cities in your resultset (SELECT DISTINCT city FROM ...)
For example:
$cities =array();
foreach($res as $row){
$cities[] = $row['city'];
}
var_dump($cities);
However it depends on the content of $res
Using keys to eliminate duplicates:
$cities = array();
foreach($res as $row)
$cities[$row['city']] = true;
$cities = array_keys($cities);