Selecting row information by date - php

I'm trying to display data starting at a certain time and day and ending and another time and day. here is my code:
<?php
include 'includes/connect3.php';
$query = "SELECT * FROM u_visits WHERE date >= '2013-08-31 22:56:20' AND date <= '2013-
08- 31 23:59:59'";
$result = mysqli_query($con,$query);
echo "<table><tr>
<th>USER ID</th>
<th>TIMES VISITED</th>
</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['visits'] . "</td></tr>";
}
echo "</table>";
?>
When I go to the page, only the table header is displayed with no data showing.

you can also use BETWEEN for range comparisons.
$query = "SELECT * FROM u_visits WHERE `date` BETWEEN '2013-08-31 22:56:20' AND '2013-08-31 23:59:59'";

The reason you didn't see any result is because your query has some errors. The error in your query is that you have a space after 2013-08- in your where clause (date <= '2013-08- 31 23:59:59'";)
Had you used proper error handling, you would have noticed this yourself. One common way to do this is:
$result = mysqli_query($con,$query) or die ('Query execution failed: ' . mysqli_error($con));

Related

Need help displaying only one result per user from database (PHP)

i am making a top 10 list of the best times from my bhop server in csgo. All the times get stored in the database, but the problem is that each time the user gets a new time it adds a new row. With the code i have now it displays the top ten list of all the times, i want it to only display one result per user(the best one)
My current code:
<div id="content">
<table cellspacing="0">
<h1 align="center">bhop_eazy_csgo</h1>
<tr><th>Place</th><th>Name</th><th>Time</th></tr>
<?php
$i = 1;
$con=mysqli_connect("localhost","root","*******","timer");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM round WHERE map = 'bhop_eazy_csgo' ORDER BY time LIMIT 0, 10");
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . ($i) . "</td><td>" . $row['name'] . "</td> <td>" . gmdate("i:s", $row['time']) . "</td></tr>";
$i++;
}
mysqli_close($con);
?>
</table>
</div>
How it looks:
http://gyazo.com/3653ec8a87fbf68c4137b67b75e20f8d
Edit
Now it looks like this:
1 Wildmine 00:49 2 Wildmine 00:50 3 Wildmine 01:02 4
?J#rr3? 01:12
I want it to look like this:
1 Wildmine 00:49 2 ?J#rr3? 01:12
Thanks to Michael Wagner for helping me getting it working:)
$result = mysqli_query($con,"
SELECT DISTINCT name n, (
SELECT time
FROM round
WHERE map = 'bhop_eazy_csgo'
AND name = n
ORDER BY time
LIMIT 1
) AS time
FROM round
WHERE map = 'bhop_eazy_csgo'
ORDER BY time
LIMIT 0 , 10
");
while($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . ($i) . "</td><td>" . $row['n'] . "</td> <td>" . gmdate("i:s", $row['time']) . "</td></tr>";
$i++;
}
Try this:
SELECT DISTINCT name n, (
SELECT time
FROM round
WHERE map = 'bhop_eazy_csgo'
AND name = n
ORDER BY time
LIMIT 1
) AS time
FROM round
WHERE map = 'bhop_eazy_csgo'
ORDER BY TIME
LIMIT 0 , 10

Print a row from a database

I need to print a row from a database, i know how to print columns, but having a hard time printing rows. Can someone tell me how to?
<?php
$query = "SELECT * FROM categorias ";
$result = mysqli_query($conn, $query) or die (mysql_error());
while ($categoria = mysqli_fetch_array($result)) {
echo "<p>" . $categoria ['descricao'] . "</p>";
}
?>
This is how im printing columns
The answer is don't use SELECT * in PHP, it's extremely prone to errors. If you explicitly list the columns in your select statement you can concatenate them into a table in PHP.
Hope this helps.
Use print_r to debug selected data.
Also look for Mysql Fetch Row
Always Use Google
<?php
$query = "SELECT * FROM categorias ";
$result = mysqli_query($conn, $query) or die (mysql_error());
if(mysqli_num_rows($result)>0)
{
while ($categoria = mysqli_fetch_array($result)) {
echo "<p>" . $categoria['descricao'] . "</p>";
}
}
?>
<table><tr><?php
while ($categoria = mysqli_fetch_array($result)) {
echo "<td>" . $categoria ['descricao'] . "</td>";} ?></tr></table>
I use a table, where while the array is true places the values cell by cell in a row, because the loop is working inside the <tr> </tr> creating a new <td> for every record.

How do I Subtract Values of Multiple Queries

I have had a long road to get to this last question. Everything is my code is working now, but I can't get this last little issue. Right now I have:
$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS
value_sum FROM maindata GROUP BY phonenumber, dataplan";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$val = $row["value_sum"];
$plan = $row["currentplan"];
$remain = $plan - $val;
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
It only subtracts the first value as opposed to the values for all. displayed like this:
while ($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['phonenumber'] . "</td> ";
echo "<td>".$row['currentplan'] . "</td> ";
echo "<td>".ROUND ($row["value_sum"],2) . "MB</td> ";
echo "<td>".$remain . " MB</td> ";
echo "<td>".$row['email'] . "</td></tr>";
}
So my goal is to subtract all value_sums from all dataplans, but what I have now, gives me the first value for all columns. Thank you!
mysql_fetch_assoc() will always get one row. You can use it in loop, or better use PDO, eg. like this:
$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS
value_sum FROM maindata GROUP BY phonenumber, dataplan";
$results = $pdo->query($sql);
You can read about creating PDO connections here http://www.php.net/manual/en/book.pdo.php

issues with DATETIME in database

I have devised the following code; to calculate the waiting time and expected time for a patient. The code should also echo a warning if the patient has been waiting too long.
Please note: Waiting_time is DATETIME in the database.
Here is the code;
<?php
$conn = mysqli_connect("localhost","root","") or die ("No connection");
mysqli_select_db($conn, "a&e") or die('Could not select database.');
$query = "SELECT PatientID, Forename, Surname, Gender, Illness, Priority, Arrival_time,NOW() as now,ABS(TIMEDIFF(NOW(), Arrival_time)) as Waiting_Time FROM Patient";
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'>
<tr>
<th>PatientID</th>
<th>Forename</th>
<th>Surname</th>
<th>Gender</th>
<th>Illness</th>
<th>Priority</th>
<th>Waiting Time</th>
</tr>";
while ($row = $result->fetch_object()){
//Select the expected and discharge time for this patient.
$query2 = "SELECT Abs(TIMEDIFF(Expected_Time,'00:00:00')) as Expected,Abs(TIMEDIFF(Discharge_Time,'00:00:00')) as Discharge ".
"FROM priority_time ".
"WHERE Illness = '".$row->Illness."'".
" AND Priority = '".$row->Priority."'".
";";
$result2 = mysqli_query($conn, $query2) or die("Invalid statement: ".$query2);
$row2 = $result2->fetch_object();
$expected = $row2->Expected;
$discharge = $row2->Discharge;
echo "expected-> ".$expected." discharge-> ".$discharge;
if($expected > $discharge){
echo "There is a problem with the database consistency, expectedTime must be less than dischargeTime!";
}
//Set the patient color.
if($row->Waiting_Time < $expected && $row->Waiting_Time < $discharge){
echo "<tr>";
}
if($row->Waiting_Time >= $expected && $row->Waiting_Time < $discharge){
echo '<tr bgcolor="#FFFF00">';
}
if($row->Waiting_Time > $expected && $row->Waiting_Time > $discharge){
echo '<tr bgcolor="#FF0000">';
}
//Print patient info
echo
"<td>" . $row->PatientID . "</td>
<td>" . $row->Forename . "</td>
<td>" . $row->Surname . "</td>
<td>" . $row->Gender . "</td>
<td>" . $row->Illness . "</td>
<td>" . $row->Priority . "</td>
<td>" . $row->Waiting_Time . "(".$expected."-".$discharge.") </td>";
//Close row
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
EDIT:
On each row, in the column Waiting Time it is showing the waiting time in seconds, and in brackets the currentTime a minus and the arrival time, just for checking. How do I convert the waiting time to the format hh:mm:ss to have a better representation for the user?
Showing;
Waiting time
01:15:42(10500.000000-10500.000000)
Why is it displaying (10500.000000-10500.000000)?
Try this:
gmdate("H:i:s", $seconds)
If that doesn't work, have a look at How to convert seconds to time format?
Update:
To do this in the SQL statement try something like this:
SELECT TIME_TO_SEC(TIMEDIFF('2013-03-27 12:00:00', '2013-03-27 10:00:00')) diff;
So something like this:
SELECT PatientID
, Forename
, Surname
, Gender
, Illness
, Priority
, Arrival_time
, NOW() as now
, TIME_TO_SEC(TIMEDIFF(NOW(), Arrival_time)) as Waiting_Time
FROM Patient;
Then you would change this line:
<td>" . $row->Waiting_Time . "(".$expected."-".$discharge.") </td>
to this:
<td>" . gmdate("H:i:s", $row->Waiting_Time) . "(".$expected."-".$discharge.") </td>
When dealing with dates and times in php strtotime() is your biggest friend. Lucky the date() function is all you need for this. Something that is going to convert seconds to a readable format could be the following.
$time = strtotime('now');
echo $time . '<br />';
$var = date('H:i:s',$time);
echo $var;

mysql_num_rows() not a valid resource - mysql_error() shows nothing

I have the following code.
include("DBHeader.inc.php");
include("libs/ps_pagination.php");
$sql = "SELECT * FROM Products P, Manufacturers M WHERE M.sManufacturerCode='$LC' AND M.iManufacturerID=P.iManufacturerID";
$rs = mysql_query($sql);
echo $sql;
$pager = new PS_Pagination( $conn, $sql, 3, 4, null );
$rs = $pager->paginate();
$num = mysql_num_rows( $rs ) or die('Database Error: ' . mysql_error());
if ($num >= 1 ) {
echo "<table border='0' id='tbProd' class='tablesorter' style='width:520px;'>
<thead>
<tr>
<th>Product Code</th>
<th>Product Name</th>
<th> </th>
</tr>
</thead>
<tbody>";
//Looping through the retrieved records
while($row = mysql_fetch_array($rs))
{
echo "<tr class='prodRow'>";
echo "<td>" . $row['sProductCode'] . "</td>";
echo "<td>" . $row['sProductName'] . "</td>";
echo "<td><a href='ProdEdit.php?=" . $row['sProductCode'] . "'><img src='images/manage.gif' alt='Edit " . $row['sProductName'] . "' /></a></td>";
echo "</tr>";
}
echo "</tbody></table>";
}
else {
//if no records found
echo "No records found!";
}
And instead of it giving me the data from the table, it spits out on the screen:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/nyksys/www/regserver2/search_results.php on line 37
mysql_error() is actually returning nothing at all, so I'm very confused as to what the error is. The SQL when echo'd:
SELECT * FROM Products P, Manufacturers M WHERE M.sManufacturerCode='216E3ACAC673DE0260083B5FF809B102B3EC' AND M.iManufacturerID=P.iManufacturerID
I'm baffled here! Am I overlooking something simple here?
I've double checked my database information, I'm certain that isn't the problem.
EDIT- I'm following the tutorial Paginating Your Data with AJAX and Awesome PHP Pagination Class.
$sql = "SELECT * FROM Products P, Manufacturers M WHERE M.sManufacturerCode='$LC' AND M.iManufacturerID=P.iManufacturerID";
$rs = mysql_query($sql);
echo $sql;
$rs is a MySQL result resource that you could use with mysql_num_rows.
$pager = new PS_Pagination( $conn, $sql, 3, 4, null );
$rs = $pager->paginate();
Now it's not1!
$num = mysql_num_rows( $rs ) or die('Database Error: ' . mysql_error());
Oops!
1 Or, if it is, [a] you didn't show us that in your question, and [b] the original query was entirely pointless.
You are overwriting the $rs variable
My guess is whatever the PS_Pagination class is doing, it is not returning a MySQL resource. You are overwriting your $rs resource variable with that object, and it ceases to be a valid resource, even if your query succeeds.
$rs = mysql_query($sql);
echo $sql;
$pager = new PS_Pagination( $conn, $sql, 3, 4, null );
// Use a different variable than $rs here.
$rs = $pager->paginate();

Categories