Retrieving records from the table with reference - php

i have this code of Pagination, actually it will retrieve all the records in my table student, what i want is to retrieve records with a reference by year level. here is the code:
thanks for your help!
<?php
if (!isset($_POST['level'])) {
$_POST['level'] = "undefine";
}
$level = $_POST['level'];
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("kp_and_harang") or die(mysql_error());
if (!(isset($_GET['pagenum']))) {
$pagenum = 1;
} else {
$pagenum = $_GET['pagenum'];
}
$data = mysql_query("SELECT id,surname,firstname,middlename,level FROM students") or die(mysql_error());
$rows = mysql_num_rows($data);
$page_rows = 2;
$last = ceil($rows / $page_rows);
if ($pagenum < 1) {
$pagenum = 1;
} elseif ($pagenum > $last) {
$pagenum = $last;
}
$max = 'limit ' . ($pagenum - 1) * $page_rows . ',' . $page_rows;
$data_p = mysql_query("SELECT *,LPAD(id,4,'0') as id FROM students $max ") or die(mysql_error());
while ($info = mysql_fetch_array($data_p)) {
echo "<tr class='tr1'>";
echo "<center>";
echo "<td class='1'>" . $info['id'] . "</td>";
echo "<td class='1'>" . $info['surname'] . ", " . $info['firstname'] . " " . $info['middlename'] . "</td>";
echo "<td class='1'>" . $info['level'] . "</td>";
echo "</center>";
echo "</tr>";
echo "<br>";
}
echo "<p>";
echo " --Page $pagenum of $last-- <p>";
if ($pagenum == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo "----";
$previous = $pagenum - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
echo " ---- ";
if ($pagenum == $last) {
} else {
$next = $pagenum + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo "----";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
?>

I have rewrote your code to use mysqli.
As well, you just needed to add a "where" to you sql query.
<?php
if (!isset($_POST['level'])) {
$_POST['level'] = "undefined";
}
$mysqli = new mysqli("localhost", "user", "password", "database");
$level = $mysqli->real_escape_string($_POST['level']);
if (!(isset($_GET['pagenum']))) {
$pagenum = 1;
} else {
$pagenum = $_GET['pagenum'];
}
$query = "SELECT id,surname,firstname,middlename,level FROM students";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$rows = $result->num_rows;
$page_rows = 2;
$last = ceil($rows / $page_rows);
if ($pagenum < 1) {
$pagenum = 1;
} elseif ($pagenum > $last) {
$pagenum = $last;
}
$max = 'limit ' . ($pagenum - 1) * $page_rows . ',' . $page_rows;
if ($level == "undefined"){
$query = "SELECT *,LPAD(id,4,'0') as id FROM students $max" ORDER BY level;}
else{
$query = "SELECT *,LPAD(id,4,'0') as id FROM students $max where level = '$level' ORDER BY level";}
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
while ($info = $result->fetch_array(MYSQLI_BOTH)) {
echo "<tr class='tr1'>";
echo "<center>";
echo "<td class='1'>" . $info['id'] . "</td>";
echo "<td class='1'>" . $info['surname'] . ", " . $info['firstname'] . " " . $info['middlename'] . "</td>";
echo "<td class='1'>" . $info['level'] . "</td>";
echo "</center>";
echo "</tr>";
echo "<br>";
}
echo "<p>";
echo " --Page $pagenum of $last-- <p>";
if ($pagenum == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo "----";
$previous = $pagenum - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
echo " ---- ";
if ($pagenum == $last) {
} else {
$next = $pagenum + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo "----";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
?>
As well, this code was meant to match your code as close as possible, however... a much better way would be to make level an int value, as well using a case with default being the line $query = "SELECT *,LPAD(id,4,'0') as id FROM students $max";.

Related

PHP Simple Pagination

the below code is getting some values from DB by "select option form" , i recently added Pagination snip to limit the results, when i run the code it fetch 5 recorders as defined,but didn't show the remaining number of pages.
what im doing wrong here ?
<?php
$per_page = 5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page = 1;
}
$start_from = ($page - 1) * $per_page;
if (!empty($_POST['form_val']) && isset($_POST['form_val'])) {
$_POST['form_val'] = 0;
$sql = "SELECT u.log_id , u.user_name, s.site, u.date ,u.comment , l.location, e.picture FROM `pool` u, `location_all` l , `site_all` s JOIN db2.user e
where l.location_id = u.location and s.site_id = u.site and e.user_id = u.user_id";
if (!empty($_POST['Location']) && isset($_POST['Location'])) {
$sql = $sql . " AND location =" . $_POST['Location'];
}
$strtdate = $_POST['Sday'];
$enddate = $_POST['Eday'];
if (!empty($_POST['Sday']) && isset($_POST['Sday']) && !empty($_POST['Eday']) && isset($_POST['Eday'])) {
$sql = $sql . " AND date between '" . $strtdate . "' and '" . $enddate . "'";
} elseif (!empty($_POST['Sday']) && isset($_POST['Sday'])) {
$sql = $sql . " AND date>='" . $strtdate . "'";
} elseif (!empty($_POST['Eday']) && isset($_POST['Eday']))
$sql = $sql . " AND date<='" . $enddate . "'";
}
if (!empty($_POST['Site']) && isset($_POST['Site'])) {
$sql = $sql . " AND u.site=" . $_POST['Site'];
}
$sql = $sql . " LIMIT $start_from, $per_page";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) >= 1) {
$rowcount = mysqli_num_rows($result);
echo '<legend> ' . $rowcount . ' Records Found !!!</legend>';
echo '<br><br>';
echo "<table class='srchtable'>
<tr>
<th>Picture</th>
<th>Date</th>
<th>User Name</th>
<th>country</th>
<th>Location</th>
<th>Site</th>
<th>Comment</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td> <img src='" . $row['picture'] . "' alt='' style='width:70%; height:auto; border-radius: 50%;'> </td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['user_name'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['site'] . "</td>";
echo "<td>" . $row['comment'] . "</td>";
echo "</tr>";
}
echo "</table>";
$total_pages = ceil($rowcount / $per_page);
echo "<center><a href='?page=1'>" . 'First Page' . "</a> ";
for ($i = 1; $i <= $total_pages; $i++) {
echo "<a href='?page=" . $i . "'>" . $i . "</a> ";
}
echo "<a href='?page=$total_pages'>" . 'Last Page' . "</a></center> ";
} else {
echo '<p>No Results Found !!!</p>';
}
}
}
?>
As I said in my comments, for displaying pagination links:
You're counting total number of rows but incorporating LIMIT and OFFSET clauses in your SELECT query, this won't give the correct number of row count. Your SELECT query should not contain this part, ... LIMIT $start_from, $per_page.
Since you're filtering the results based on several $_POST data, you should incorporate those conditions in your pagination links as well, otherwise when you visit a different page(through pagination link), you won't get the desired result, and that's because $_POST data will not be retained when you hop from page to page. Better that you change the method of your <form> from POST to GET, because in this way it'd be easier for you to catch and manipulate things when you hop from one page to another using pagination links.
So based on the above points, your code should be like this:
$per_page = 5;
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page = 1;
}
$start_from = ($page - 1) * $per_page;
if (!empty($_GET['form_val']) && isset($_GET['form_val'])) {
$_GET['form_val'] = 0;
$sql = "SELECT u.log_id , u.user_name, s.site, u.date ,u.comment , l.location, e.picture FROM `pool` u, `location_all` l , `site_all` s JOIN db2.user e
where l.location_id = u.location and s.site_id = u.site and e.user_id = u.user_id";
if (!empty($_GET['Location']) && isset($_GET['Location'])) {
$sql = $sql . " AND location =" . $_GET['Location'];
}
$strtdate = $_GET['Sday'];
$enddate = $_GET['Eday'];
if (!empty($_GET['Sday']) && isset($_GET['Sday']) && !empty($_GET['Eday']) && isset($_GET['Eday'])) {
$sql = $sql . " AND date between '" . $strtdate . "' and '" . $enddate . "'";
} elseif (!empty($_GET['Sday']) && isset($_GET['Sday'])) {
$sql = $sql . " AND date>='" . $strtdate . "'";
} elseif (!empty($_GET['Eday']) && isset($_GET['Eday'])) {
$sql = $sql . " AND date<='" . $enddate . "'";
}
if (!empty($_GET['Site']) && isset($_GET['Site'])) {
$sql = $sql . " AND u.site=" . $_GET['Site'];
}
$data_query = $sql . " LIMIT $start_from, $per_page";
$result = mysqli_query($conn, $data_query);
if (mysqli_num_rows($result) >= 1) {
$rowcount = mysqli_num_rows($result);
echo '<legend> ' . $rowcount . ' Records Found !!!</legend>';
echo '<br><br>';
echo "<table class='srchtable'>
<tr>
<th>Picture</th>
<th>Date</th>
<th>User Name</th>
<th>country</th>
<th>Location</th>
<th>Site</th>
<th>Comment</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td> <img src='" . $row['picture'] . "' alt='' style='width:70%; height:auto; border-radius: 50%;'> </td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['user_name'] . "</td>";
echo "<td>" . $row['country'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['site'] . "</td>";
echo "<td>" . $row['comment'] . "</td>";
echo "</tr>";
}
echo "</table>";
$query_result = mysqli_query($conn, $sql);
$total_rows = mysqli_num_rows($query_result);
$total_pages = ceil($total_rows / $per_page);
parse_str($_SERVER["QUERY_STRING"], $url_array);
unset($url_array['page']);
$url = http_build_query($url_array);
?>
<center>First Page
<?php
for ($i = 1; $i <= $total_pages; $i++) {
?>
<?php echo $i; ?>
<?php
}
?>
Last Page</center>
<?php
} else {
echo '<p>No Results Found !!!</p>';
}
}

