php and mysql function snowballing results - php

Im using the following function.
function GetSubmissions($coach){
$result = mysql_query("SELECT * FROM `ptable` WHERE coach = '$_SESSION[username]'") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$teampre = $row['team'];
$eventpre = $row['event'];
$statuspre = $row['status'];
$eventarray = DecodeEvent($eventpre);
$event = $eventarray[0];
$cat = $eventarray[1];
$subcat = $eventarray[2];
$division = $eventarray[3];
$type = $eventarray[4];
$teamarray = DecodeTeam($teampre);
foreach ($teamarray AS $key => $value){
$teamgo .= $value[1]." ".$value[2]."<br/>";
}
$push .= "<div id=submission><div id=event>$event</div><div id=status>$statuspre</div><div id=subinfo>$cat $subcat $division $type</div><div id=team>$teamgo</div></div>";
}
return $push;
}
What is happening, is that the $teampre contains a series of numbers representing the team members, which i pass to the DecodeTeam function to return the names of the given members in an array. The problem is. That say there are 3 results for the main query. The first is fine. The second result starts off with the team members from the first result. The third result starts off with the team members from the first and second queries, like a snowball effect.
I figure the problem is in the way im handling the $teamgo variable, but im not sure how to get the results to stop snowballing like this.

Looks like you just need to reset the $teamgo string each time you go through the loop:
$teamarray = DecodeTeam($teampre);
$teamgo = ""; // Reset so it doesn't contain the results from the last row.
foreach ($teamarray AS $key => $value){
$teamgo .= $value[1]." ".$value[2]."<br/>";
}

I was beat to the bunch but I beautified your code =)
function GetSubmissions($coach) {
$result = mysql_query("SELECT * FROM `ptable` WHERE coach = '$_SESSION[username]'");
while ($row = mysql_fetch_array($result)) {
// stripslashes
foreach($row AS $key => $value) {
$row[$key] = stripslashes($value);
}
$id = $row['id'];
$teampre = $row['team'];
$eventpre = $row['event'];
$statuspre = $row['status'];
$eventarray = DecodeEvent($eventpre);
$event = $eventarray[0];
$cat = $eventarray[1];
$subcat = $eventarray[2];
$division = $eventarray[3];
$type = $eventarray[4];
$teamarray = DecodeTeam($teampre);
$teamgo = '';
foreach ($teamarray AS $key => $value) {
$teamgo .= $value[1]." ".$value[2]."<br/>";
}
$push .= "blah blah blah";
}
return $push;
}

Related

Data in nested foreach loops used in update query

This is my code:
session_start();
/* loops through each row in the global $_SESSION variable which
contains the array and uses the $value to GET the data in the text
boxes and output them */
// studevent_result =
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
echo $studResult;
echo "<br>";
}
// result_postion =
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition = $_GET[$value];
echo $studPosition;
echo "<br>";
}
echo "<br>";
// stud_id =
foreach ($_SESSION['arrayId'] as $value) {
echo $value;
echo "<br>";
}
// UPDATE query, this will update the studevent_result and result_position
// column in the database for the specific stud_id.
$updateQuery = "
UPDATE result
SET studevent_result = '00:20:33',
result_position = '6'
WHERE result.stud_id = '12'
";
$updateRow = mysqli_query($conn, $updateQuery);
I use $_SESSION variables which all store an array. I extract the results of these arrays using foreach loops.
In $updateQuery, I want to make studevent_result = to the results of my first foreach loop above, result_position = to the results of the second foreach loop above and the result.stud_id = to the results of the third foreach loop above.
After me editing the code my code now looks like this:
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
foreach ($_SESSION['arrayNamePosition'] as $data) {
$studPosition = $_GET[$data];
foreach ($_SESSION['arrayId'] as $idValue) {
echo $idValue;
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult',
result_position = '$studPosition'
WHERE result.stud_id = '$idValue'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
}
}
I nested the foreach loops. But the problem now is that for the last foreach loop in the nested loops, $idValue in the query only uses the last element in the array $_SESSION['arrayId']. How can I fix this to loop throught the whole array, so that the query uses all the values in the array?
Thanks in advance.
If I understood your issue this should help you
session_start();
$i = 0;
$studResult = array();
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult[$i] = $_GET[$value];
$i++;
}
$studPosition= array();
$i=0;
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
}
$stud_id = array(); $i=0;
foreach ($_SESSION['arrayId'] as $value) {
$stud_id[$i] = $value; $i++;
}
for($j =0; $j<$i; $j++){
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult[$j]',
result_position = '$studPosition[$j]'
WHERE result.stud_id = '$stud_id[$j]'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
Hope it will be helpful. Happy coding :)

