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
Related
I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.
You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';
First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}
Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}
I'm trying to fetch arrays from two queries. The result only gets the first index.
while(($row2 = mysql_fetch_array($query1)) && ($index = mysql_fetch_array($query2)))
{
$leaveID = $row2['leaveID'];
$personID = $index['personID'];
$Person_Type = $index['Person_Type'];
if ($Person_Type == 'Regular')
{
$Sick_Remaining_Days = 10 - $Sick_Total_Days;
}else{
$Sick_Remaining_Days = 5 - $Sick_Total_Days;
}
echo "<tr>";
echo ($leaveID == $personID) ? "<td>$Sick_Remaining_Days</td>" : "<td>--</td>";
echo "</tr>";
}
Assuming both queries are OK I offer two ways to loop through them depending on your needs. Hopefully one of them will help.
<?php
$arrayRowA = array();
$arrayRowB = array();
while($row = mysql_fetch_array($query1)){$arrayRowA[] = $row;}
while($row = mysql_fetch_array($query2)){$arrayRowB[] = $row;}
// Loop through two arrays in a square way (every combination of both arrays)
foreach($arrayRowA as $keyA => $objectA){
foreach($arrayRowB as $keyB => $objectB){
$leaveID = $objectA['leaveID'];
$personID = $objectB['personID'];
$Person_Type = $objectB['Person_Type'];
if($Person_Type == 'Regular')
{
$Sick_Remaining_Days = 10 - $Sick_Total_Days;
}else{
$Sick_Remaining_Days = 5 - $Sick_Total_Days;
}
echo "<tr>";
echo ($leaveID == $personID) ? "<td>$Sick_Remaining_Days</td>" : "<td>--</td>";
echo "</tr>";
}
}
// Loop through two arrays in a linear way (one to one)
foreach($arrayRowA as $keyA => $objectA){
if(isset($arrayRowB[$keyA])){
$objectB = $arrayRowB[$keyA];
$leaveID = $objectA['leaveID'];
$personID = $objectB['personID'];
$Person_Type = $objectB['Person_Type'];
if($Person_Type == 'Regular')
{
$Sick_Remaining_Days = 10 - $Sick_Total_Days;
}else{
$Sick_Remaining_Days = 5 - $Sick_Total_Days;
}
echo "<tr>";
echo ($leaveID == $personID) ? "<td>$Sick_Remaining_Days</td>" : "<td>--</td>";
echo "</tr>";
}
}
?>
$query = mysql_query("select p*, l* from person as p left join leave as l on p.personID = l.leaveID");
while(($row = mysql_fetch_array($query)))
{
$Person_Type = $row['Person_Type'];
if ($Person_Type == 'Regular')
{
$Sick_Remaining_Days = 10 - $Sick_Total_Days;
}else{
$Sick_Remaining_Days = 5 - $Sick_Total_Days;
}
echo "<tr>";
echo "<td>$Sick_Remaining_Days</td>";
echo "</tr>";
}
You should get array before while:
array f,s
while(first)
{
f = ...;
}
while(second)
{
s = ...;
}
And now use both array.
Or try use new http://php.net/manual/en/mysqli-result.fetch-array.php. Probably you losing connection to first query after use second query.
while($row = mysqli_fetch_assoc($result))
{
$row2 = mysqli_fetch_assoc($result2);
echo $row['id'];
echo $row2['id'];
/* your code */
} `
Use this... It is what do you search !
while($row2 = mysql_fetch_array($query1))
{
$index = mysql_fetch_array($query2);
echo $row['id'];
echo $index['id'];
/* add code */
}
I sorted a list alphabetically and data from database mysql.To read the data i am using foreach loop.Now,I want when first letter (a->b->c) will change a seperator will be add after 'A' character list and so on.
Code:
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
foreach($result as $val){
echo $val['name']."<br>"; echo "<hr></hr>";
}
Thanks in advance
<?php
$first = '';
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
foreach($result as $val){
$first = substr($val['name'], 0, 1);
if ($first != $prev){
echo '<h1>'.$first.'</h1>';
}
echo $val['name']."<br>";
$prev = $first;
}
Try this:
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
$lastChar = "?"; //initialization
foreach($result as $val){
if($lastChar != $val['name'][0]){
echo $val['name'][0].'<BR>'; //separator
}
echo $val['name']."<br>"; echo "<hr></hr>";
$lastChar = $val['name'][0]; //update
}
Try this (untested code) :
$firstLetter = 'A';
foreach( $result as $val ) {
$ch = substr( $val['name'],1,1);
if( $ch != $firstLetter ) {
echo "<hr>";
$firstLetter = $ch;
}
echo $val['name']."<br>";
}
$char = 'a';
foreach($result as $val) {
$newChar = substr($val['name'],0,1);
if ($newChar != $char) {
$char = $newChar;
echo "seperator for new character";
}
//do your other stuff
}
Is this what you were wanting to do?
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.
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;
}