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>";
}
Related
I'm designing a website for a neighbor for a potential restaurant he wants to open. I need to create a page for testimonials/review. I'd like to code it so that the number of stars is in a SQL, I'm just not sure how to do it.
Essentially what I'm looking for is a way to determine the integer of the ratings field (1-5) and for each number, display a star image.
So:
if rating = 1, display star.png once
if rating = 2, display star.png twice
...
if rating = 5, display star.png five times
I'm just not sure how to write the code to do so.
The website is being written in PHP and CSS. I'd like to avoid JQuery, Javascript, .NET, and so forth, as I'm not as familiar with them and will be the one keeping the site up to date.
Here's what I've got so far, but it's not working right, and I get a syntax error:
$result = mysqli_query($con,"SELECT * FROM Reviews");
while($row = mysqli_fetch_array($result))
{
IF (Rating = "1"()){
echo '<img src="star.png">' . }
ELSE IF (Rating = "2"()){
echo '<img src="star.png"><img src="images/star.png">' . }
Else IF (Rating = "3"()){
echo '<img src="star.png">star.png"><img src="images/star.png">' . }
ELSE IF (Rating = "4"()){
echo '<img src="star.png"><img src="images/star.png">star.png"><img src="images/star.png">' . }
ELSE
echo '<img src="star.png"><img src="images/star.png">star.png"><img src="images/star.png"><img src="images/star.png">' .
"<br/> <b>" .
$row['Name'] .
"</b> <em>" .
$row['City'] . $row['State'] . $row['Country'] . "</em><br/>" .
$row['Review'] . "<br/> <hr> <br/>"
}
?>
Use a select statement to get the ratings for a place from your database.
Store the result in a php variable (lets call it $rating)
Use php logic to output number of stars (in html obviously) based on value of $rating.
Hope that helps :)
I would recommend 3 tables for this idea.
Users Table
UserRatings Table
Dish Table
Users table is used to store just that. User information. Possibly a username, password, first name, last name for example. The table should have a primary key. Call it UsersID. It should auto increment itself and be unique for every row.
The Dish table is next. Put a dish name in it. It should have a primary key as well. Call it DishID.
Lastly is the UserRatings table will store UserRatingsId, Rating, InsertTimeStamp, UpdateTimeStamp.
Use a loop to output your HTML based on your rating.
$rating = 4; //Figure this out in your script and set accordingly
for($i = 0; $i < $rating; $i++) {
echo '<img src="star.png" />';
}
Should print out four stars for you.
Help from a friend:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$starCount = 0;
$result = mysqli_query($con,"SELECT * FROM Reviews");
while($row = mysqli_fetch_array($result)) {
$starCount = $row['Rating'] ;
while ($starCount > 0) {
echo '<img src="images/star.png">';
$starCount -- ;
}
$starCount = 0;
echo "<br/> <b>" . $row['Name'] . "</b> - <em>" .
$row['City'] .", ". $row['State'] ." ". $row['Country'] . "</em><br/>" .
$row['Review'] . "<br/> <hr> <br/>" ;
}
?>
$number=$row->rating ;
$middle="";
$first="<td width='200' align='left'>";
for($x=1;$x<=$number;$x++) {
$middle=$middle.img($fullimage_properties);
}
if (strpos($number,'.')) {
$middle=$middle.img($halfimage_properties);
$x++;
}
while ($x<=5) {
$middle=$middle.img($blankimage_properties); ;
$x++;
}
echo $last=$first.$middle."</td>";
I'd like to increment a page views ("num_views") database value when a certain image in "Paging.php" is clicked on so I can keep track of how many times that image has been viewed
Paging.php:
while ($imageCounter < $imagesPerPage && ($row = $catResult->fetch_assoc())) {
echo "<br />ID: " . $row['imgid'] .
'<br /><img src="' . $thumbpath.$row['imgthumb'] . '"/>' .
"<br />CATFK: " . $row['catfk'] .
"<br/>";
$imageCounter++;
}
ViewComic.php
<?php
include 'include/header.php';
$imgid = $_GET['id'];
$views = $_GET['views'];
include '../scripts/dbconnect.php';
$mysqli->query("UPDATE child_images SET num_views = ($views+1) WHERE imgid = $imgid");
mysqli_close($mysqli);
?>
It doesn't seem to be incrementing though
An easier way is to just increment the value that has been posted into the database. This way you don't have to worry about data manipulate in your query string.
$imgid= $mysqli->real_escape_string($imgid);
$mysqli->query("UPDATE child_images SET num_views = num_views + 1 WHERE imgid = $imgid");
mysqli_close($mysqli);
Just do this:
$mysqli->query("UPDATE child_images SET num_views = (num_views+1) WHERE imgid = $imgid");
I am trying to add 3 combo boxes which all display the exact same information that comes from my MySQL db. It seems like the code I wrote makes the entire page wait until all 3 combo boxes are populated, before continuing.
<?
$query = "Select * from tblWriters order by surname";
for ($i = 1; $i <= 3; $i++) {
$result = mysql_query($query);
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] . ", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}
?>
I would like to optimize this piece of code, so the query will not be executed 3 times, as I believe this is where the page slows down.
If I put
$result = mysql_query($query);
outside of the for loop, the 2nd and 3rd combo box do not populate. I tried looking into resetting the pointer of the result, but I can't seem to figure out how that works.
Also, is there a way I can reuse the while loop, so I don't have to execute it 3 times?
Can someone point me in the right direction?
I'm pretty new to PHP and trying to learn on my own. Any help would be much appreciated. Thanks!
If you move your mysql_query() out of the loop again, you can reset your mysql-result-pointer by using mysql_data_seek() at the beginning or end of your loop.
This will result in:
mysql_query($query);
for($i=1;$i<=3;$i++);
{
mysql_data_seek(0); // reset datapointer
// output querydata
}
I'm obliged however to point out that the mysql-extension is deprecated by now and you should use mysqli or pdo for new projects and code.
Cache the query result in an array, then generate your markup:
$query = "Select * from tblWriters order by surname";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result))
{
$data[] = $row;
}
for ($i = 1; $i <= 3; $i++) {
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
foreach ($data as $row) {
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] .
", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}
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
?>
I have a database to store people's quick links. This is a very basic quick link storage method. The database looks like this:
full_name | 1url | 1name | 2url | 2name | 3url |3 name | 4url |4name | 5url | 5name
^This goes on until 10. I know this is a bad way, but this is for an unprofessional website.
I will want to put the result into an ordered list. But I am unsure how to change the number (1url or 2url) each time?
So currently I have it set up like this in PHP
$result = mysql_query(SELECT * FROM `links` WHERE `full_name`='$loggedin')or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<li><a href="';
echo $row['1url'];
echo '"></a></li>';
}
But I am having no luck with that! I'm very unsure of what I should do. I want it to display another <li> with an <a> and the link plus name of the link for each row found.
Thanks! Please be specific with me, as this is new ground! :D
EDIT:
I have also run into another problem. I have used code from peoples' answers and most of them work. However, If one of the fields is blank (so a user has only 6 quick links) it still shows an <li>. Now I can't see anyway round this issue. :/
SOLUTION:
Here is what works:
while($row = mysql_fetch_array($result)){
for($i = 1; $i < 10; $i++) {
if(!trim($row[$i . 'url'])=='') {
echo '<li><a href="';
echo $row[$i . 'url'];
echo '">';
echo $row[$i . 'name'];
echo '</a></li>';
} //end of didn't trim
}//end for for
}//end of while
$result = mysql_query("SELECT * FROM `links` WHERE `full_name`='$loggedin'")or die (mysql_error());
while($row = mysql_fetch_array($result)){
for($i = 1; $i < 10; $i++)
{
echo '<li><a href="';
echo $row[$i . 'url'];
echo '"></a></li>';
}
}
Mind you, this is pretty hacky... I would have just implemented it with 3 columns (maybe 4 using an autoincrement to sort) and then select the rows based on the user, emitting each row. That removes the 10 url limit.
Edit
For your second question, have a look at the PHP 'empty' function and break/continue the loop if the function returns true.
It would be a lot cleaner and easier to change your database setup a little bit. You could have two tables:
users
id: a unique ID for each user, probably an auto increment int of some sort
full_name: just as you've used it in your table
quick_links
id: quick link id, probably an auto increment int (or you could do a primary index on user_id+order)
user_id: the user ID to tell us who this quick_link belongs to
name: the name of the quick link
url: the url of the quick link
order: what order to show this link in
Then you can simply do something like
$userid_result = mysql_query(
"SELECT `id` from `users` WHERE `full_name` = $loggedin;"
);
$row = mysql_fetch_row($userid_result);
$userid = $row[0];
$links_result = mysql_query(
"SELECT * from `quick_links` WHERE `user_id` = $userid ORDER BY `order` ASC;"
);
while($quick_link = mysql_fetch_object($links_result))
{
printf("<li>%s</li>", $quick_link->url, $quick_link->$name);
}
Of course you'd need some error checking in there, but that gives you an idea.
You need to put some double quotes around your select statement:
$result = mysql_query("SELECT * FROM `links` WHERE `full_name`='$loggedin'") or die (mysql_error());
while($row = mysql_fetch_array($result)){
echo '<li><a href="';
echo $row['1url'];
echo '"></a></li>';
}
while ($row = mysql_fetch_array($result))
{
$full_name = array_shift($row);
for ($i = 0; $i < 10; ++$i)
{
echo '<li><a href=' . htmlspecialchars(array_shift($row)) . '>';
echo array_shift($row);
echo '</a></li>';
}
}
array_shift returns the first element from an array and removes it from the array at the same time. So the code above removes the full_name field from the record and then iterates over the rest of the record, removing and printing a URL and its corresponding name on each iteration.
htmlspecialchars is used to ensure that a valid a-tag is created. Depending on where the name of the link comes from, it should also be used on the name of the link.
You SQL query needs to be passed as a string enclosed in "...":
$result = mysql_query( "SELECT * FROM `links` WHERE `full_name`='$loggedin'" )
or die (mysql_error());
$i = 0;
while($row = mysql_fetch_array($result)){
$attributeURL = $i . 'url';
$attributeName = $i++ . 'name';
echo '<li>'
. '' . $row[ $attributeName ] . '
. '</li>'
;
}