Sort and Pagination combined, PHP with SQL - php

I've got a CV database, you can see the fields below and they are pretty standard. Retrieval is done by a simple form sending the information into an SQL database.
I was happy with my simple system till I was flooded with over 500 applicants in my inbox. My previous system allowed me to view the applicants only one by one which would have taken forever...
What I'm trying to achieve is a simple backend page similar to the phpmyadmin of the table view. (no i don't want to just use phpmyadmin as i'd like to give the CV sifting task to other employees)
Basically the concept is to display the table like an excel, allow sorting by clicking on headers, pagination [20 rows per page] and a check box to delete row.
I'm ok with asking for some help as I have put alot of effort into trying to figure this out ;)
So far what i've got is:
The sorting works no problem, clicking on one of the headers spits out localhost/mena/new3.php?sort=fname to the address bar and parses the correct Sql query and sorts the page.
The pagination so far does not work. The page displays all 815 candidates. It is providing the numbered links 1-42 that when clicked on result in the address bar changing to localhost/new3.php?page=2 but 0 change.
Also for the life of me i can't see how to include the php delete into this..
9 yo pseudo code idea of it is :
//Input the rows from SQL
While($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> $checkbox1
if checkbox1=true then mysqli_query($con,"DELETE FROM cv WHERE .$row[].");
echo "<td>" . $row['title'] .
My code so far:
<?php
$con=mysqli_connect("localhost","root","","test_db-jil");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Pagination
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 20;
// Sort, from headers.
if(isset($_REQUEST['sort'])){
if($_GET['sort'] == "title"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY title");
}
elseif($_GET['sort'] == "fname"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY fname");
}
elseif($_GET['sort'] == "lname"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY lname");
}
elseif($_GET['sort'] == "gender"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY gender");
}
elseif($_GET['sort'] == "dob"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY dob");
}
elseif($_GET['sort'] == "nationality"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY nationality");
}
elseif($_GET['sort'] == "language"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY language");
}
elseif($_GET['sort'] == "phone"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY phone");
}
elseif($_GET['sort'] == "email"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY email");
}
elseif($_GET['sort'] == "uni"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY uni");
}
elseif($_GET['sort'] == "prog"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY prog");
}
elseif($_GET['sort'] == "graddate"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY graddate");
}
elseif($_GET['sort'] == "startdate"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY startdate");
}
elseif($_GET['sort'] == "grad"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY grad");
}
else{
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY fname");
}
}
else{ // Default if no parameters passed
$result = mysqli_query($con,"SELECT * FROM cv");
}
//Table of Content
echo "<table border='1'>
<tr>
<th><a href=new3.php?sort=title>Title</a></th>
<th><a href=new3.php?sort=fname>First Name</a></th>
<th><a href=new3.php?sort=lname>Last Name</a></th>
<th><a href=new3.php?sort=gender>Gender</a></th>
<th><a href=new3.php?sort=dob>Date Of Birth</a></th>
<th><a href=new3.php?sort=nationality>Nationality</a></th>
<th><a href=new3.php?sort=language>Language</a></th>
<th><a href=new3.php?sort=phone>Phone No</a></th>
<th><a href=new3.php?sort=email>Email</a></th>
<th><a href=new3.php?sort=uni>University</a></th>
<th><a href=new3.php?sort=prog>Program</a></th>
<th><a href=new3.php?sort=graddate>Graduated</a></th>
<th><a href=new3.php?sort=startdate>Start Date</a></th>
<th><a href=new3.php?sort=grad>Applying for</a></th>
<th>CV File</th>
</tr>";
//Input the rows from SQL
While($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['dob'] . "</td>";
echo "<td>" . $row['nationality'] . "</td>";
echo "<td>" . $row['language'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['uni'] . "</td>";
echo "<td>" . $row['prog'] . "</td>";
echo "<td>" . $row['graddate'] . "</td>";
echo "<td>" . $row['startdate'] . "</td>";
echo "<td>" . $row['grad'] . "</td>";
echo "<td>" . $row['cvfilename'] ."</td>";
echo "</tr>";
}
echo "</table>";
//Get total count of rows then ceil divide by 20 as pages
$sql = "SELECT COUNT(*) as 'num' FROM cv";
$total_pages = $con->query($sql) or die(mysqli_error($connection));
$row = $total_pages->fetch_assoc();
$total_pages = ceil($row['num'] / 20);
for ($i=1; $i<=$total_pages; $i++) {
//Can I ?page= and ?sort= ??????
echo "<a href='new3.php?page=".$i."'>".$i."</a> ";
};
mysqli_close($con);
?>
Recap, please help me fix pagination, have it work with sort and finally add a delete check box to each row. :)

You know you can optimize that entire block of "else if" statements by just assigning the
$_GET to a variable:
$type = $_GET;
Then use that in your mysqli:
$result = mysqli_query($con, "SELECT * FROM cv ORDER BY $type");
To limit your results use LIMIT:
$result = mysqli_query($con, "SELECT * FROM cv ORDER BY $type LIMIT 20, $page");
20 = how many to return
$page = where you want the results to start from

Related

Data from mysql is not getting retrieved on every page refresh

Iam trying to fetch the random data from mysql database, but it only fetches the same row on page refresh
I tried to run the query to get the random single row data from mysql and display on the webpage using php, but it only retrieving only the same row every time
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1
<?php
$link = mysqli_connect("host", "username", "password", "db_name");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>email_md5</th>";
echo "<th>age_group </th>";
echo "<th>age</th>";
echo "<th>income</th>";
echo "<th>Income_group </th>";
echo "<th>gender</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['email_md5'] . "</td>";
echo "<td>" . $row['age_group'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['income'] . "</td>";
echo "<td>" . $row['Income_group'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
I need the random row data to be displayed everytime the page is refreshed. Will really be helpful if anyone can suggest be the best solution.
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND()
LIMIT 1";
Change the line to
$randomv=rand(min,max);
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY $randomv
LIMIT 1";
Here is my implementation in another case where I have to choose from a random id available - Yii 2 Framework
$prodcutids= \app\models\TblProduct::find()->all();
$targetproduct= ArrayHelper::map($prodcutids, 'id','id');
$productdetails= \app\models\TblProduct::findOne(['id'=>array_rand($targetproduct)]);
$productseriesname= \app\models\TblSeries::findOne(['id'=>$productdetails['Serie']]);
Or if you have an id column
$sql = "SELECT * FROM identity_explorer_demographics WHERE id=$randomv
LIMIT 1";
rand(min,max)
min specifies the lowest value that will be returned.
max specifies the highest value to be returned.
You mix it with PHP
$sql = 'SELECT * FROM `identity_explorer_demographics`';
//Perform query and parse result, E.G $sql = db::query($sql);
function getRandomRow($sql) {
$random_row = count(0, count($sql));
foreach($sql as $row => $result) {
if ($row == $random_row) {
return $row;
}
}
}

Select Data by Id PHP

I have trouble to select a set of specific data using ID from the database. For example, employee one has a unique id of e000000001, when I click the view button in the index will lead to employee detail page which shows the detail of that particular employee instead of all the employees' detail. Thank you.
//from index.php page
<?php
require_once 'db/dbEmpList.php';
$sqlStr = "SELECT * FROM employees;";
$result = $connection->query($sqlStr);
if ($result->num_rows > 0) {
echo "<table class='table table-sm'><thread><tr><th>Full Name</th><th>Employee ID</th><th>Position</th><th>View Employee's Details</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>"
. $row["empName"]. "</td><td>"
. $row["empID"]. "</td><td>"
. $row["position"]. "</td>"
. "<td> <a href='employeedetail.php?id={$row["empID"]}'>View</a>"
. "</td></tr>";
}
}
// from employee page
require_once 'db/dbEmpDetail.php';
$sql = "SELECT * FROM employees where empID = '{$row["empID"]}' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>' .'<td>' .$row["empName"].'</td>'.'<td>'. $row["position"].'</td>' .'<td>'.$row["empNRIC"].'</td>' .'<td>'.$row["empID"].'</td>' .'<td>'.$row["empEmail"].'</td>' .'<td>'.$row["empPwd"].'</td>' . "</tr>";
}
} else {
echo "0 results";
}
mysqli_close($connection);
?>
// FROM EMPLOYEE PAGE
The way you retrieve URL query string is wrong. You should be using $_GET to get the query string from URL. In your case it should be $_GET['id']. See the code below:
require_once 'db/dbEmpDetail.php';
$employeeid = trim(mysqli_real_escape_string($_GET['id']));
$sql = "SELECT * FROM employees where empID = '".$employeeid."' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>' .'<td>' .$row["empName"].'</td>'.'<td>'. $row["position"].'</td>' .'<td>'.$row["empNRIC"].'</td>' .'<td>'.$row["empID"].'</td>' .'<td>'.$row["empEmail"].'</td>' .'<td>'.$row["empPwd"].'</td>' . "</tr>";
}
}
else {
echo "0 results";
}
mysqli_close($connection);
?>

