php script to get data from database android - php

i m trying to build a JSON array from mysql. it does not get the information from mysql
<?php
$host="localhost";
$pwd="";
$user="root";
$db="mydb";
$con=mysqli_connect($host,$user,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo"failded to connect";
}
$query = mysqli_query($con,"select * from product");
if ($query)
{
while($row = mysqli_fetch_array($query))
{
$flag[] = $row;
}
print(json_encode($flag));
}
mysqli_close($con);
?>
Notice: Array to string conversion in C:\wamp\www\new\count.php on line 19
What does this error mean and how do I fix it?

Please initialize $flag something like this $flag = array()
hope it was helpful to you.

change print to print_r(json_encode($flag)) you won't get any error

You are converting your array to a json array so you have to use var_dump or print_r().

Related

Value of output "any" when there are no rows in the SQL table

<?php
$successreturn[]=array(
"id"=>"any",
"firstname"=>"any",
"lastname"=>"any",
"dateofbirth"=>"any",
"city"=>"any",
"gender"=>"any"
);
header("Access-Control-Allow-Origin: *");
$servername="localhost";
$username="root";
$password="sandeepchetikam";
$dbase="mydb";
$conn=mysqli_connect($servername,$username,$password,$dbase);
if (!$conn) {
echo "Connection Problem".mysqli_connect_error($conn);
}
$sql= "SELECT * FROM Employees";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
$value=0;
if(!$result){
echo "Connection Failed " .mysqli_connect_error($result);
}
while($row = mysqli_fetch_assoc($result)){
$successreturn[$value]['id'] =$row['id'];
$successreturn[$value]['firstname'] =$row['firstname'];
$successreturn[$value]['lastname'] =$row['lastname'];
$successreturn[$value]['dateofbirth'] =$row['dateofbirth'];
$successreturn[$value]['city'] =$row['city'];
$successreturn[$value]['gender'] =$row['gender'];
$value++;
};
echo json_encode($successreturn);
?>
output :
[{"id":"any","firstname":"any","lastname":"any","dateofbirth":"any","city":"any","gender":"any"}]
I am trying to return a JSON value into my angular service. But when there are no more rows in the table. Its returning the Colomn value as "any".
Why is it like that ?? How do i return a empty row with no value?
You need to control the program flow a little differently
<?php
header("Access-Control-Allow-Origin: *");
$servername="localhost";
$username="root";
$password="sandeepchetikam";
$dbase="mydb";
$conn=mysqli_connect($servername,$username,$password,$dbase);
if (!$conn) {
echo "Connection Problem".mysqli_connect_error($conn);
}
// first only select what you want to use from the row
$sql= "SELECT `id`,`firstname`,`lastname`,
`dateofbirth`,`city`,`gender`
FROM Employees";
$result = mysqli_query($conn,$sql);
if(!$result){
// you only use `mysqli_connect_error` to get connection errors
// use mysqli_error($result) for normal query errors
echo "Query failed " . mysqli_error($result);
echo json_encode(array('error'=>'Query failed'));
exit;
}
if ( mysqli_num_rows($result) > 0 ) {
while($row = mysqli_fetch_assoc($result)){
// now as you only have what you want in your assoc array
$rows[] = $row;
}
echo json_encode($rows);
} else {
// no data returned from query
// return something so the calling code knows what to do
echo json_encode(array('error'=>'No data in table'));
}
?>
When no row selected then the while loop is not executting and the initial $successreturn array is return with value 'any' to return no value if no row selected then
Just change this
$successreturn[]=array(
"id"=>"any",
"firstname"=>"any",
"lastname"=>"any",
"dateofbirth"=>"any",
"city"=>"any",
"gender"=>"any");
To
$successreturn[]=array(
"id"=>"",
"firstname"=>"",
"lastname"=>"",
"dateofbirth"=>"",
"city"=>"",
"gender"=>"");
Edit:-
$successreturn=[];
And check the value is empty or not in view and then display the data if it have otherwise don't display it.
I thing it will help you.

json data not showing

i'm trying to connect mysql database server xampp to android studio,i wrote php code and when i run the code ,the result not showing anything.
here is my code:
connection.php
<? php
define ('hostname','localhost');
define ('user','root');
define ('password','1993');
define ('dbname','mat');
$connect = mysqli_connect(hostname,user,password,dbname);
$mysqli->query("set character_set_server='utf8'");
$mysqli->query("set NAMES 'utf8'");
?>
php to fetch data from database:
show.php
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
include 'connection.php';
ShowMat();
}
function ShowMat()
{
global $connect;
$query = "Select * from mat;";
$result = mysqli_query($connect, $query);
$number_of_rows = mysqli_num_rows($result);
$temp_array = array();
if($number_of_rows > 0) {
while ($row = mysqli_fetch_assoc($result))
{
$temp_array[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode(array("mata"=>$temp_array));
mysqli_close($connect);
}
How can I solve this?
I think your REQUEST_METHOD is GET so your code :
if($_SERVER["REQUEST_METHOD"]=="POST"){
so this condition will fail that is why you are not getting any echo.
You can use POSTMAN to test your apis give it a try its really useful.
You change this line mysqli_fetch_assoc to this line while ($row = mysqli_fetch_array($result))
This line is creating problem :if($_SERVER["REQUEST_METHOD"]=="POST").Check what type of data are you sending.Are you sending raw data or structured data.Try isset($_REQUEST['']). Example :
$action=isset($_REQUEST['action'])?$_REQUEST['action']:"";
switch($action)
{
case "ShowMat":
ShowMat();
}
function ShowMat()
{
// code
}

PHP : 'json_encode' from Database not showing any values

It's not a duplicate question about UTF-8 Unicode.
I am new to php and I am trying to create a json response.
I added data into my database properly as follows.
Then I tried to connect to DB and i did it successfully .
but after that when I tried to create a json response by using the following code, it doesn't shows any json response .
My PHP code is :
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','qwerty');
define('DB','carol');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (!$con)
{
echo "Please try later..";
}
else
{
echo "DB Connected..";
}
$sql = "SELECT * from songs";
$res = mysqli_query($con,$sql);
if (!$res)
{
echo "query failed..";
}
else
{
echo "Query success..";
echo (mysqli_num_rows($res));
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0]),
array('url'=>$row[1]),
array('lyrics'=>$row[2])
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
I'm getting only echo of DB Connected , Query Success and 14 (no of rows)
I'm trying PHP for the first time by using some online tutuorials.
if I did any mistake in my code,please help me to find my mistake.
Thank you in advance.
After I added echo var_dump($res);
I got

JSON returns [null,null] in my app

I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author

empty response php sql json

i am developing a php server sending arrays response to Android client using JSON. Now i simply testing the php code but the result is empty. Please help!!
<?php
#Connect to Database
$con = mysqli_connect("localhost","root","", "leoonline");
#Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}
//Check already exist account
$allaccount = mysqli_query($con, "SELECT * FROM usersacc");
$results = array();
while($row = mysqli_fetch_array($allaccount))
{
$results[] = array(
'id' => base64_decode($row['id']),
'phone' => $row['phone'],
'password'> $row['password']
);
}
$json = json_encode($results);
?>
Is this your final code? You are not outputting anything apart from the connection error message if it happens.
Change
$json = json_encode($results);
to
echo json_encode($results);
If its still blank, then it could be a db data problem.

Categories