While reading json data getting null value - php

Using my php page i m reading mysql data and showing in json. Code of php page is --
<?php
function loadData($limit){
require "config.inc.php";
$query = $con->prepare("SELECT * FROM UploadText ORDER BY slno DESC LIMIT $limit ");
$query->execute();
$array = array();
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$id = $data['slno'];
$title = $data['textmsg'];
array_push($array, array(
"id" => $id,
"title" => $title
)
);
}
echo json_encode($array);
}
function loadMoreData($lastId, $limit){
require "config.inc.php";
try{
$query = $con->prepare("SELECT * FROM UploadText WHERE slno < $lastId ORDER BY slno DESC LIMIT $limit ");
$query->execute();
$array = array();
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$id = $data['slno'];
$title = $data['textmsg'];
array_push($array, array(
"id" => $id,
"title" => $title
)
);
}
echo json_encode($array);
} catch(Exception $e){
die($e->getMessage());
}
}
if(isset($_GET['action']) && $_GET['action'] == "apiText"){
$lastId = $_GET['lastId'];
// this is teh limit set in the android java code (LOAD_LIMIT)
$limit = $_GET['limit'];
loadMoreData($lastId, $limit);
} else {
$limit = $_GET['limit'];
loaddata($limit);
}
?>
And this is the output of the above code --
[{"id":"14","title":"A Kid On His Way 2 Home With His Mom\r\nSaw A Couple Kissing On The Road,\r\nHe Suddenly Shouted & Said:\r\nLook Mom look, that boy and girl\r\nAre Fighting For A Chewing GUM."},
{"id":"13","title":null},
{"id":"12","title":null},
{"id":"11","title":null},
{"id":"10","title":"PAPPU : Daddy, have you\never been to Egypt?\nFATHER : No. Why do\nyou ask that?\nPAPPU: Well, where did\nyou get THIS mummy??"},
{"id":"9","title":"Y r u so opposite to me?\nWhen i say tea,u say coffee!\nI say white,u say black!\nI went to dental hospital,u went to mental hospital!\nI came back and u still there!"}]
Not able to understand, why its reading null values.
Data is present in mysql table, but then also reading some null values and some data are shown properly.
This is the structure of my mysql table --

Finally resolved the issue by googling, the issue is encoding problem --
$title = utf8_encode($data['textmsg']);
This resolved the problem.

Related

How to save query in multidimesional array?

I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
include '../inc/dbinfo.inc';
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "################################################# UpdateVendorInvoiceDays.php #################################################" );
$three = 3;
$fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
$getInvoices = $conn->prepare($fetchAllInvoices);
$getInvoices->bind_param("i", $three);
$getInvoices->execute();
$result = $getInvoices->get_result();
$rows = array();
$j = 0;
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]); //Only outputs one row
//UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
$updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
$setDays = $conn->prepare($updateDaysRemaining);
$k = 0; //incrementor
$numberOfEntries = $rows['COUNT(*)'];
for($k;$k<$numberOfEntries;$k++){
$setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
$rows[$k]['VENDORINVOICEID'], $three);
if($setDays->execute()){
error_log('Cron success');
}else{
error_log('Cron fail');
}
}
?>
Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.
There are a couple of simplifications to get all of the rows. Instead of...
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]);
You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);
Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount
and then you can use this alias for the field reference...
$rows['COUNT(*)']
becomes
$rows['rowCount']

Why does my PHP PDO Select in while not working with page limit? Also issue with Array in select