output data based on two tables

I need to output a table based on two other tables as shown below:
case: there are two table "tbl_schedule" and "tbl_report"
this is my script:
$sql = mysql_query("SELECT*, count(*) as schedule_date FROM mst_schedule WHERE schedule_date LIKE '%$date' GROUP BY schedule_account") or die (mysql_error());
while ($data = mysql_fetch_array($sql)) {
$account = schAccount($data['schedule_account']);
$sql2 = mysql_query("SELECT * FROM trn_reportsch WHERE schedule_id='$data[schedule_id]' GROUP BY schedule_id");
echo "<tr>";
echo "<td>".ucfirst($account['admin_fullname'])."</td>";
while ($data2 = mysql_fetch_array($sql2)) {
echo "<td>".$data2['rating']."</td>";
}
echo "<td>".$data['schedule_date']."</td>";
echo "</tr>";
}
So far I don't get the desired output. How should I change the script?
Your code is almost correct.
Add following lines:
$sql = mysql_query("SELECT*, count(*) as schedule_date FROM mst_schedule WHERE schedule_date LIKE '%$date' GROUP BY schedule_account") or die(mysql_error());
while ($data = mysql_fetch_array($sql)) {
$account = schAccount($data['schedule_account']);
$sql2 = mysql_query("SELECT * FROM trn_reportsch WHERE schedule_id='$data[schedule_id]' GROUP BY schedule_id");
echo "<tr>";
echo "<td>" . ucfirst($account['admin_fullname']) . "</td>";
$bad = $good = $vGood = 0; // <-- ADD THIS LINE
while ($data2 = mysql_fetch_array($sql2)) {
if($data2['rating'] <=2){ // BAD
$bad++;
} else if($data2['rating'] <= 3){ // GOOD
$good++;
} else if($data2['rating'] > 3){ // VERY GOOD
$vGood++;
}
}
echo "<td>" . $bad . "</td>"; // Display the final value for bad
echo "<td>" . $good . "</td>"; // Display the final value for good
echo "<td>" . $vGood . "</td>"; // Display the final value for very good
echo "<td>" . $data['schedule_date'] . "</td>";
echo "</tr>";
}

