So, let’s say I have 10 rows in my database. However, after the mysql query, only 9 rows are being displayed in the html table.
I need every row from the database to be displayed in the html table.
I hope someone can point me in the right direction. I’ll be here if I need to provide anymore details.
This is my code:
<?php
$sqlQuery = "SELECT * FROM periods";
$result = mysqli_query($conn, $sqlQuery);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$out = $row['fell_out'];
$in = $row['fell_in'];
$sum = $row['sum'];
$nextEstimate = $row['next_estimate'];
$nextEstimateDays = $row['next_estimate_days'];
$notes = $row['notes'];
$sqlQueryLastDate = "SELECT * FROM (select * from periods WHERE id < $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
$resultLastDate = mysqli_query($conn, $sqlQueryLastDate);
$resultCheckLastDate = mysqli_num_rows($resultLastDate);
if ($resultCheckLastDate > 0) {
while ($rowLastDate = mysqli_fetch_assoc($resultLastDate)) {
$lastInDate = $rowLastDate['fell_in'];
$sqlQueryCurrentDate = "SELECT * FROM (select * from periods WHERE id = $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
$resultCurrentDate = mysqli_query($conn, $sqlQueryCurrentDate);
$resultCheckCurrentDate = mysqli_num_rows($resultCurrentDate);
if ($resultCheckCurrentDate > 0) {
while ($rowCurrentDate = mysqli_fetch_assoc($resultCurrentDate)) {
$currentOutDate = $rowCurrentDate['fell_out'];
$lastIn = new DateTime($lastInDate);
$currentOut = new DateTime($currentOutDate);
$intervalLastCurrent = $lastIn->diff($currentOut);
$elapsedLastCurrent = $intervalLastCurrent->format('%a days %h hours');
/*Why? Php is erasing everything after adding the above variable to the table...Entire first row gets erased!*/
echo "
<tr>
<td>".$id."</td>
<td class='test'>".$elapsedLastCurrent."</td>
<td class='dateOutResult'>".$out."</td>
<td class='dateInResult'>".$in."</td>
<td class='sumHours'>".$sum."</td>
<td class='nextEstimate'>".$nextEstimate." (".$nextEstimateDays.")</td>
<td class='notes'>".$notes."</td>
</tr>";
} /*$sqlQueryCurrentDate*/
}
} /*$sqlQueryLastDate*/
}
} /*$sqlQuery*/
}
?>
Here's the live result: https://unidrones.co.za/periods
I am really new to mysql/php so I do not understand what I'm doing wrong. The nested queries is probably not the best approach to use, but I'm still learning, and any input will be deeply appreciated.
This is because your query is
//select * from periods WHERE id < $id ORDER BY id DESC LIMIT 1;
your first $id will be always equal id.
Related
I'm still learning PHP & MySQL and the following has confused me for a long time and I'm looking for some guidance as to how I'd be able to do this.
Basically, I have a HTML table which is displayed by an echo which grabs the values from a MySQL database, the table displays Position, User, Today. Weekly & Monthly. The rows that the table displays is dependent on how many users are logged in so if 10 people are logged in, 10 rows will be displayed, 5 users = 5 rows etc. To achieve this I created a loop which displays the information for each logged in user and this is where I think the issue starts with sorting the data. This is what is used to display the data:
<?php
$counter = 1;
include_once 'config.php';
$sql = "SELECT * FROM vicidial_live_agents";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$dateNow = date('Y-m-d H:i:s');
$dateNow = strtotime($dateNow);
$dateOld = $row['last_state_change'];
$dateOld = strtotime($dateOld);
$dateDiff = $dateNow - $dateOld;
if ($row['status'] == "INCALL") {
$colour = "w3-green";
}
elseif ($row['status'] == "READY") {
$colour = "w3-yellow";
}
elseif ($row['status'] == "PAUSED") {
$colour = "w3-grey";
}
elseif ($row['status'] == "DEAD") {
$colour = "w3-red";
}
$user = $row['user'];
echo
'<tr class="'.$colour.'">
<td class="w3-xlarge">'.$counter.'</td>
<td class="w3-xlarge">'.$user.'</td>';
$sql2 = "SELECT count(status) AS sales FROM vicidial_agent_log WHERE user = '$user' AND DATE(event_time) = CURDATE() AND status = 'SALE'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc())
{
echo
'<td class="w3-xlarge">'.$row2['sales'].'</td>';
$sql3 = "SELECT count(status) AS salesWeek FROM vicidial_agent_log WHERE user = '$user' AND WEEK(event_time) = WEEK(CURDATE()) AND YEAR(event_time) = YEAR(CURDATE()) AND status = 'SALE'";
$result3 = $conn->query($sql3);
while($row3 = $result3->fetch_assoc())
{
echo
'<td class="w3-xlarge">'.$row3['salesWeek'].'</td>';
$sql4 = "SELECT count(status) AS salesMonth FROM vicidial_agent_log WHERE user = '$user' AND MONTH(event_time) = MONTH(CURDATE()) AND YEAR(event_time) = YEAR(CURDATE()) AND status = 'SALE'";
$result4 = $conn->query($sql4);
while($row4 = $result4->fetch_assoc())
{
echo
'<td class="w3-xlarge">'.$row4['salesMonth'].'</td>
</tr>';
$counter++;
}
}
}
}
?>
What I want is for the table to be sorted by highest monthly sales with the highest being at the top and lowest at the bottom.
I have done some research and the solutions I've found I could not get to work with this situation for example, a JS sort from W3Schools wouldn't work and I think this is due to the values being called from the database.
I hope this is clear, any advice on how to tackle this is appreciated :)
What I am trying to achieve best described in the example diagram below, in a html table. My table works fine with data from a MySQL database but all the data is printed in rows, which is correct, however I am required to display the data in the format below and the same format in Excel. This avoids repeating similar data.
My SQL statement is this:
$query = mysql_query("SELECT * FROM Reservations WHERE Date = '$DateToday' ORDER BY Airline ASC, Flight ASC, Name");
but I guess to achieve the desired display php would be more relevant than MySQL.
So first the while loop....
while ($row = mysql_fetch_array($query)) { $results = mysql_query("SELECT * FROM Reservations WHERE Airline = '$Airline'");
$Count = mysql_num_rows($results);
if($Count > 1) // More then 1 passenger on same flight
{
$iReservationID = $row['ReservationID'];
$iAirline = strtoupper($row['Airline']);
$iFlight = strtoupper($row['Flight']);
$iName = strtoupper($row['Name']);
$iName = "<BR>".$iName;
} else {// NOT More then 1 passenger on same flight
$ReservationID = $row['ReservationID'];
$Airline = strtoupper($row['Airline']);
$Flight = strtoupper($row['Flight']);
$Name = strtoupper($row['Name']);
}
}
<table>
<tr>
<td>AIRLINE</td>";
<td>FLIGHT#</td>";
<td>PASSENGER</td>";
</tr>
<tr>
<td>echo $Airline;</td>
<td>echo $Flight;</td>
<td>print "$Name<BR>$iName</td>
</tr>
</table>
The table works fine with rows for each entry when there is only one passenger but it is duplicating the passenger names when nested.
SELECT DISTINCT doesn't do the trick either nor SELECT FROM Reservations WHERE ReservationID <> $ReservationID - I have tried a second WHILE loop to refetch the data according to FLIGHT# but still not correct.
Suggestions greatly appreciated.
You can try this code
<?php
$query = mysql_query("SELECT *,GROUP_CONCAT(Name SEPARATOR '<BR>') AS PasName FROM Reservations WHERE Date = '$DateToday' GROUP BY Airline,Flight ORDER BY Airline ASC, Flight ASC, Name");
echo "<table>
<tr>
<td>AIRLINE</td>
<td>FLIGHT#</td>
<td>PASSENGER</td>
</tr>";
while ($row = mysql_fetch_array($query)) {
//$results = mysql_query("SELECT * FROM Reservations WHERE Airline = '$Airline'");
$ReservationID = $row['ReservationID'];
$Airline = strtoupper($row['Airline']);
$Flight = strtoupper($row['Flight']);
$Name = strtoupper($row['PasName']);
//$Count = mysql_num_rows($results);
/*if ($Count > 1) { // More then 1 passenger on same flight
$iName = "";
while ($inrow = mysql_fetch_array($results)) {
$iName .= "<BR>".$inrow['Name'];
}
} else {// NOT More then 1 passenger on same flight
// $ReservationID = $row['ReservationID'];
// $Airline = strtoupper($row['Airline']);
// $Flight = strtoupper($row['Flight']);
}*/
echo "<tr>
<td>$Airline</td>
<td>$Flight</td>
<td>$Name</td>
</tr>";
}
echo "</table>";
?>
But, I recommend you to fetch the multiple users within query only i.e replace this query
SELECT * FROM Reservations WHERE Airline = '$Airline'
with
SELECT GROUP_CONCAT(Name SEPARATOR '<BR>') FROM Reservations WHERE Airline = '$Airline' GROUP BY Airline,Flight
so that there is no need of inside loop for concating user names
Try this
$sql = "SELECT * FROM Reservations WHERE Date = '$DateToday' ORDER BY Airline ASC, Flight ASC, Name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<table>
<tr>
<td>AIRLINE</td>
<td>FLIGHT#</td>
<td>PASSENGER</td>
</tr>
";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>
<td>"+$row['ReservationID']+"</td>
<td>"+strtoupper($row['Airline'])+"</td>
<td>"+strtoupper($row['Flight'])+"</td>
<td>"+MethodToFetchNameOfPassengersOfTheFlight(params)+"</td>
</tr>";
echo "</table>";
}
for the method
string MethodToFetchNameOfPassengersOfTheFlight(params){
//write a query to fetch the name of the passenger of the flight
$CustomerNames = "";
//in for each loop do this
foreach($name in $names)
$CustomerNames += $name + "<br>";
return strtoupper($CustomerNames);
}
First we show the details of the airlines. Then we find the passengers of the corresponding flight and append them in a string with breaks and then distplay them.
I am trying to get a random row from MySQL table but all three attemps:
$query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
give a NULL result in mysql_query($query).
Higher up my PHP code I obtain a row from the same table OK by specifying WHERE, so I don't understand why I can't retrieve a random one.
Here is the code snippet:
$query = "SELECT uid,clu FROM uable WHERE un = '$un'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$resultid = mysql_fetch_assoc($result);
$uid = $resultid['uid'];
file_put_contents('debugging.txt',__LINE__.' - $uid = '.var_export($uid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE uid = $uid AND cn = '$cn'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$cr = mysql_fetch_assoc($result);
$cid= $cr['cid'];
file_put_contents('debugging.txt',__LINE__.' - $cid= '.var_export($cid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM fable WHERE cid= '$cid'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
file_put_contents('debugging.txt',__LINE__.' - $result = '.var_export($result,true).PHP_EOL,FILE_APPEND);
$fr = mysql_fetch_assoc($result);
file_put_contents('debugging.txt',__LINE__.' - $fr = '.var_export($fr,true).PHP_EOL,FILE_APPEND);
echo '<form action="'.$_SERVER['PHP_SELF'].’" method="post">';
if (!$fr) {
$o= $cn;
while ($o= $cn) {
// $ac = mysql_query("SELECT * FROM table") or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
// $num_rows = mysql_num_rows($ac);
//file_put_contents('debugging.txt',__LINE__.' - $num_rows = '.$num_rows.PHP_EOL,FILE_APPEND);
// --$num_rows;
// $query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
// $query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
$resultid = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($resultid);
$o= $opr['cn'];
}
file_put_contents('debugging.txt',__LINE__.' - $query = '.$query.PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $resultid = '.var_export($resultid,true).PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $op[\'cid\'] = '.$op['cid'].PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE cid= ".$op;
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($opr);
$o= $opr['cn'];
$od= $opr['description'];
echo '<p>'.$op;
if ($od<> '') {
echo ','.$odesc;
}
echo '</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
} else {
echo '<p>'.$fr['p'].'</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
}
echo '</form>';
The resulting debugging.txt:
24 - $uid = '4'
29 - $cid = '21'
32 - $result = NULL
34 - $fr = false
These queries look OK, but I think you're starting at the wrong place. When you're uncertain how to frame something in SQL, open up a SQL client like SequelPro or Navicat and try writing a few queries by hand until you get the result you want. (Also this gives you a chance to double-check the contents of relevant tables and ensure the expected data are there.) Then you can go back into the PHP with full confidence that the SQL code is correct, so if there's a problem it must be with the PHP (either the variables you inject into a Mysql statement, or the way you call that statement).
Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";
I have the following code:
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($result = mysql_fetch_array($query)) {
extract($result);
if ($activity_type == "discussion") {
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($result = mysql_fetch_array($query)) {
extract($result);
echo $discussion_user . " said:<br>" . $discussion_text . "<br>";
}
} elseif ($activity_type == "file") {
}
}
But it just returns the last row. My goal is to have a chronological list of "activities" each displayed slightly differently depending on their type.
Your using $query and $result twice so the second loop is overwriting the result of the first and stopping...
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
and
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
same with $results var...
I would suggest you change to $query and $query2 but best to use something like
$activies = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($activity = mysql_fetch_array($activies)) {
and
$discussions = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($discussion = mysql_fetch_array($discussions)) {
I would also avoid using extract - as you might be overwriting vars your not expecting to...
You have to create another connection to the database so that you can run them at the same time.
OR
You can load the results of the first one into an array, and then just loop through the array.