I'm having some problems with the php script below that I'm currently working on. What I am trying to do is make a list with 5 events that are being shown ordered by date.
In my database I have a table with events. Each event has a date (DATETIME), an id and a name. What the php needs to do is check the table with events and filter the ones that have already passed. If an event has already passed, it's not shown. If it still has to happen, it's shown.
Now the problem is that in the do while loop, the script doesn't seem to go to a next row when it has had a run.
For example: if the database table has 10 events in it, it will show 10 times the event that's on the first row of the table when testing.
I need to know what I'm doing wrong, or if there is a way to make the row increase after each run of the loop.
<?php
$test_query_kalender = "SELECT * FROM kalender ORDER BY datum ASC";
$test_result_kalender = mysql_query($test_query_kalender);
$rij_kalender = mysql_fetch_assoc($test_result_kalender);
$vandaag_unix = time();
$datum_unix = strtotime($rij_kalender['datum']);
$i = 0; //this variable is used to insure that only 5 items are being shown on the page
do{
if($datum_unix >= $vandaag_unix) //checks if the date of the event has already passed
{
//if the date has not passed, the event will be shown
echo "<p>" . date("d-m-Y", $datum_unix) . " " . $rij_kalender['naam'] . "</p>";
$i++;
}
else
{ //if it has already passed then it should put nothing, but for testing I put a line in it
echo "<p>" . $rij_kalender['naam'] . "</p>";
}
} while(($i <= 4) && ($rij_kalender = mysql_fetch_assoc($test_result_kalender)));
echo "<p>While loop finished</p>"; //just some checking
?>
Your code loads the date once and then compares it to today each time. Move
$datum_unix = strtotime($rij_kalender['datum']);
into the loop, before the date check.
Try this:
<?php
$test_query_kalender = "SELECT * FROM kalender ORDER BY datum ASC";
$test_result_kalender = mysql_query($test_query_kalender);
$rij_kalender = mysql_fetch_assoc($test_result_kalender);
$vandaag_unix = time();
$datum_unix = strtotime($rij_kalender['datum']);
$i = 0; //this variable is used to insure that only 5 items are being shown on the page
while($rij_kalender = mysql_fetch_assoc($test_result_kalender))
{
$datum_unix = strtotime($rij_kalender['datum']);
if($datum_unix >= $vandaag_unix) //checks if the date of the event has already passed
{
//if the date has not passed, the event will be shown
echo "<p>" . date("d-m-Y", $datum_unix) . " " . $rij_kalender['naam'] . "</p>";
$i++;
}
else
{
//if it has already passed then it should put nothing, but for testing I put a line in it
echo "<p>" . $rij_kalender['naam'] . "</p>";
}
if ($i == 5) break;
}
echo "<p>While loop finished</p>"; //just some checking
?>
Related
I am showing results arranged in table from mysql database using php, but I am not being able to find a way to paginate my results, because of the data being arranged in table and because some of the rows are missing and as webpage will be dynamic so user will be able to delete rows and insert new rows again and again, so because of that I can't get my results paginated using auto_increment value as well.
Following is my script:
<?php
$mysql_session = mysql_query("SELECT * FROM session");
$no_of_rows_session = mysql_num_rows($mysql_session);
$msg_session='';
$last_row = mysql_query("SELECT * from session ORDER BY id DESC LIMIT 1");
$last_id = '';
while($select_id_of_last_row = mysql_fetch_array($last_row)) {
$last_id = $select_id_of_last_row['id'];
}
?>
<?php echo $msg_session; ?>
<?php
if($no_of_rows_session < 1) {
$msg_session = 'No Session has been added yet';
} else {
for($i = 1; $i<=$last_id; $i++) {
${'mysql_session_every_single_query_' . $i} = mysql_query("SELECT * FROM session WHERE id LIKE '%$i%'");
${'mysql_existance_of_session_id_' . $i} = mysql_num_rows(${'mysql_session_every_single_query_' . $i});
while(${'mysql_every_session_data_' . $i} = mysql_fetch_array(${'mysql_session_every_single_query_' . $i})){
${'id_session_' . $i} = ${'mysql_every_session_data_' . $i}['id'];
${'session_start_' . $i} = ${'mysql_every_session_data_' . $i}['start'];
${'session_end_' . $i} = ${'mysql_every_session_data_' . $i}['end'];
echo "<table>";
echo "<tr id='tr_session_hover_" . $i . "'
class='tr_session_hover'
onClick=\"document.location='session_edit.php?ss=${'session_start_' . $i}&se=${'session_end_' . $i}';\">
<td>" . ${'session_start_' . $i} . "-" . ${'session_end_' . $i} . "</td>
</tr>";
echo "</table>";
}
}
}
?>
I think you are on wrong way. The things like this is simple when you choice the some order criteria and implement it into your table - for example the time of last edit or creation of the row. After that, when you have a page length and number of the page you have to use OFFSET / LIMIT clauses for SELECT, ordered by criteria - in this way you let the MySQL engine generate the proper pages.
I have got a solution.
If you are also facing such kind of problem and want to proceed with variables only (like me):
suppose you need to show 6 results on one page and your auto_increment (suppose a column named id is the auto_increment one, in your table) values are't regular, then what you can do is, get id of the 6th element by
I am supposing that you have already connected to phpmyadmin and selected a database
$no_of_results_per_page = 6;
if(isset($_GET['page_no'])) {
$page_no = $_GET['page_no'];
} else{
$page_no = 1;
}
$upper_limit = ($page_no - 1)*$no_of_result_per_page - 1;
if($page_no > 1){
$mysql_getting_id_le = mysql_query("SELECT id FROM table LIMIT $upper_limit, 1");
while($getting_id_last_elem = mysql_fetch_array($mysql_getting_id_le)) {
$id_last_element = $getting_id_last_elem['id'];
}
} else {
$mysql_getting_id_le = mysql_query("SELECT id FROM table LIMIT 0, 1");
while($getting_id_last_elem_p_1 = mysql_fetch_array($mysql_getting_id_le)) {
$id_last_element = $getting_id_last_elem_p_1['id'];
$id_last_element = $id_last_element - 1;
}
}
The above query will help us in getting id of the last element of the page
Now we will be creating the buttons to navigate from one page to another.
$final_mysql_query = mysql_query("SELECT * FROM table WHERE id > '%id_last_element%' LIMIT $no_of_results_per_page");
//Now, we can get all data limited to show no. of results you have defined per page using a loop
$total_results = mysql_query("SELECT * FROM table");
$total_results_count = mysql_num_rows($total_results);
$total_pages = ceil($total_results_count/$no_of_results_per_page);
$page_no = '';
for($i = 1; $i <= $total_pages; $i++) {
$page_no .= "<a href='?page_no=" . $i . "'>" . $i . "</a>";
}
I recently had a script that worked where I could count the rows in a table with a variable like so:
$i = 1;
while($row = mysqli_fetch_array($query5)) {
echo "$i";
echo "<br />";
$i++;
}
However, I recently implemented this pagination script here http://papermashup.com/easy-php-pagination/ which ruins it. As I go to the second page, it counts the rows all over again and starts identifying each row as #1. However, I would like it to continue to name the same row # from the previous page. Is this possible?
You must have page number somewhere, so start counting from page number * items per page
$i = $page_number * $page_size + 1;// assuming page_number starts from 0
while($row = mysqli_fetch_array($query5))
{
echo "$i";
echo "<br />";
$i++;
}
This is for a timetable and what it does is displays the previous day's timetable and who has booked each slot (this is for a radio station.)
At the moment it displays who has booked each slot in chronological order however I would like it to say the time next to each result. The query outputs 24 rows (which is from Midnight to 23:00) and next to each slot I would like it to say (00:00, 01:00, 02:00, 03:00... 21:00, 22:00 so on so forth.)
This is my current code:
<?php
include("../config.php");
#// Timetable Clearup Variabls
$yesterday = strtotime('yesterday');
$yesterdow = date('l',$yesterday);
echo "<table width=\"580px\" class=\"board\" border=\>";
$order = "SELECT * FROM timetable WHERE day = '$yesterdow'";
$result = mysql_query($order);
// Error checking
if (!$result) {
// output error, take other action
}
else {
while ($row=mysql_fetch_array($result)){
// Append all results onto an array
$rowset[] = $row;
}
}
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td></tr>";
}
?>
Can you help?
I think we're all looking too hard at a VERY simple problem. You are already using SELECT * in your query, so you're already fetching all three columns from your table. So now, all you need to do is add another cell to each row of your table.
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td><td>" . htmlspecialchars($row['time']) . "</td></tr>";
And to make sure you are fetching your rows in the correct order, you should add an ORDER BY to your query:
SELECT * FROM timetable WHERE day = '$yesterdow' ORDER BY time
If you don't specify an ORDER BY clause, you have no guarantee that you will get the results in any particular order.
And one last thing, you are looping through the rows twice, unnecessarily. Get rid of the foreach loop and put the echo directly inside the while loop.
try this:
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . htmlspecialchars($row['time'])"</td></tr>";
I'm a little bit confused why it does not work.
What i want is that control db if for ex 2012-02-21 exist in DB delete it and insert again but it does not work why
my full code is that but else statement doesnt work :S
$ga->requestAccountData();
$mysql = new mysql();
$mysql->connect();
// $startDate = date("Y-m-d");
$startDate = "2012-02-21";
$dbResult = mysql_query("select * from profiles where profile_Date='".$startDate."'");
$query = mysql_num_rows($dbResult);
if($query > 0)
{
mysql_query("delete from profiles where profile_Date='".$startDate."'");
foreach ($ga->getResults() as $result) {
$ga->requestReportData($result->getProfileId(),array('eventCategory','eventAction'),array('totalEvents'),$sort_metric=null,$filter='eventAction==InitPlayer',$start_date=$startDate,$end_date=$startDate);
foreach($ga->getResults() as $result2)
{
echo $result;
echo $result2->geteventCategory()."<br />";
echo $result2->geteventAction();
echo $result2->gettotalEvents();
"<br />";
"<br />";
"<br />";
$mysql->query("insert into profiles values(" . $result->getProfileId() . ",'" . $result . "','".$result2->geteventCategory()."','".$result2->geteventAction()."','".$result2->gettotalEvents()."','".$startDate."')");
}
}
}
else
{
foreach ($ga->getResults() as $result) {
$ga->requestReportData($result->getProfileId(),array('eventCategory','eventAction'),array('totalEvents'),$sort_metric=null,$filter='eventAction==InitPlayer',$start_date=$startDate,$end_date=$startDate);
foreach($ga->getResults() as $result2)
{
echo $result;
echo $result2->geteventCategory()."<br />";
echo $result2->geteventAction();
echo $result2->gettotalEvents();
"<br />";
"<br />";
"<br />";
$mysql->query("insert into profiles values(" . $result->getProfileId() . ",'" . $result . "','".$result2->geteventCategory()."','".$result2->geteventAction()."','".$result2->gettotalEvents()."','".$startDate."')");
}
}
}
You should use mysql_num_rows to count the results selected and not mysql_affected_rows which applies to queries altering data (insert, update, delete etc.)
$result = mysql_query("select * from profiles where profile_Date='".$startDate."'");
$count = mysql_num_rows($result);
if($count > 0) {
...
}
http://php.net/manual/en/function.mysql-num-rows.php
Why you need to first delete and then insert? you can use update query as well. Also what is the data type of the field profile_Date ? Is it set date or date and time?
You can use MySQL's REPLACE functionality (docs).
It basically works like INSERT, with the exception that if a value with the same key already exists in the database, at first the existing value will be removed and afterwards the new value will be inserted as completely new entry. If there is no existing value, it will behave like INSERT.
Watch out for the differences to UPDATE
The difference to UPDATE is hidden in the details:
since an existing value will actually be removed, all referenced foreign keys constraints will be removed too.
UPDATE will just update the values provided, with INSERT the other columns will get the default value (practical example: a field name timestamp_created with the default value of CURRENT_TIMESTAMP will be unchanged in an UPDATE statement, but will display the current time in a REPLACE statement)
I'm working at this thing that takes information from a MySQL database that comes from a contact form and displays it all to the user. Well, I got that far without issues using:
$result = mysql_query("SELECT * FROM contact");
while($row = mysql_fetch_array($result))
{
echo $row['name'] . "<br/>" . " " . $row['email'] . "";
echo "<br/>";
echo $row['message'];
echo "<br />";
}
Now I would like to add a button next to each item that would single them out, basically taking me to a page where only the selected row shows up, not all of them, as happens on this page.
The thing is that i don't know how to do that. So, does anyone have any ideas?
Thanks!
Add a button that refreshes the page with a "GET" parameter, such as yourpage.php?uid=123; Then do
if ($_GET['uid'] !== null) {
$id = (int) $_GET['uid'];
$result = mysql_query('SELECT * FROM contact WHERE id='.$id);
...
}