how to store associative array php MySQL

I want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on
$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.
There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}

PHP better solution than for each loop

I have this timetable where a first loop a bunch of members from the database with and while-loop. Inside the while-loop I have an foreach-loop. How ever, the foreach-loops makes the whole timetable very slow, and I need an different approach to this problem.
What it looks like now.
$sql = mysql_query("SELECT * FROM tblstaff ORDER BY strName ASC");
while($row = mysql_fetch_array($sql))
{
$user_id = $row['intId'];
$arr = array($one, $two, $three, $four, $five, $six, $seven);
foreach ($arr as $w) {
$week = $w;
$sql_offtime = mysql_query("SELECT tbloffwork.intId, tbloffwork.intWhoId, tbloffwork.strWeek
FROM tblstaff, tbloffwork
WHERE tbloffwork.intWhoId = '$user_id' AND tbloffwork.strWeek = '$week'");
$rwOff = mysql_fetch_array($sql_offtime);
$sql_work = mysql_query("SELECT DISTINCT tblstaff.intId as staffId, tblstaff.strName, tblworktable.intId, tblworktable.intWhoId, tblworktable.strElapsed, tblworktable.strNotes
FROM tblstaff, tblworktable
WHERE tblworktable.intWhoId = '$user_id' AND tblworktable.strElapsed = '$week'");
$rw_work = mysql_fetch_array($sql_work);
if($rwOff['strWeek'] == $week) {
$td_stat = "timetable-td-background-yellow";
} elseif($rw_work['strElapsed'] != "") {
$td_stat = "timetable-td-background-green";
} else {
$td_week = "timetable-td-background-red";
}
if($rw_work['strNotes'] != ""){
$notes = "<i class='fa fa-pencil-square-o mediumsmall'></i>";
} else { $notes = $null; }
echo "<td align='right' valign='top' id='timetable-td-small-square' class='". $td_week ."''>". $notes ."</td>";
}
}
Is there a better way to approach this instead of going with the foreach method?
foreach makes a copy of the set, you can use while instead
while (list($key, $value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
http://php.net/manual/en/control-structures.foreach.php

PHP duplicate output

I have a while loop fetching a row and I'm trying to create a structure so that each row will create 2 links. The first is a German word and the second being an English one. The output I'm getting is repeated as if the row isn't being incremented. I've narrowed it down to this:
PHP:
while ($row = $database->row()->fetch()) {
foreach ($row as $value) {
$this->data .= $value . "!";
}
list($this->pid, $this->german, $this->english) = explode("!", $this->data);
$this->links .= "$this->german<br/>$this->english<br/>";
}
Output:
die Männer
men
die Männer
men
$row = array();
while ($row = $database->row()->fetch()) {
$row[] = $row;
}
foreach ($row as $value)
{
$this->data .= $value . "!";
list($this->pid, $this->german, $this->english) = explode("!", $this->data);
$this->links .= "$this->german<br/>$this->english<br/>";
}
I've solved the problem by looking at the keys and creating variables based on a simple matched string test. If anyone can improve my answer I would like to hear it. Thanks.
PHP:
while ($row = $database->row()->fetch()) {
while(list($key, $value) = each($row)) {
if ($key == "PID") {
$this->pid = $value;
}
if ($key == "german") {
$this->german = $value;
}
if ($key == "english") {
$this->english = $value;
}
}
$this->links .= "$this->german<br/>$this->english<br/>";
}

php function to return SQL results

This is what i have
function GetEventsList(){
$result = mysql_query("SELECT * FROM `events`") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$en = $row['name'];
$endt = $row['date'];
$push = "<option value=$id>$en - $endt</option>";
return $push;
}
}
Its only returning 1 result, when there are 3 in the table
That's because you're returning from the function at the end of the first iteration. Try:
function GetEventsList() {
$result = mysql_query("SELECT * FROM `events`") or trigger_error(mysql_error());
$push = '';
while ($row = mysql_fetch_array($result)) {
foreach($row AS $key => $value) {
$row[$key] = stripslashes($value);
}
$id = $row['id'];
$en = $row['name'];
$endt = $row['date'];
$push .= "<option value=$id>$en - $endt</option>";
}
return $push;
}
On a side note: if you used good formatting/indenting that would've been far easier for you to spot.
Also, are you sure you need to use stripslashes()?
If I'm reading the code correctly, return $push; is exiting the while loop prematurely. You want to return only after all results are gathered and stored in something.
Either use echo $push in your foreach loop; or put each iteration of the option element into an array, then insert the array as needed.

Categories