Why does hello not display to the screen, why is the while loop not executed?
Also I have an issue because the array $zipcodeA[$x] may contain random zip codes like 90564 80564 70564 88464 98754 but the database tman may contain info such as 90564 90564 90564 80564 70564 70564 88464 98754. How do I get the select to go through all the zip codes that are in the array $zipcodeA[$x] instead of just pulling info of one of each zip code? The database holds random zip codes and many zip codes can be duplicates, the array only many different zip codes with no duplicates
for($x = 0; $x <= $v; $x++)
{
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc limit :limit");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
$stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$id2 = $row['id'];
$name = $row['name'];
echo 'hello';
}
}
Try to do it like this :
$limit = ($pageno - 1) * $rows_per_page . ',' . $rows_per_page;
for($x = 0; $x <= $v; $x++) {
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve = 'Y' AND zip = :zipp ORDER BY id desc LIMIT " . $limit);
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)) {
$id2 = $result['id'];
$name = $result['name'];
echo 'hello';
}
}
You should replace your limit parameter with a PHP variable:
$stmt = $conn->prepare("SELECT * FROM tman
WHERE approve='Y' AND zip=:zipp
ORDER BY id DESC LIMIT $limiter");
According to the PHP PDO::prepare manual in regard to prepared statements:
Use these parameters to bind any user-input, do not include the
user-input directly in the query.
Since preparing a statement lets you filter user input, these parameters, by design are not allowed to replace any other part of the query that is supposed to be set by a developer. For instance allowing a parameter to replace a table name would provide access to an attacker to use the privileges of the user on anything the user has access to. Likewise, in your situation, LIMIT is provided through MySQL as a query optimization. Exploiting this feature can bring down a system where massive datasets exist.
Also you should wrap your PDO query with a Try/Catch statement to prevent others from seeing your PDO exceptions when they're thrown.
//Load your IP here
$dev_ip = 'your.ip.address.here';
//Filter the user's IP
$user_ip = filter_input(INPUT_SERVER,'REMOTE_ADDR', FILTER_VALIDATE_IP);
//Set your limiting variable
$limiter = ($pageno-1)*$rows_per_page.','.$rows_per_page;
for($x = 0; $x <= $v; $x++) {
try {
$stmt = $conn->prepare("SELECT * FROM tman WHERE approve='Y' AND zip=:zipp ORDER BY id desc LIMIT $limiter");
$stmt->bindParam(":zipp", $zipcodeA[$x], PDO::PARAM_INT);
if(array_key_exists($x, $zipcodeA)&&!empty($zipcodeA[$x])){
echo '<br>zipcode: ' . $zipcodeA[$x] . '<br>';
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (array_key_exists('id', $result)&&!empty($result['id'])) {
$id2 = $result['id'];
} else {
if($user_ip==$dev_ip){
echo 'No ID';
}
}
if (array_key_exists('name', $result)&&!empty($result['name'])) {
$name = $result['name'];
} else {
if($user_ip==$dev_ip){
echo 'No Name';
}
}
}
} catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
if($user_ip==$dev_ip){
echo $ex->getMessage();
}
}
}
Don't base your loop condition on the result of fetch(). Get the result and evaluate it separately.
From the docs: "The return value of this function on success depends on the fetch type." IE Not necc a great thing for a boolean evaluation. It will return false if it fails but when it succeeds it may behave in an unexpected manner.
Better - use fetchAll() and loop through the resultant array.
Last - check your result set using print_r(). Make sure you have something to loop through.

Wrong data updated in mysql when function runs first time

function renew_status($propertyId){
$code = '';
$code = mt_rand(500000, 999999);
$q = "UPDATE `ps_listings` SET
`accessCode` = $code,
`renew` = '0'
WHERE `id` = $propertyId ";
mysql_query($q) or die(mysql_error());
$this->db->select('accessCode')->from('ps_listings');
$this->db->where(array('id' => $propertyId));
$query = $this->db->get();
$results = $query->result();
return $results[0]->accessCode;
}
I am updating a mysql table through codeigniter function. first time when i access my function it updates wrong number but if i refresh the page correct value is updated.
return $results[0]->accessCode; gives me this code 893195. while in database it saves 997228. Please Help me
Try this
function renew_status($propertyId){
$code = '';
$code = mt_rand(500000, 999999);
$data = array('accessCode' => $code, 'renew' => '0');
$this->db->where('id',$propertyId);
$this->db->update('ps_listings',$data);
$this->db->select('accessCode');
$this->db->where('id',$propertyId);
$query = $this->db->get('ps_listings');
$results = $query->result_array();
return $results[0]->accessCode;
}
1) Use mysql_affected_rows for check works update or no.
2) I think refresh page is wrong way. Use Session for deny double update.
3) For debugging retrieve and print accessCode before updating, after, and in
result(UI).
1) is "id" column unique and not null?
2) what does the following code returns :
echo count($results);

PHP Array Population Working on XAMPP but not Server