PHP Pagination for MySQL database - display the first page by default

Code:
$totalItemsRequired = 8;
$query = "SELECT * FROM fruits ORDER BY origin ASC ";
$result = mysqli_query($connection, $query);
if ($result == false)
{
echo "<p>Selecting all fruits failed.</p>";
}
else
{
$totalRecords = mysqli_num_rows($result);
$totalPages = ceil($totalRecords / $totalItemsRequired);
echo "<p>Page: ";
for ($i = 1; $i <= $totalPages; $i++)
{
echo "<a href='?page=" . $i . "'>" . $i . "</a> ";
}
echo "</p>";
if (isset($_GET['page']))
{
$currentPageNum = $_GET['page'];
$offset = ($currentPageNum - 1) * $totalItemsRequired;
$query = "SELECT * FROM fruits " . "LIMIT " . $offset . ", " . $totalItemsRequired;
$result = mysqli_query($connection, $query);
if ($result == false)
{
echo "<p>Selecting subset (page) of fruits failed.</p>";
}
else
{
echo "<ul>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<li>" . $row["id"] . "," . $row["name"] . ", " . $row["origin"] . ", " . $row["stock"] . "</li>";
}
echo "</ul>";
}
}
else
{
echo
// By default, load first page of records here
}
}
?>
Hi, I'm trying to load the first page of records by default where I have put the comment. There are no problems with the code, and the initial output is good. I'm just not sure how to show by default. Can anyone help please?
EDIT: Can anyone help?
Why not use LIMIT clause in your MySQL statement?
SELECT * FROM fruits ORDER BY origin ASC LIMIT 8 //First 8 rows of the table
SELECT * FROM fruits ORDER BY origin ASC LIMIT 8,8 //Second 8 rows
SELECT * FROM fruits ORDER BY origin ASC LIMIT 16,8 //Third 8 rows
In General:
LIMIT offset,row_count will return row_count rows starting from offset+1 row.
Instead of if statement, you should just be able to change
$currentPageNum = $_GET['page'];
$offset = ($currentPageNum - 1) * $totalItemsRequired;
to
$currentPageNum = isset($_GET['page']) ? $_GET['page'] : 0;
$offset = $currentPageNum > 0 ? (($currentPageNum - 1) * $totalItemsRequired) : 0;
Full code:
<?php
$totalItemsRequired = 8;
$query = "SELECT * FROM fruits ORDER BY origin ASC ";
$result = mysqli_query($connection, $query);
if ($result == false)
{
echo "<p>Selecting all fruits failed.</p>";
}
else
{
$totalRecords = mysqli_num_rows($result);
$totalPages = ceil($totalRecords / $totalItemsRequired);
echo "<p>Page: ";
for ($i = 1; $i <= $totalPages; $i++)
{
echo "<a href='?page=" . $i . "'>" . $i . "</a> ";
}
echo "</p>";
$currentPageNum = isset($_GET['page']) ? $_GET['page'] : 0;
$offset = $currentPageNum > 0 ? (($currentPageNum - 1) * $totalItemsRequired) : 0;
$query = "SELECT * FROM fruits " . "LIMIT " . $offset . ", " . $totalItemsRequired;
$result = mysqli_query($connection, $query);
if ($result == false)
{
echo "<p>Selecting subset (page) of fruits failed.</p>";
}
else
{
echo "<ul>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo "<li>" . $row["id"] . "," . $row["name"] . ", " . $row["origin"] . ", " . $row["stock"] . "</li>";
}
echo "</ul>";
}
}
}
?>