search results in table with rows limit php

I created a web site and i added search option which show search results in table, i want to limit rows number to 5 by page please help me to do that:
i would like also to make search results in random sort for each search operation, not the same results are shown on the first page each search :
this is my search code :
$query = mysql_query("SELECT * FROM table WHERE company LIKE '$company' and activity LIKE '$activity'");
echo "<h3>search results</h3><p>";
echo "<table border='1' align='center' >
<tr>
<th>phone</th>
<th>city</th>
<th>activity</th>
<th>company</th>
</tr>";
while($row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>" . $row['phone']. "</td>";
echo "<td>" . $row['city']. "</td>";
echo "<td>" . $row['activity']. "</td>";
echo "<td>" . $row['company']. "</td>";
echo "</tr>";
}
echo "</table>";
$anymatches=mysql_num_rows($result );
if ($anymatches == 0)
{
echo "<h3>sorry no results</h3>";
}
?>
thank you.
Change your query first into
$query = mysqli_query($con,"SELECT * FROM table WHERE company LIKE '%$company%' and activity LIKE '%$activity%' ORDER BY RAND()");
We can use a counter to limit the fetching to 5.
$counter=1;
while($row = mysqli_fetch_array($query)){
if($counter<6){
echo "<td>" . $row['phone']. "</td>";
echo "<td>" . $row['city']. "</td>";
echo "<td>" . $row['activity']. "</td>";
echo "<td>" . $row['company']. "</td>";
}
else {
/* NOTHING TO DO */
}
$counter=$counter+1;
} /* END OF WHILE LOOP */
$anymatches=mysqli_num_rows($result);
if ($anymatches == 0)
{
echo "<h3>sorry no results</h3>";
}
OR you can try this, just changing your query into:
$query = mysqli_query("SELECT * FROM table WHERE company LIKE '%$company%' and activity LIKE '%$activity%' ORDER BY RAND() LIMIT 5");
Please make it clear, if you want to show only 5 results or a pagination with 5 rows per page.
If pagination is what you're looking for:
We should start by storing the data first into a table storage. For example we have a table named search with even just one field, searchfield.
$searchword=mysqli_real_escape_string($con,$_POST['searchword']);
mysqli_query($con,"UPDATE search SET searchfield='$searchword'");
/* this is where you store your search text for later purposes */
And we'll fetch it right away (Don't get me wrong, this is for the pagination purposes)
$selectsearch = "SELECT * FROM search";
$querysearch = mysqli_query($con, $selectsearch) or die(mysqli_error($selectsearch));
while($rows = mysqli_fetch_array($querysearch)){
$search = $rows['searchfield'];
}
$query = "SELECT * FROM table WHERE company LIKE '%$search%' OR activity LIKE '%$search%'"; /* do your query search */
$result = mysqli_query($con, $query);
$count = mysqli_num_rows($result);
$r = mysqli_fetch_row($result);
$numrows = $r[0];
echo '<b> '.$count.' result/s found for "'.$search.'"</b>';
$rowsperpage = 5;
$totalpages = ceil($count / $rowsperpage);
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
$currentpage = (int) $_GET['currentpage'];
} else {
$currentpage = 1;
}
if ($currentpage > $totalpages) {
$currentpage = $totalpages;
}
if ($currentpage < 1) {
$currentpage = 1;
}
$offset = ($currentpage - 1) * $rowsperpage;
$select="SELECT * FROM table WHERE company LIKE '%$search%' OR activity LIKE '%$search%' LIMIT $offset, $rowsperpage"; /* do the query again but with limit */
$result=mysqli_query($con, $select);
/*start of the table*/
{
echo "<table border='1'>
<tr>
<th>phone</th>
<th>city</th>
<th>activity</th>
<th>company</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['city'] . "</td>";
echo "<td>" . $row['activity']. "</td>";
echo "<td>" . $row['company']. "</td>";
echo "</tr>";
}
echo "</table>";
}
echo '<table border="0"><tr><td>';
/* ***** build the pagination links ***** */
$range = 2;
if ($currentpage > 1) {
$prevpage = $currentpage - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'>Previous</a> ";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " <font color='#546f3e'><b>$x</b></font> ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>Next</a> ";
} // end if
/* ***** end build pagination links ***** */
echo '</td></tr></table>';
You haven't written any pagination code, use MySQL LIMIT , clause.
For ordering randomly, try this:
SELECT * FROM table WHERE company LIKE '$company' and activity LIKE '$activity' ORDER BY RAND()
Start with this. In this you need to pass the page number in URL (Eg yourwebsite/your-php.php?page=0)
$page = $_GET['page'];
$perPage = 5;
$start = $page * $perPage;
$query = mysql_query("SELECT * FROM table WHERE company LIKE '$company' and activity LIKE '$activity' limit " . $start . ',' . $perPage);
echo "<h3>search results</h3><p>";
echo "<table border='1' align='center' >
<tr>
<th>phone</th>
<th>city</th>
<th>activity</th>
<th>company</th>
</tr>";
while($row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>" . $row['phone']. "</td>";
echo "<td>" . $row['city']. "</td>";
echo "<td>" . $row['activity']. "</td>";
echo "<td>" . $row['company']. "</td>";
echo "< /tr>";
}
echo "</table>";
$anymatches=mysql_num_rows($result );
if ($anymatches == 0)
{
echo "<h3>sorry no results</h3>";
}
?>
You need to implement pagination in to this by giving link to different page numbers.
I suggest to use some MVC framework rather than having all data retrieval and view in one file.