Thanks a lot to anyone who can help me out! I've uploaded a gift-shop style website to a server running PHP v 5.4.19. The problem is that the image and page references that were fetched on xampp don't appear in the array on the server. Why is this and what is wrong with my code (apart from me not adopting msqli yet)?
function smallDisplay()
{
$query = mysql_query($con, "SELECT `imageSrcQ`, `productCode` FROM `products` WHERE `displayCode` >= 11 && `displayCode` <= 12");
while ($results_row = mysql_fetch_array($query))
{
$returned_results[] = array(
'productCode' => $results_row['productCode'],
'imageSrcQ' => $results_row['imageSrcQ']
);
}
return $returned_results;
}
$results = smallDisplay();
echo $results;
$x = 0;
foreach ($results as $result)
{
${'img'.$x} = $result['imageSrcQ'];
$x++;
}
echo $img0;
Edit: mysql_query does not take $con as the first argument, see: http://php.net/manual/en/function.mysql-query.php.
Change your code to:
$query = mysql_query("SELECT `imageSrcQ`, `productCode` FROM `products` WHERE `displayCode` >= 11 && `displayCode` <= 12");
and it should work.
As a note you might want to declare your $returned_results - array before the loop, and use the mysql_fetch_assoc() instead

where clause not displaying data

i am trying to display data based on wether data in a field is new. instead of showing only the data that is new it is showing all data. can someone point out my error. many thanks
<?php
include("../../js/JSON.php");
$json = new Services_JSON();
// Connect to MySQL database
mysql_connect('localhost', 'root', '');
mysql_select_db(sample);
$page = 1; // The current page
$sortname = 'id'; // Sort column
$sortorder = 'asc'; // Sort order
$qtype = ''; // Search column
$query = ''; // Search string
$new = 1;
// Get posted data
if (isset($_POST['page'])) {
$page = mysql_real_escape_string($_POST['page']);
}
if (isset($_POST['sortname'])) {
$sortname = mysql_real_escape_string($_POST['sortname']);
}
if (isset($_POST['sortorder'])) {
$sortorder = mysql_real_escape_string($_POST['sortorder']);
}
if (isset($_POST['qtype'])) {
$qtype = mysql_real_escape_string($_POST['qtype']);
}
if (isset($_POST['query'])) {
$query = mysql_real_escape_string($_POST['query']);
}
if (isset($_POST['rp'])) {
$rp = mysql_real_escape_string($_POST['rp']);
}
// Setup sort and search SQL using posted data
$sortSql = "order by $sortname $sortorder";
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
// Get total count of records
$sql = "select count(*)
from act
$searchSql";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$total = $row[0];
// Setup paging SQL
$pageStart = ($page -1)*$rp;
$limitSql = "limit $pageStart, $rp";
// Return JSON data
$data = array();
$data['page'] = $page;
$data['total'] = $total;
$data['rows'] = array();
$sql = "select *
from act
$searchSql
$sortSql
$limitSql";
$results = mysql_query($sql);
while ($row = mysql_fetch_assoc($results)) {
$data['rows'][] = array(
'id' => $row['id'],
'cell' => array($row['id'], $row['slot'], $row['service'], $row['activity'], $row['department'], $row['company'], $row['address'], $row['user'], $row['item'], $row['filebox'], date('d/m/Y',strtotime($row['date'])), $row['quantity'], $row['type'], $row['new'])
);
}
echo $json->encode($data);
?>
You should debug SQL by looking at the SQL query, not at the PHP code that produces the SQL query. If you echo $sql and look at it, you'll probably see any syntax errors much more easily.
You can also copy & paste that SQL and try to execute it in the MySQL command tool, and see what happens, whether it gives the result you want, you can profile it or use EXPLAIN, etc.
You're using mysql_real_escape_string() for integers, column names, and SQL keywords (ASC, DESC). That escape function is for escaping only string literals or date literals. It's useless for escaping unquoted integers, column names, SQL keywords, or any other SQL syntax.
For integers, use (int) to typecast inputs to an integer.
For column names or SQL keywords, use a whitelist map -- see example in my presentation http://www.slideshare.net/billkarwin/sql-injection-myths-and-fallacies
You're not testing for error statuses returned by any of your functions. Most functions in ext/mysql return false if some error occurs. You should check for that after every call to a mysql function, and report errors if they occur.
You're selecting a database using a constant name sample instead of a quoted string "sample". This might be intentional on your part, I'm just noting it.
Also, this is not related to your errors, but you should really upgrade to PHP 5. PHP 4 has been end-of-lifed for over two years now.
after looking at the code again and all the suggestions i think i should be using an AND clause and not WHERE. for example the code
$searchSql = ($qtype != '' && $query != '') ? "where ".$qtype." LIKE '%".$query."%' AND new = 1" : '';
this is the WHERE clause? which basically translates to:
$sql = "select *
from act
$searchSql
$sortSql
$limitSql"; <- original code
$sql = "select *
from act
WHERE company LIKE '%demo%' AND new = 1
$sortSql
$limitSql";<-updated code
am i on the right track?

Categories