Getting null array first and then getting actual result in php - php

In my script i am fetching data from database and storing it in array and output it in json. Everything is going correct just the first array I am getting is null and then the second array has the correct data. I don't understand why am I getting first null array.
My problem solves if I get correct result in array without the null array.
Here is the output I am getting
[[],{"url":"example.com\/sign_pdf\/PDFSign.pdf","name":"PDFSign.pdf","signer":"aman","sequence":"1","message":"Hello","flag":"0"}]
I don't need First null array. Why the hell am I getting that.
Here is the code.
if(($_GET['action'])&&($_GET['username'])&&($_GET['key'])) {
$select = $_GET['action'];
$username =$_GET['username']; //no default
$key= $_GET['key'];
if($key=='abcxyz'){
if($select=='select'){
/* connect to the db */
$connect = mysqli_connect('localhost','root','')or die("Couldn't connect to database!");
mysqli_select_db($connect,'sign') or die ("Couldn't find database");
$query ="SELECT * FROM path WHERE signer ='$username' ";
$result = mysqli_query($connect,$query);
$numrows=mysqli_num_rows($result);
$posts[] = array();
if($numrows!==0) {
while($row = mysqli_fetch_array($result)) {
$post['url'] = $row['url'];
$post['name'] = $row['name'];
$post['signer'] = $row['signer'];
$post['sequence'] = $row['sequence'];
$post['message'] = $row['message'];
$post['flag'] = $row['flag'];
array_push($posts, $post);
}
header('Content-type: application/json');
echo json_encode($posts);
}
}
}
}

You are creating array(array()) by $posts[] = array();
Replace this:
$posts[] = array();
with
$posts = array();
$posts = array(); will create a null array() and not array(array())

Instead of
$posts[] = array();
Which assigns an array to the first element of $posts, use
$posts = array();
Which initialises the variable, what I think you are trying to do.

Your $posts[]=array() should be like $posts=array() And append $post into $posts using $posts[]=$post .
$posts = array();
if ($numrows !== 0) {
while ($row = mysqli_fetch_array($result)) {
$post = array();
$post['url'] = $row['url'];
$post['name'] = $row['name'];
$post['signer'] = $row['signer'];
$post['sequence'] = $row['sequence'];
$post['message'] = $row['message'];
$post['flag'] = $row['flag'];
$posts[] = $post;
}
}

You should remove the $posts array. The array_push($posts, $post) is basically taking your empty $posts array and adding the $post array to it.

Related

Array in while loop

I created a function that read data from a mysql db.
I want to put the data into a array and read that outside of the PHP function.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
return $kategorien;
}
}
To load the data outside from function:
$kategorien = showCategory($con);
echo $kategorien['kategorie'][0];
It doesn't work. Whats wrong?
The
return $kategorien;
will exit the loop and the function, so move this to the end of the function and not in the loop.
function showCategory($con) {
$sql = "SELECT kategorie FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}
Rather than using *, it's also worth specifying the column names if you only need some of them.
Display the data using...
$kategorien = showCategory($con);
print_r( $kategorien );
or use a foreach()...
$kategorien = showCategory($con);
foreach ( $kategorien as $kat ) {
echo $kat.PHP_EOL;
}
Use this instead, because returning $kategorien will exit the loop, so it will only run once.
function showCategory($con) {
$sql = "SELECT * FROM kategorien";
$kategorien = array();
$result = $con->query($sql);
while($row = $result->fetch_assoc()) {
$kategorien[] = $row["kategorie"];
}
return $kategorien;
}

How do I hide arrays php with an empty value of 0?

I have to hide all empty arrays from the result or with value = 0. How can I do?
$return_arr = array();
$fetch = mysqli_query($conn, "SELECT...");
while ($row = mysqli_fetch_array($fetch, MYSQLI_ASSOC)) {
$row_array['id'] = $row['ordr'];
$row_array['name'] = $row['name'];
$row_array['icon'] = $row['icon'];
$row_array['file_a'] = $row['file_a'];
$row_array['file_b'] = $row['file_b'];
$row_array['file_c'] = $row['file_c'];
$row_array['file_r'] = $row['file_r'];
array_push($return_arr,$row_array);
}
$response_arr = json_encode($return_arr);
return $response_arr;
}
There is missing code from your function so I have worked with what is available.
Try selecting only the cols you want data from and then check if col is empty per row. If there is a column that has data then the whole row is returned.
$return_arr = array();
$fetch = mysqli_query($conn, "SELECT name,icon,file_a,file_b,file_c,file_r FROM...");
while ($row = mysqli_fetch_array($fetch, MYSQLI_ASSOC)) {
$tmp = 0;
foreach( $row as $key => $val ){
if( !empty($row[$key]) ) $tmp++;
}
if( $tmp > 0 ) array_push($return_arr,$row_array);
}
$response_arr = json_encode($return_arr);
return $response_arr;
}
Also array_filter might be helpful as it can exclude all false values on the results set (used without callback).
More info on array_filter

How to get entire column from database and store it in an array using php?

