JSON pagination blank after include few page - php

Config.php
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','mypass');
define('DB','db_news');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>
Listnews.php
<?php
include'con_db.php';
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
$page= (int) $_GET['page'];
} else {
$page= 1;
}
$all_row = "SELECT COUNT(*) FROM berita";
$data_page = mysqli_query($con, $all_row);
$r = mysqli_fetch_row($data_page);
$numrows = $r[0];
$rowsperpage = 10;
$totalpages = ceil($numrows / $rowsperpage);
//if current page is greater than total pages
if ($page > $totalpages) {
//set current page to last page
$page= $totalpages;
}
//if current page is less than first page
if ($page < 1) {
//set current page to first page
$page= 1;
}
// the offset of the list, based on current page
$offset = ($page - 1) * $rowsperpage;
$query = "SELECT * FROM berita order by id_berita DESC LIMIT $offset, $rowsperpage";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)>0) {
$response["list_data"] = array();
while ($row = mysqli_fetch_assoc($result)) {
$temp = array("id" => $row["id_berita"],
"judul" => $row["judul"],
"isi" => $row["isi_berita"],
"tgl" => $row["tanggal"].' '.$row["jam"],
"dibaca" => $row["dibaca"].' Dibaca',
"url_berita" => $row["judul_seo"],
"gambar" => $row["gambar"]);
array_push($response["list_data"], $temp);
}
if($result){
$response["success"] = 1;
$response["message"] = "Successfully Displayed";
$response["page"] = $page;
$response["total_pages"] = $totalpages;
$data = json_encode($response);
echo $data;
}
else{
$response["success"] = 0;
$response["message"] = "Try Again";
$response["page"] = $page;
$response["total_pages"] = $totalpages;
$data = json_encode($response);
echo $data;
}
}else{
$response["success"] = 2;
$response["message"] = "No Details Found";
$response["page"] = $page;
$response["total_pages"] = $totalpages;
$data = json_encode($response);
echo $data;
}
/*
**$data = json_encode($response);
**echo $data;
*/
?>
after test with postman myhost/news/berita.php?page=1,2,3,4,5,6 it showing json data.
showing json data with page 1-6
then i include page 7 myhost/news/berita.php?page=7 its blank
after incluse page 7
please help me sir, i'm sorry for bad my language

finally done my problem, just add utf8ize function
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
and use it for json_encode
$response["success"] = 1;
$response["message"] = "Successfully Displayed";
$response["page"] = $halaman;
$response["total_pages"] = $totalpages;
$data = json_encode(utf8ize($response));
echo $data;

Related

How to verify hashed password json for android login

How I can let user login from android app, using codeigniter api.
JSON response..
I want use password_hash and password_verify method for more security.
I tryed to password_verify in model, but getting error 1 wrong password. If I debug my app I can see it tries to post password what is not encrypted, but I think this password must be checked in Model.
controller:
public function login() {
$response = array("success" => 0, "error" => 0);
if (isset($_POST['email']) && $_POST['email'] != '') {
$device_token = $_POST['device_token'];
$email = $_POST['email'];
$password = $_POST['password'];
$device_type = $_POST['device_type'];
$data = $this->Registration_model->login($email,$password,$device_token,$device_type);
if ($data) {
$user_id = $data['u']->id;
$status_level = $this->Freelancer_model->service_level($user_id);//Bronze,silver..
$discount = $this->Registration_model->discountDetails($user_id);
if (!empty($discount)) {
$discount = $discount;
} else {
$discount ='';
}
if ($data['u']->approve_status == 1) {
$response["error"] = 0;
$response["success"] = 1;
$response["message"] = "success";
$image = base_url().'upload/'.$data['u']->user_image;
$response["data"]["user_id"] = $data['u']->id;
$response["data"]["user_image"] = $image;
$response["data"]["user_type"] = $data['u']->user_type;
$response["data"]["referral_code"] = $data['u']->referral_code;
$response["data"]["device_token"] = $data['u']->device_token;
$response["data"]["company_name"] = $data['u']->company_name;
$response["data"]["reg_no"] = $data['u']->registration_no;
$response["data"]["first_name"] = $data['u']->first_name;
$response["data"]["last_name"] = $data['u']->last_name;
$response["data"]["dob"] = $data['u']->dob;
$response["data"]["address"] = $data['u']->address;
$response["data"]["lat"] = $data['u']->lat;
$response["data"]["long"] = $data['u']->long;
$response["data"]["mobile"] = $data['u']->mobile;
$response["data"]["email"] = $data['u']->email;
$response["data"]["password"] = $data['u']->password;
$response["data"]["gender"] = $data['u']->gender;
$response["data"]["about"] = $data['u']->about;
$response["data"]["address_acceptance"] = $data['u']->address_acceptance;
$response["data"]["availability"] = $data['u']->availability;
$response["data"]["canceling_policy"] = $data['u']->canceling_policy;
$response["data"]["acceptance"] = $data['u']->acceptance;
$response["data"]["seen_status"] = $data['u']->seen_status; // 0=not, 1=yes
$response["data"]["approv_status"] = $data['u']->approve_status;
$response["data"]["complete_serviceLevel"]= $status_level;
$response["account"] = $data['a'];
$response["discount"] = $discount;
echo json_encode($response);
} else {
$response["error"] = 2;
$response["success"] = 0;
$response["message"] = "User is not approved";
echo json_encode($response);
}
} else {
$response["error"] = 1;
$response["success"] = 0;
$response["message"] = "Enter correct email and password";
echo json_encode($response);
}
} else {
$response["error"]=4;
$response["message"]= "Access denied";
echo json_encode($response);
}
}
model:
public function login($email, $password, $device_token, $device_type) {
$r = $this->db->get_where('registration', array('email'=>$email, 'password'=>$password));
$count = $r->num_rows();
if ($count > 1) {
$this->db->select('id,email,user_type');
$this->db->from('registration');
$this->db->where('email',$email);
$cc = $this->db->get()->result();
$response["error"] = 0;
$response["success"] = 1;
$response["message"] = "Success, Which account does you want to login?";
$response["data"] = $cc;
echo json_encode($response);
die();
} else if ($count == 1) {
$r1 = $r->row();
$id = $r1->id;
$this->db->where('id',$id);
$update =$this->db->update('registration',array('device_token' => $device_token,'device_type' => $device_type));
//$id = $r1->id;
$r2 = $this->db->get_where('accountdetails', array('user_id' => $id))->result();
$data= array(
"u" =>$r1,
"a" =>$r2
);
return $data;
} else {
return false;
}
}