Printing two separate SQL table data on the dynamically populated table - PHP

Can someone please help me on the following code? Simply put, I'm trying to get two separate SQL tables' data, one on the horizontal side (brands) and the other (distributors) on the vertical side of a dynamically populated table.
my issue is, if you go through the code I cant get the text boxes populated under each respective brand name I get to display from the database. The text boxes are appearing only for the first brand name column.
My second issue if how do I assign a unique ID or a name to a dynamically populated text box here?
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$sqlq="SELECT * FROM brands";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
$resultq = mysqli_query($db,$sqlq) or die ("SQL Error_er2");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
while($rowq = mysqli_fetch_array($resultq))
{
echo "<td>" . $rowq['bname'] . "</td>";
}
"</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='txt1'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
You're creating loop without relating to eachother, and the same goes for the execution of the querys...
If you want to solve it you will have to nestle the loops together, something like:
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
//Go through all distributors
while($rowq = mysqli_fetch_array($result)) {
echo "<td>" . $rowq['bname'] . "</td>";
//Show all brands for current distributor
$sqlq="SELECT * FROM brands where distributor_id = " . $rowq['rsm'];
$resultBrands = mysqli_query($db,$sql) or die ("SQL Error Brands");
while($row = mysqli_fetch_array($resultBrands))
{
$id = $row['rsm'];
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
//End show all brands for current distributor
}
//End Go through all distributors
A better solution though, would be something like (of course $q has to validated before input inside of query and also binded with bind_param()).
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql = " SELECT * FROM distributors d";
$sql .=" LEFT JOIN brands b ON (d.brand_id = b.brand_id)";
$sql .=" WHERE d.rsm=$q";
$result = mysqli_query($db,$sql) or die ("SQL Error");
echo "<table border='1'>";
while($rowq = mysqli_fetch_array($result))
{
$id = rowq['rsm'];
echo "<tr>";
echo "<td>" . $rowq['dname'] . "</td>";
echo "<td>" . $rowq['bname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
Take notice of the name='textBox[]'. From PHP you can access the variable with $_POST['textBox'] (or $_GET['textBox'] and PHP will return an array).

Categories