My table's name is userdetails, it has four attributes named name, username, mobile and password. I want to get all the mobile numbers and store it in an array using php.
I have used the following php code
if($_SERVER['REQUEST_METHOD']=='GET'){
require_once('dbConnect.php');
$mobile = $_GET['mobile'];
$sql = "SELECT MOBILE FROM USERDETAILS";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"MOBILE"=>$res['MOBILE']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
but all I am getting is the first entry of the database.
Please help.
You should loop through the records by doing the following:
$result = [];
while ($array = mysqli_fetch_array($r)) {
$result[] = $array['MOBILE'];
}
echo json_encode($result);
For getting all number of column use while loop as
$jsonData = array();// initialized you array
while ($array = mysqli_fetch_array($r,MYSQLI_ASSOC)) {// add MYSQLI_ASSOC to get associative array
$jsonData[] = $res['MOBILE'];// store data into array
}
echo json_encode($jsonData);// convert in into json
Try this:
$result = mysqli_query($con,$sql);
$mob = Array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$mob[] = $row['MOBILE'];
}

can't get result from sp into array

I'm trying to get the result of a stored procedure in MySQL into an array with use of php. The code I have:
function get_all_uzovi($dbc) {
//$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
// FROM tbl_diagnoses
// WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
// ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,"CALL spGetUzovi");
//WHAT DOES NOT WORK:
//$data = array();
//while ( $row = $result->fetch_assoc() ) {
// $data[] = $row;
//}
//return json_encode($data);
//WHAT DOES WORK:
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
}
The code under "//WHAT DOES NOT WORK" is what I need: the result as a json format. For some reason it gives me nothing..
The code under "//WHAT DOES WORK", does work, but this is not what I want.
the code for the sp:
CREATE DEFINER=`ziekenh3`#`localhost` PROCEDURE `spGetUzovi`()
NO SQL
SELECT *
FROM tbl_uzovi
the code that I use when working with queries (which does work) instead of sp:
function get_diagnoses($dbc,$var_chosen_specialism) {
$query = "SELECT diagnose_id, diagnose_code, specialisme_agb_code_fk
FROM tbl_diagnoses
WHERE specialisme_agb_code_fk = '$var_chosen_specialism'
ORDER BY diagnose_code ASC";
$result = mysqli_query($dbc,$query);
$data = array();
//while ( $row = $result->fetch_assoc() ) {
while ( $row = mysqli_fetch_assoc($result) ) {
$data[] = $row;
}
return json_encode($data);
}
Any thoughts?
Does this work?
function get_all_uzovi($dbc) {
$result = mysqli_query($dbc,"CALL spGetUzovi");
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
return json_encode($data);
}
I Solved it. A bit of a stupid problem: there where some fields in the result set that contained characters like: , ( . etc. I don't think json likes this..
When I did a SELECT * FROM on another table it worked. So, my code that works now is:
function get_all_uzovi($dbc) {
$q = "CALL spGetUzovi";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
return json_encode($data);
}
I'm sorry for the inconvenience!

SQLSRV query to array

I try to query a SQL database and save data into a custom array, but the array always repeats last row*num rows on database.
php:
class Cst
{
public $ParagemID;
public $Designacao;
public $DecimalDeGrauY;
public $DecimalDeGrauX;
}
require 'config.php';
$dsn = array( "Database"=>"$database", "UID"=>"$username", "PWD"=>"$password", "LoginTimeout"=> 60);
$db = sqlsrv_connect($server, $dsn);
$sql = "SELECT ParagemID, Designacao, DecimalDeGrauY, DecimalDeGrauX FROM adoParagens WHERE ParagemID >= 20000";
$stmt = sqlsrv_query($db, $sql);
$locations = new Cst();
$location=array();
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$locations->ParagemID = $row->ParagemID;
$locations->Designacao = $row->Designacao;
$locations->DecimalDeGrauY = $row->DecimalDeGrauY;
$locations->DecimalDeGrauX = $row->DecimalDeGrauX;
//echo json_encode($locations);
$location[$i]= $locations;
$i++;
}
echo json_encode($location);
It looks like you're always working with same instance of that object. Updating it for each row will also update all copies of it, as they are in fact the same object.
Try this instead.
...
$location = array();
while( $row = sqlsrv_fetch_object($stmt) )
{
$data = array();
$data['ParagemID'] = $row->ParagemID;
$data['Designacao'] = $row->Designacao;
$data['DecimalDeGrauY'] = $row->DecimalDeGrauY;
$data['DecimalDeGrauX'] = $row->DecimalDeGrauX;
$location[]= $data;
}
...
try using a 2 dimensional array.
$i=0;
while( $row = sqlsrv_fetch_object($stmt))
{
$location[$i][$locations->ParagemID/*put your val*/] = $row->ParagemID;
$location[$i][$locations->Designacao/*put your val*/] = $row->Designacao;
$location[$i][$locations->DecimalDeGrauY/*put your val*/] = $row->DecimalDeGrauY;
$location[$i][$locations->DecimalDeGrauX/*put your val*/] = $row->DecimalDeGrauX;
//echo json_encode($locations);
$i++;
}

Categories