Issue in php script for android app - php

I have a showProduct.php file from where i want to call a function showProduct() in another file. In showProduct() i want to extract all rows from database and to showProduct.php file. the issue is that when i return the array only last row is showing. I want to show all the rows.
The showProduct.php is:
<?php
require_once '../includes/DbOperations.php';
$response = array();
$result = array();
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$db = new DbOperations();
$result = $db->showProduct();
if(!empty($result))
{
$response["prod_name"] = $result["prod_name"];
$response["prod_desc"] = $result["prod_desc"];
$response["prod_image"] = $result["prod_image"];
}
else
{
$response["error"] = true;
$response["message"] = "products are not shown";
}
}
echo json_encode($response);
?>
and showProduct() function is:
public function showProduct(){
$menu = array();
$query = mysqli_query($this->con,"SELECT * FROM `products` WHERE 1");
while ($row = mysqli_fetch_array($query)) {
$menu['prod_name'] = $row['prod_name'] ;
$menu['prod_desc'] = $row['prod_desc'] ;
$menu['prod_image'] = $row['prod_image'];
}
return $menu;
}

In your function, you are just overwriting the last data each time, you need to build this data up. Create an array with the new data and use $menu[] to add this new data to the list of menus...
public function showProduct(){
$menu = array();
$query = mysqli_query($this->con,"SELECT * FROM `products` WHERE 1");
while ($row = mysqli_fetch_array($query)) {
$newMenu = []; // Clear array to ensure no details left over
$newMenu['prod_name'] = $row['prod_name'] ;
$newMenu['prod_desc'] = $row['prod_desc'] ;
$newMenu['prod_image'] = $row['prod_image'];
$menu[] = $newMenu;
}
return $menu;
}

Related

problem in fetching data from tables of sql in PHP

hi i"ve created multiples tables in sql first time s i'm having difficulties in fetching data. so here is my code ,
<?php
// Use to fetch product data
class Product
{
public $db = null;
public function __construct(DBController $db)
{
if (!isset($db->con)) return null;
$this->db = $db;
}
// fetch product data using getData Method
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$resultArray[] = $item;
}
return $resultArray;
}
i'm only getting data from $result as i want to fetch data from $result 1-3.
i tried to run loop for all the result variables like this,
<?php
// Use to fetch product data
class Product
{
public $db = null;
public function __construct(DBController $db)
{
if (!isset($db->con)) return null;
$this->db = $db;
}
// fetch product data using getData Method
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$resultArray[] = $item;
}
return $resultArray;
// fetch product data one by one
while ($item1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)){
$resultArray[] = $item1;
}
return $resultArray;
// fetch product data one by one
while ($item2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
$resultArray[] = $item2;
}
return $resultArray;
// fetch product data one by one
while ($item3 = mysqli_fetch_array($result3, MYSQLI_ASSOC)){
$resultArray[] = $item3;
}
return $resultArray;
}
but i got the error which was ::undefined variable item1-3 in line no 74::
what should i do now.
You have some mistakes in your code, i somekind of "corrected" your code for you.
return statement exits your function means code below return is not executed
you can reuse variables
use multidimensional array to store multiple tables in one array
I know its not the best way to query the database - but i hope it helps you a little
public function getData($table = 'lipstick', $liner = 'liner', $brush = 'brush', $eyeshadow = 'eyeshadow'){
$result = $this->db->con->query( "SELECT * FROM {$table}");
$result1 = $this->db->con->query( "SELECT * FROM {$liner}");
$result2 = $this->db->con->query("SELECT * FROM {$eyeshadow}");
$result3 = $this->db->con->query("SELECT * FROM {$brush}");
$resultArray = array();
// fetch product data one by one
$resultArray[$table] = array();
while ($item = mysqli_fetch_array($result, MYSQLI_ASSOC)){
array_push($resultArray[$table], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$liner] = array();
while ($item = mysqli_fetch_array($result1, MYSQLI_ASSOC)){
array_push($resultArray[$liner], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$eyeshadow] = array();
while ($item = mysqli_fetch_array($result2, MYSQLI_ASSOC)){
array_push($resultArray[$eyeshadow], $item);
}
//return $resultArray; //no return here, if you return here the code below will not be executed
// fetch product data one by one
$resultArray[$brush] = array();
while ($item = mysqli_fetch_array($result3, MYSQLI_ASSOC)){ //you can reuse $item
array_push($resultArray[$brush], $item);
}
return $resultArray;
}

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

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++;
}

How to return error message if there is no data in the database?

I wanted the logic is if there is data in the database then query the data. Or else if there is no data then it will show an error message.
Here is my code:
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
} else {
return $data = $query;
}
Before this code, if the code that query from database:
//Query string and put it in a variable.
if(isset($_POST['dob_chi'])){
$query = "SELECT * FROM $table_n WHERE dob_chi = :date";
} else {
$query = "SELECT * FROM $table_n WHERE dob_eng = :date";
}
I tried input a non data to execute the code but somehow it didn't show error and straight process to the scripting area.
The script below:
//create a while loop for every entry in our DB where the date is match.
while ($row = $stmt->fetchObject()) {
$r1 = $row->rowone;
$r2 = $row->rowtwo;
$r3 = $row->rowthree;
$englishdate = $row->dob_eng;
$chinesedate = $row->dob_chi;
//add all initial data into the matrix variable for easier access to them later
$rows[0]
$rows = array(
array($r1),
array($r2),
array($r3),
array()
);
}
//incoporate modulo value as an argument.
function incmod($a, $m)
{
return ($a % $m) + 1;
}
//Population each row, with $populationCount number of elements, where each element is added with incmod(X, $mod)
function populateRow($rowId, $populationCount, $mod)
{
//function to access the global variable.
global $rows;
$row = $rows[$rowId];
while (sizeof($row) < $populationCount) {
$rowInd = sizeof($row) - 1;
$m = incmod($row[$rowInd], $mod);
array_push($row, $m);
}
//set the row back into the global variable.
$rows[$rowId] = $row;
}
$stmt = $db->prepare($query);
$stmt->execute(array('date' => $myFormat));
$data = $stmt->fetchAll();
if ( !$data ) {
echo 'No data found in database!';
}

How to return a multidimensional array keys as a tree?

I am working on an MLM application in which i need to show all users as a tree. For this is implemented parent child relationship among the users. my table structure is here :-
I had retrieve the id's of users in a multidimensional array as per the relation. Here is array:-
For this i used this code :-
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 )
{
$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id']);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
Now, i need to show the data in a tree structure like :-
Any hint will be helpful. I am very near to complete this...
Yes, you are so near..!!
Try below it will be work for you..
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('testapp', $con);
function create_tree( $parent_id = 0 ,$result_array = array())
{
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'],$result_array);
}
}
}
return $result_array;
}
$tree = create_tree();
print_r($tree);
?>
If this will not work for you than let me know..!!
Thanks..
try that, it should give you the structure;
function create_tree( $parent_id = 0 , $result_array = array() )
{
//$result_array = array();
$Query = 'SELECT * FROM `user` WHERE `parent`=\''.$parent_id.'\';';
$query_result = mysql_query($Query);
if(mysql_num_rows($query_result)>0)
{
while($row = mysql_fetch_assoc($query_result))
{
if(!array_key_exists($row['user_id'], $result_array))
{
//$result_array[$row['user_id']] = $row;
$result_array[$row['user_id']] = create_tree($row['user_id'], $result_array[$row['user_id']]);
}
}
}
return $result_array;
}
edit; forgot the remove result_array in function

Categories