Need some help if possible?
I’m trying to add pagination to my code.. The problem I am getting is the pagination script works perfectly well without the JOIN statement and the JOIN statement works when I exclude the pagination script so they both work just not together.
It counts the results correctly with both scripts together just wont show the data.
The question is how do I get them to work together as I get an error:
Any help would be grateful
ini_set('display_errors', 1);
error_reporting(~0);
$Keyword = null;
if(isset($_POST["term"])){
$Keyword = $_POST["term"];
}
if(isset($_GET["term"])){
$Keyword = $_GET["term"];
}
$sql = "SELECT * FROM table1
INNER JOIN table2 ON (table1.member_id = members.id)
WHERE MATCH (name,location) AGAINST ('%".$Keyword."%' IN NATURAL LANGUAGE MODE)";
$query = mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($query);
$per_page = 2;
$page = 1;
if(isset($_GET["Page"])) {
$page = $_GET["Page"];
}
$prev_page = $page-1;
$next_page = $page+1;
$row_start = (($per_page*$page)-$per_page);
if($num_rows<=$per_page) {
$num_pages =1;
} else if(($num_rows % $per_page)==0) {
$num_pages =($num_rows/$per_page) ;
} else {
$num_pages =($num_rows/$per_page)+1;
$num_pages = (int)$num_pages;
}
$row_end = $per_page * $page;
if($row_end > $num_rows) {
$row_end = $num_rows;
}
$sql .= "SELECT * ORDER BY ID ASC LIMIT $row_start ,$row_end ";
$query = mysqli_query($conn,$sql);
while($result=mysqli_fetch_array($query,MYSQLI_ASSOC)) {
Related
This is mysql connection coding, it is working fine
the same code i wrote with pdo connection,it is not working i'm new to php please help me to get out of this problem.
thanks in advance
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$result = mysqli_query("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysqli_query( $SQL ) or die("Couldn?t execute query.".mysqli_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$responce->rows[$i]['id']=$row[WeekNo].$row[Login];
$responce->rows[$i]['cell']=array($row['WeekNo'],$row['WeekBeginning'],$row['SITE'],$row['Name'],$row['WFH'],$row['Login'],$row['Manager_Login'],$row['Lead'],$row['Cost_center'],$row['Business_Title'],$row['Function'],$row['Workgroup'],$row['Login_time'],$row['ROLE'],$row['Secondary_Skill'],$row['Weekoff'],""); $i++;
}
echo json_encode($responce);
?>
PDO connection code
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'config.php';
if(isset($_GET["nm_mask"]))
$nm_mask = $_GET['nm_mask'];
else
$nm_mask = "";
if(isset($_GET["cd_mask"]))
$cd_mask = $_GET['cd_mask'];
else
$cd_mask = "";
if(isset($_GET["func"]))
$func = $_GET['func'];
else
$func = "";
$where = "WHERE 1=1";
if($nm_mask!='')
$where.= " AND Login LIKE '$nm_mask%'";
if($cd_mask!='')
$where.= " AND Manager_Login LIKE '$cd_mask%'";
if($func!='')
$where.= " AND Function LIKE '$func%'";
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$count = $dbh->exec("SELECT COUNT(*) AS count FROM EmpMasterTB ".$where);
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT * from EmpMasterTB ". $where ." ORDER BY $sidx $sord LIMIT $start , $limit"; /*** The SQL SELECT statement ***/
$stmt = $dbh->query($SQL); /*** fetch into an PDOStatement object ***/
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
/*** echo number of columns ***/
$obj = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($ );
?>
You have missed for loop and you didn't pass response in json_encode().
Please check my below code:
/*** echo number of columns ***/
$objs = $stmt->fetch(PDO::FETCH_OBJ);
/*** loop over the object directly ***/
foreach($objs as $obj)
{
$responce->rows[$i]['id']=$obj->WeekNo.$obj->Login;
$responce->rows[$i]['cell']=array($obj->WeekNo ,$obj->WeekBeginning ,$obj->SITE ,$obj->Name ,$obj->WFH ,$obj->Login ,$obj->Manager_Login ,$obj->Lead ,$obj->Cost_center ,$obj->Business_Title ,$obj->Function ,$obj->Workgroup ,$obj->Login_time ,$obj->ROLE ,$obj->Secondary_Skill ,$obj->Weekoff ); $i++;
}
echo json_encode($responce );
new Query
$query = "SELECT COUNT(*) FROM payments $sCriteria";
$result = mysql_query($query) or die("Error encountered on retrieving logs.");
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
$rows_per_page = 30;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
}
$limit = "LIMIT ".($pageno - 1) * $rows_per_page .",".$rows_per_page;
$rs = mysql_query("SELECT * FROM payments $sCriteria ORDER BY pay_date DESC $limit") or die("Error encountered on retrieving logs.".mysql_error());
$current_rows = mysql_num_rows($rs);
if ($current_rows) {
while ($rows = mysql_fetch_array($rs)) {
echo "<tr>
<td>".date("m/d/Y n:H:s",strtotime($rows["pay_date"]))."</td>
<td>".$rows["po_no"]."</td>
<td>".$rows["or_no"]."</td>
<td>".$rows["sold_to"]."</td>
<td>Php ".number_format($rows["amt_to_pay"],2,".",",")."</td>
<td>Php ".number_format($rows["amt_paid"],2,".",",")."</td>
<td>".$rows["pay_status"]."</td>
**<td>".$rows["verified"]."</td>**
<td><a href='pay_preview.php?id=$iPayID' class='action preview' title='Print Preview'><img src='images/preview.png' class='action_img' /></a></td>
Old Query
$query = "SELECT COUNT(*) FROM payments";
$result = mysql_query($query) or die("Error encountered on retrieving payment details.");
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
$rows_per_page = 10;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
}
if ($pageno < 1) {
$pageno = 1;
}
$limit = "LIMIT ".($pageno - 1) * $rows_per_page .",".$rows_per_page;
$rs = mysql_query("SELECT * FROM payments ORDER BY pay_date DESC, po_id $limit") or die("Error encountered on retrieving payment details.");
$current_rows = mysql_num_rows($rs);
if ($current_rows) {
while ($rows = mysql_fetch_array($rs)) {
$iPayID = $rows["pay_id"];
$iPoID = $rows["po_id"];
$dSubTotal = get_po_subtotal($iPoID);
$sPoNo = get_value("po","po_no","WHERE po_id=$iPoID");
$iDis = get_value("po","discount","WHERE po_id=$iPoID");
$dNet = $dSubTotal - ($dSubTotal * ($iDis/100));
$sStat = $rows["pay_status"];
switch($sStat) {
case "Paid": $sColor = "class='blue'";break;
default: $sColor = "";break;
}
if ($rows["verified"]) {
$sVerified = "Yes";
}
else {
$sVerified = "No <a href='payment_verification.php?id=$iPayID' class='action verify' title='Verify' id='$iPayID'>(verify)</a>";
}
echo "<tr>
<td>".date('Y-m-d',strtotime($rows["pay_date"]))."</td>
<td>".$rows["or_no"]."</td>
<td>$sPoNo</td>
<td>".$rows["sold_to"]."</td>
<td class='right'>Php ".number_format($rows["amt_to_pay"],2,".",",")."</td>
<td class='right'>Php ".number_format($rows["amt_paid"],2,".",",")."</td>
<td $sColor>".$rows["pay_status"]."</td>
<td>$sVerified</td>
<td><a href='pay_preview.php?id=$iPayID' class='action preview' title='Print Preview'><img src='images/preview.png' class='action_img' /></a></td>
</tr>\n";
}
}
My problem is that on my new query I can't change the Verified output to Paid or Unpaid, It stays with a 0 and 1 ** I did also copy and compare it with my old and new query, it just that it didn't work, can someone help me with it? thank you so much.
I would suggest something like as an example to use a condition in mysql:
I your SQL statement specify the columns and don't use SELECT *
SELECT IF(Field > 0,'TRUE','FALSE') AS verified FROM Table
You can add a field to change it to paid or unpaid as well
SELECT IF(Field > 0,'Paid','Unpaid') AS verified FROM Table
Serves as an example. you can add any condition and result output
ALSO
In you code I cannot determine where $sVerified is ever assigned a value?
I am not sure exactly what your asking.. I don't know if your needing to print the value to the page, or if your needing to change it for another query..
Maybe a switch case would work.. Allowing you to change the format to however you need it. Basically converting your old queries result so your new query can handle it..
$value = 0; // or false.. this is your value from first query
$newval = null; // just placeholder for newval in switch
switch($value) {
case 0:
$newval = 'Unpaid';
break;
case 1:
$newval = 'Paid';
break;
default:
$newval = 'Unknown';
}
echo $newval;
I have this issue with pagination.
I have this php code here:
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 15;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
I have this query here:
$query_pag_data = 'SELECT
matching.date,
matching.points,
matching.time,
matching.location,
matching.epos_id,
rbpos_epos.epos_id,
rbpos_epos.location
FROM
matching
LEFT JOIN
rbpos_epos ON matching.epos_id = rbpos_epos.epos_id
WHERE
matching.user_id = ".$id_user." LIMIT $start, $per_page';
I get $start variable is undefined. I guess it has to do with the query because if i put another query more simple it works.
Please help me.
Thanks.
Use double quotes in your query because $start and $per_page are strings not variables
$query_pag_data = "SELECT
matching.date,
matching.points,
matching.time,
matching.location,
matching.epos_id,
rbpos_epos.epos_id,
rbpos_epos.location
FROM
matching
LEFT JOIN
rbpos_epos ON matching.epos_id = rbpos_epos.epos_id
WHERE
matching.user_id = $id_user LIMIT $start, $per_page";
First of all I am using JQGrid in my application. After changing my CSS to Bootstrap CSS.
I have to use DataTable. I want to reuse my controller pages which makes query to display the data in JQGrid.
Here is my controller page.
<?php
require_once("JsonHeader.php");
$at = $_SESSION['abc'];
$start_date = $_SESSION['start_date'];
$end_date = $_SESSION['end_date'];
if ($_SESSION['list'] == '-1') {
$user_query = "";
} else {
$user_list = $_SESSION['list'];
$user_query = " AND a.user_id IN ($list)";
}
$start_date = $_SESSION['start_date'];
$end_date = $_SESSION['end_date'];
if ($_SESSION['list'] == '-1') {
$user_query = "";
} else {
$user_list = $_SESSION['list'];
$user_query = " AND a.user_id IN ($list)";
}
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
$qtype = ''; // Search column
$query = ''; // Search string
if (isset($_GET['searchField'])) {
$qtype = mysql_real_escape_string($_GET['searchField']);
}
if (isset($_GET['searchString'])) {
$query = mysql_real_escape_string($_GET['searchString']);
}
if (isset($_GET['searchOper'])) {
switch ($_GET['searchOper']) {
case 'eq':
$oper = '=';
$query = mysql_real_escape_string($_GET['searchString']);
break;
case 'ne':
$oper = '!=';
$query = mysql_real_escape_string($_GET['searchString']);
break;
case 'cn':
$oper = 'like';
$query = "%".mysql_real_escape_string($_GET['searchString'])."%";
break;
}
}
$searchSql1 = ($qtype != '' && $query != '') ? "and $qtype $oper '$query'" : '';
if (!$sidx)
$sidx = 1; // connect to the database
$result = mysql_query(sprintf("SELECT ae.col1,ae.col2,ae.col3, ae.col4,ae.col5,ae.col6,ae.col7,a.col8,a.col9,r.col10,p.col11
FROM $tablename3 ae,$tableName a, $tablename1 p, $tablename2 r
WHERE ae.col1=$at $searchSql1
AND a.col1 = $at
AND a.col5=r.col5
AND a.col6=p.col6
$user_query"));
$row = mysql_num_rows($result);
$count = $row;
if ($count > 0) {
$total_pages = ceil($count / $limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages)
$page = $total_pages; $start = $limit * $page - $limit; // do not put
$limit * ($page - 1);
$SQL = sprintf("SELECT ae.col1,ae.col2,ae.col3, ae.col4,ae.col5,ae.col6,ae.col7,a.col8,a.col9,r.col10,p.col11
FROM $tablename3 ae,$tableName a, $tablename1 p, $tablename2 r
WHERE ae.col1=$at $searchSql1
AND a.col1 = $at
AND a.col5=r.col5
AND a.col6=p.col6
$query");
$result = mysql_query($SQL) or die("Couldn t execute query." . mysql_error());
$responce = new stdClass();
$responce->page = new stdClass();
$responce->total = new stdClass();
$responce->records = new stdClass();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$responce->rows[$i]['id'] = $row['col1'];
$responce->rows[$i]['cell'] = array($row['col1'], $row['col2'], $row['col3'], $row['col4'], $row['col5'], $row['col6'], $time, $row['col7']);
$i++;
}
echo json_encode($responce);
?>
HOW can I change this for DataTable?.
Please provide me the best way...
Finally I found how to resue my controller page for DataTable. Simply change the post variables in the controller page.
Like
$_GET['page']; By $_REQUEST['sEcho']
$_GET['rows']; By $_REQUEST['iDisplayStart'],$_REQUEST['iDisplayLength']
$_GET['sord']; $_REQUEST['sSortDir_0']
$_GET['searchString']: $_GET['sSearch']:
And some changes the json response like
$ans['iTotalRecords'] = $count;
$ans['iTotalDisplayRecords'] = $count;
$ans['aaData'] = $aadata;
echo json_encode($ans);
I've recently got back into doing some PHP coding but have got stuck on something with PHP Pagination, it would seem that anything I tried either results in it not counting the pages and displaying on one page of results, or just stops at Page 6 and goes no further, I know with the data that is stored in the MySQL database, it should be showing 52 pages of results at 12 per page.
So I'm in need of some help, I thought it was working until I hit the won't go further than Page 6 after putting in 100's of entires into the database.
The code is as follows
<?php
//
//How to print date
//
if($print_date == 1)
{
$print_date = '%d.%m.%Y';
}
elseif($print_date == 2)
{
$print_date = '%m.%d.%Y';
}
elseif($print_date == 3)
{
$print_date = '%W, %M %D %Y';
}
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
} // if
$get_matches = mysql_query("SELECT
O.OpponentName AS hometeam, OP.OpponentName AS awayteam,
LM.LeagueMatchHomeGoals AS goals_home,
LM.LeagueMatchAwayGoals AS goals_away,
LM.LeagueMatchID AS id,
DATE_FORMAT(LM.LeagueMatchDate, '$print_date') AS date
FROM tplls_leaguematches LM, tplls_opponents O, tplls_opponents OP
WHERE O.OpponentID = LM.LeagueMatchHomeID AND
OP.OpponentID = LM.LeagueMatchAwayID AND
LeagueMatchSeasonID LIKE '$defaultseasonid'
ORDER BY LM.LeagueMatchDate");
$get_matches = #mysql_query($SQL) or die("Error Processing Fixtures");
$query_data = mysql_fetch_row($get_matches);
$numrows = $query_data[0];
$rows_per_page = 12;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
} // if
if ($pageno < 1) {
$pageno = 1;
} // if
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$get_matches2 = mysql_query("SELECT
O.OpponentName AS hometeam, OP.OpponentName AS awayteam,
LM.LeagueMatchHomeGoals AS goals_home,
LM.LeagueMatchAwayGoals AS goals_away,
LM.LeagueMatchID AS id,
DATE_FORMAT(LM.LeagueMatchDate, '$print_date') AS date
FROM tplls_leaguematches LM, tplls_opponents O, tplls_opponents OP
WHERE O.OpponentID = LM.LeagueMatchHomeID AND
OP.OpponentID = LM.LeagueMatchAwayID AND
LeagueMatchSeasonID LIKE '$defaultseasonid'
ORDER BY LM.LeagueMatchDate, hometeam $limit",$connection)
or die(mysql_error());
while($row = mysql_fetch_array($get_matches2))
{
?>
More to add, if I take out the first SELECT statement, I get the same result?
Try this out. It's just your code with some minor modifications.
<?php
//
//How to print date
//
switch ($print_date)
{
case 1:
$print_date = '%d.%m.%Y';
break;
case 2:
$print_date = '%m.%d.%Y';
break;
case 3:
$print_date = '%W, %M %D %Y';
}
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
} // if
$clause = "
FROM tplls_leaguematches LM, tplls_opponents O, tplls_opponents OP
WHERE O.OpponentID = LM.LeagueMatchHomeID AND
OP.OpponentID = LM.LeagueMatchAwayID AND
LeagueMatchSeasonID LIKE '$defaultseasonid'
ORDER BY LM.LeagueMatchDate";
$query = "SELECT COUNT(*) as num $clause";
$result = #mysql_query($query) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
$rows_per_page = 12;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
if ($pageno > $lastpage) {
$pageno = $lastpage;
} // if
if ($pageno < 1) {
$pageno = 1;
} // if
$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;
$query = "SELECT
O.OpponentName AS hometeam, OP.OpponentName AS awayteam,
LM.LeagueMatchHomeGoals AS goals_home,
LM.LeagueMatchAwayGoals AS goals_away,
LM.LeagueMatchID AS id,
DATE_FORMAT(LM.LeagueMatchDate, '$print_date') AS date $clause $limit";
$get_matches = mysql_query($query, $connection)
or die(mysql_error());
while($row = mysql_fetch_array($get_matches))
{
?>
It's actually what #g.salakirov suggested but in the context of all the code you supplied. I haven't tested it, but it should work. (Famous last words. :D)
You need to use mysql_num_rows(resource $result) rather than mysql_fetch_row(resource $result) to get the number of rows in here: .
$get_matches = #mysql_query($SQL) or die("Error Processing Fixtures");
$query_data = mysql_fetch_row($get_matches);
$numrows = $query_data[0];
$rows_per_page = 12;
$lastpage = ceil($numrows/$rows_per_page);
$pageno = (int)$pageno;
Alternatively, you can use a "count(*)" query in the beginning to get the number of entries, which will be significantly faster.
For example:
$get_matches = mysql_query("SELECT
count(*) as resultCount
FROM tplls_leaguematches LM, tplls_opponents O, tplls_opponents OP
WHERE O.OpponentID = LM.LeagueMatchHomeID AND
OP.OpponentID = LM.LeagueMatchAwayID AND
LeagueMatchSeasonID LIKE '$defaultseasonid'
ORDER BY LM.LeagueMatchDate");