How do i verify query from mysql database before outputing record

In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.

PHP dynamic previous/next links

I have a table called "product".
I'm displaying all the data from PHP product view page by using the id parameter.
With my code:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT * FROM product WHERE id = $id ";
$select_product = $db->query($query);
while($row = $db->fetch_object($select_product)) {
$status = $row->status;
if($status == 'published') {
$title = $row->title;
echo $title;
}
}
I can pull all the data I need. In this example I can echo the title.
But how do I display a dynamic next page link? That goes same for previous link.
When I try with this code:
$query = "SELECT id FROM product";
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
I can see all the pages from that table. In my case they are 20,21,22...28
Next, I've tried like this:
$query = "SELECT id from product";
$select_ids = $db->query($query);
if($select_ids->num_rows > 0) {
$next = $id + 1;
echo 'Next';
} else {
}
With this code, my "next" link successfully goes to the next page. But, when it finishes with the result, in this case when I'm on page 28, the next dynamic link goes to empty page (29). Also this is not a good approach, because if some page, let's say 25 is deleted, the next link won't skip that page.
How can I improve that dynamic "next" link?
So first of all, you need two queries one for getting the data to display and another for counting the number of rows, also we'll need some additional variables.
Here comes the code:
$page = 1;
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
$numberOfResultsPerPage = 10;
$offset = $numberOfResultsPerPage * ($page - 1)
$count = $db->query("SELECT COUNT(id) as num FROM product");
while($row = $db->fetch_object($count)) {
$numberOfRows = $row->num;
}
$query = "SELECT id FROM product LIMIT ". $offset.", ".$numberOfResultsPerPage;
$select_ids = $db->query($query);
while($row = $db->fetch_object($select_ids)) {
$ids = $row->id;
echo $ids;
}
if($page > 1) {
echo 'Prev';
}
if($page < ceil($numberOfRows / $numberOfResultsPerPage)) {
echo 'Next';
}
UPDATE:
In case you need to just find the next and previous product of the product this is the solution. It is not good if you'll have lots of products but in case the number of products is under 1000 there should not be any problems:
if(isset($_GET['id'])) {
$id = $_GET['id'];
}
$query = "SELECT id from product";
$select_ids = $db->query($query);
$ids = array();
$i = 0;
while($row = $db->fetch_object($select_ids)) {
$ids[$i] = $row->id;
if($row->id == $id) {
$index = $i;
}
$i++;
}
if(isset($ids[$index-1])) {
echo 'Prev';
}
if(isset($ids[$index+1])) {
echo 'Next';
}

How can i get list of news from database with comments

i'm going to make news app for android. i made json_encode to my php file. but i just want to add comments in while. i was search it everywhere but i coulnt find. can you please help me.
Here is my php code
if (!empty($result)) {
// check for empty result
if ($result->num_rows > 0) {
$response["success"] = true;
$response["news"] = array();
while($row = $result->fetch_object()){
$news = array();
$news["id"] = $row->id;
$news["title"] = $row->title;
$news["details"] = $row->short;
$news["thumbURL"] = $thumb.$row->images;
$news["LargeImageURL"] = $big.$row->images;
array_push($response["news"], $news);
}
// echoing JSON response
echo json_encode($response);
} else {
// no news found
$response["success"] = false;
$response["message"] = "No news found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no news found
$response["success"] = false;
$response["message"] = "No news found";
// echo no users JSON
echo json_encode($response);
}
and i want to add item's comments like in photo
http://i.stack.imgur.com/RnaOJ.jpg
I found and its work good. Thanks for your helping.
if (!empty($result)) {
// check for empty result
if ($result->num_rows > 0) {
$response["success"] = true;
$response["news"] = array();
while($row = $result->fetch_object()){
$commentsql = $db->query("SELECT * FROM comment where cid='".$row->id."' order by id desc limit 0,10");
$comments = array();
while($comm = $commentsql->fetch_object()){
$comments[] = array(
'id' => $comm->id,
'text' => $comm->comment
);
}
$news = array();
$news["id"] = $row->id;
$news["title"] = $row->title;
$news["details"] = $row->short;
$news["thumbURL"] = $thumb.$row->images;
$news["LargeImageURL"] = $big.$row->images;
$news["comment"] = $comments;
array_push($response["news"], $news);
}
// echoing JSON response
echo json_encode($response);
} else {
// no news found
$response["success"] = false;
$response["message"] = "No news found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no news found
$response["success"] = false;
$response["message"] = "No news found";
// echo no users JSON
echo json_encode($response);
}

PHP: Reuse JQGrid response for Displaying data in DataTable

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);

Categories