MYSQL PHP pagination not working links

I'm trying to make a pagination, i've got next code but i cant get it working.
<?php
$link = mysqli_connect("localhost", "", " ", "");
if($link === false) { die('<span class="rosu">EROARE:</span> Nu s-a putut realiza conexiunea la baza de date.<br/><br/>Va rog verificati conexiunea pentru baza de date.<br/>' . mysqli_connect_error()); }
$num_rec_per_page=10;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sql = "SELECT * FROM My_Contracte WHERE contract_sters='nu' ORDER BY id_contract DESC LIMIT $start_from, $num_rec_per_page";
$rs_result = mysql_query ($sql); //run the query
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '<table id="contracte">';
echo "<tr>";
echo "<th>EDT</th>";
echo "<th>Numar Contract</th>";
echo "<th>C</th>";
echo "<th>Data Realizare</th>";
echo "<th>Nume Firma</th>";
echo "<th>Nume Locatie</th>";
echo "<th>Zona Judet</th>";
echo "<th>Servicii</th>";
echo "<th>Suma Plata</th>";
echo "<th>PER. CTR.</th>";
echo "<th>Nume Contact</th>";
echo "<th>Telefon</th>";
echo "<th>E</th>";
echo "<th>T</th>";
echo "<th>W</th>";
echo "<th>DEL</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td class='editbutton'><a href='modifica.php?ID=" . $row['id_contract'] . "'><img src='images/edit.png'></img></a></td>";
echo '<td>' . $row['numar_contract'] . ' <img src="images/link.png" width="14px"></img></td>';
echo "<td><a href='pdf/" . $row['link_contract_pdf'] . "' target='_blank'><img src='images/pdf.png' width='20px'></img></a></td>";
echo "<td>" . $row['expirare_contract'] . "</td>";
echo "<td>" . $row['nume_firma'] . "</td>";
echo "<td>" . $row['nume_locatie'] . "</td>";
echo "<td>" . $row['zona_judet_oras'] . "</td>";
echo "<td>" . $row['servicii_oferite'] . "</td>";
echo "<td>" . $row['suma_de_plata'] . "</td>";
echo "<td>" . $row['perioada_contract'] . "</td>";
echo "<td>" . $row['nume_contact'] . "</td>";
echo "<td>" . $row['telefon_contact'] . "</td>";
echo '<td><img src="images/email.png"></img></td>';
echo '<td><img src="images/turvirtual.png"></img></td>';
echo '<td><img src="images/website.png"></img></td>';
echo "<td class='deletebutton'><img src='images/delete.png'></img></td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
} else { print ('<span class="rosu">EROARE!</span> Nu am gasit contracte in baza de date.'); }
} else { print ('<span class="rosu">EROARE!</span> Nu s-a putut executa comada de listare a contractelor.<br/><br/><b>Motivul pentru care nu s-a putut accesa tabelul: </b>') . mysqli_error($link); print '.'; }
?>
<?php
$sql = "SELECT * FROM My_Contracte WHERE contract_sters='nu'";
$total_records = mysql_num_rows($sql); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='lista.php?page=1'><div class='pagina'>1</div></a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='lista.php?page=".$i."'><div class='pagina'>".$i."</div></a> ";
};
echo "<a href='lista.php?page=$total_pages'><div class='pagina'>$total_pages</div></a> "; // Goto last page
?>
The problem is that i get it paginated but it dosnt show right links. so i think the problem is in the next code:
<?php
$sql = "SELECT * FROM My_Contracte WHERE contract_sters='nu'";
$total_records = mysql_num_rows($sql); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='lista.php?page=1'><div class='pagina'>1</div></a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='lista.php?page=".$i."'><div class='pagina'>".$i."</div></a> ";
};
echo "<a href='lista.php?page=$total_pages'><div class='pagina'>$total_pages</div></a> "; // Goto last page
?>
Thank you!
=
EDIT:
[02-Oct-2015 12:18:57 Europe/Bucharest] PHP Warning: mysql_num_rows() expects parameter 1 to be resource, string given in /lista.php on line 81
I get this error in error_log.
81 line is:
$total_records = mysql_num_rows($sql);
Try this i guess you already put link for first and last page and again you are doing that in loop.
for ($i=2; $i<$total_pages; $i++) {
echo "<a href='lista.php?page=".$i."'><div class='pagina'>".$i."</div> </a> ";
};
I got it working like this:
<?php
include("db.php");
$sql = mysql_query("SELECT COUNT(id_contract) FROM My_Contracte WHERE contract_sters = 'nu'");
$total_records = mysql_result($sql, 0);
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='lista.php?page=1'><div class='pagina'>1</div></a> ";
for ($i=2; $i<=$total_pages; $i++) {
echo "<a href='lista.php?page=".$i."'><div class='pagina'>".$i."</div></a> ";
};
?>

PHP - MySQL to PDO

So I decided to finally move over to PDO instead of using the old mysql_
But I noticed my site is loading slower. It's a table with 500 lines, and with my mysql_ queries it loaded slightly faster (0.5-1 second faster).
I wonder if it's just the way PDO works or if I've made some mistake somewhere. I did not change much from MySQL to PDO.
Here is my original mysql_ code:
<?php
$sql = mysql_query("SELECT * FROM rookstayers ORDER BY level DESC LIMIT 0, 500");
$id = 1;
$last_player_lvl = '';
while($row = mysql_fetch_array($sql)){
$name = $row['name'];
$level = $row['level'];
$world = $row['world'];
$account = $row['accountstatus'];
$status = $row['onlinestatus'];
$country = $row['country'];
$lastlogindate = $row['lastlogin'];
$lastlogin2 = utf8_decode($lastlogindate);
$lastlogin = str_replace("?", " ", $lastlogin2);
$onrow = '';
$typeServ = '';
$Date = $lastlogin;
$Date = substr($Date, 0, strpos($Date, " CE"));
$now = date('Y-m-d');
$datetime1 = new DateTime($Date);
$datetime2 = new DateTime($now);
$interval = $datetime1->diff($datetime2);
$difference = $interval->format('%a days ago');
$player_name = urlencode($name);
if ($status == 1){
$status = 'Online';
$onrow = 'online';
} else {
$status = 'Offline';
$onrow = 'offline';
}
if ($account == 'Premium Account'){
$account = 'Premium';
} else {
$account = 'Free';
}
if ($world == 'Aurora' || $world == 'Aurera'){
$typeServ = 'activer';
} else {
$typeServ = '';
}
echo "<tr class=" . $typeServ . ">";
echo "<td align='right'>" . ( ($last_player_lvl == $row['level']) ? '' : $id ) . "</td>";
echo "<td align='center'><img src='../img/flags/" . $country . ".gif'></td>";
echo "<td><div class='". $onrow ."'></div></td>";
echo "<td><a href='../char/" . $player_name . "' class='playerlink'>" . $name . "</a></td>";
echo "<td>" . $level . "</td>";
echo "<td><a href='../world/" . $world ."' class='worldlink'>" . $world . "</a></td>";
echo "<td>"; if ($difference == 0){ echo "Today"; } elseif($difference == 1) { echo "Yesterday"; } else { echo $difference; } echo "</td>";
echo "<td>" . $account . "</td>";
echo "</tr>";
// Check if there are duplicate levels, if so, give them the same rank
if($last_player_lvl == $row['level']){
$id = $id;
}else{
$id++;
}
$last_player_lvl = $row['level'];
}
echo "</tbody>";
echo "</table>";
?>
and here is my PDO code
<?php
$sql = 'SELECT * FROM rookstayers ORDER BY level DESC LIMIT 0, 500';
$id = 1;
$last_player_lvl = '';
foreach ($db->query($sql) as $row) {
$name = $row['name'];
$level = $row['level'];
$world = $row['world'];
$account = $row['accountstatus'];
$status = $row['onlinestatus'];
$country = $row['country'];
$lastlogindate = $row['lastlogin'];
$lastlogin2 = utf8_decode($lastlogindate);
$lastlogin = str_replace("?", " ", $lastlogin2);
$onrow = '';
$typeServ = '';
$Date = $lastlogin;
$Date = substr($Date, 0, strpos($Date, " CE"));
$now = date('Y-m-d');
$datetime1 = new DateTime($Date);
$datetime2 = new DateTime($now);
$interval = $datetime1->diff($datetime2);
$difference = $interval->format('%a days ago');
$player_name = urlencode($name);
if ($status == 1){
$status = 'Online';
$onrow = 'online';
} else {
$status = 'Offline';
$onrow = 'offline';
}
if ($account == 'Premium Account'){
$account = 'Premium';
} else {
$account = 'Free';
}
if ($world == 'Aurora' || $world == 'Aurera'){
$typeServ = 'activer';
} else {
$typeServ = '';
}
echo "<tr class=" . $typeServ . ">";
echo "<td align='right'>" . ( ($last_player_lvl == $row['level']) ? '' : $id ) . "</td>";
echo "<td align='center'><img src='../img/flags/" . $country . ".gif'></td>";
echo "<td><div class='". $onrow ."'></div></td>";
echo "<td><a href='../char/" . $player_name . "' class='playerlink'>" . $name . "</a></td>";
echo "<td>" . $level . "</td>";
echo "<td><a href='../world/" . $world ."' class='worldlink'>" . $world . "</a></td>";
echo "<td>"; if ($difference == 0){ echo "Today"; } elseif($difference == 1) { echo "Yesterday"; } else { echo $difference; } echo "</td>";
echo "<td>" . $account . "</td>";
echo "</tr>";
// Check if there are duplicate levels, if so, give them the same rank
if($last_player_lvl == $row['level']){
$id = $id;
}else{
$id++;
}
$last_player_lvl = $row['level'];
}
echo "</tbody>";
echo "</table>";
?>
maybe something to improve when it comes to the PDO part?
You are executing the query on every iteration of your foreach loop. See update.
Try replacing
foreach ($db->query($sql) as $row) { ...
with
$result = $db->query($sql);
foreach ($result as $row) {
Update: #mario is right. The foreach does't evaluate the expression on each iteration. I can't seem to find a conclusive answer as to why this would have solved the OPs issue; I still think there is something to it, but even in my own tests it seems that using the variable doesn't seem to have any significant effect on performance. If anyone has any more details to add, please do. :)

Else statement doesn't work in option select

I am trying to implement a dropdown search option. All my search results are working. All the commands that I have assigned to if statements work, but when it does to else it deosn't work.
Here is my code:
if(isset($_REQUEST['submit'])){
$opt = $_POST['opt'];
if($opt==1){//if opt = 1
$sqle = "SELECT * FROM tbl_events WHERE title LIKE '%{$keywords}%'";
$resulte = mysql_query($sqle,$con) or die(mysql_error());
while($row=mysql_fetch_array($resulte)){
echo "<h4>" . $row['title'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}else if($opt==2){//if opt = 2
$sqls = "SELECT * FROM tbl_games WHERE games_name LIKE '%{$keywords}%'";
$results = mysql_query($sqls,$con)or die(mysql_error());
while($row=mysql_fetch_array($results)){
echo "<h4>" . $row['games_name'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}else{
echo "Your Searched keyword did not match";
}
}
What to do?
Try this: Take a flag to check if record exists.
$flag = false;
if($opt==1){//if opt = 1
$sqle = "SELECT * FROM tbl_events WHERE title LIKE '%{$keywords}%'";
$resulte = mysql_query($sqle,$con) or die(mysql_error());
if(mysql_num_rows($resulte) > 0) {
$flag = true;
while($row=mysql_fetch_array($resulte)){
echo "<h4>" . $row['title'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}
}else if($opt==2){//if opt = 2
$sqls = "SELECT * FROM tbl_games WHERE games_name LIKE '%{$keywords}%'";
$results = mysql_query($sqls,$con)or die(mysql_error());
if(mysql_num_rows($resulte) > 0) {
$flag = true;
while($row=mysql_fetch_array($results)){
echo "<h4>" . $row['games_name'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}
}
if(!$flag){
echo "Your Searched keyword did not match";
}

Categories