JSON Array of objects with MySql - php

i am trying to get this output from a database of countries. i had use the mysqli_fetch_object() function but it does not work with me
"countries":[{"countryname":"India","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/india.png","language":"Hindi","capital":"New Delhi","currency":{"code":"INR","currencyname":"Rupee"}},{"countryname":"Pakistan","flag":"http:\/\/wptrafficanalyzer.in\/p\/demo1\/pakistan.png","language":"Urdu","capital":"Islamabad","currency":{"code":"PKR","currencyname":"Pakistani Rupee"}}]}
and i am use this php script
<?php
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
{
die ("Erro in connection" . mysqli_connect_error);
}
else{ $encode = array();
$sql="select * from country ";
$res=mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
//$temp_array[]=$row;
$encode=$row;
}
//echo json_encode($temp_array);
echo json_encode($encode);
}
else
{
echo " 0 Rows";
}
}
?>
if anybody can help me ?

Your code should be something like below;
<?PHP
require 'config.php';
$con=mysqli_connect($servername,$username,$password,$db);
if(!$con)
die ("Error in connection" . mysqli_connect_error);
else{
$encode = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
{
$temp_array=array();
while($row=mysqli_fetch_object($res))
{
$encode[]=$row;
}
}
echo json_encode($encode);
}
?>
You do not need to write down 0 rows because you are returning a json object which has an array so when you check result.length it tells you the row count.
As an advice you may use something like below;
<?php
require 'config.php';
$con = mysqli_connect($servername,$username,$password,$db);
$resultArray = array();
$resultArray["error"] = true; //That will tell your javascript client if any error exits.
$resultArray["errorMessage"] = ""; //We will set this value if any error exits;
if(!$con)
{
$resultArray["error"] = true;
$resultArray["errorMessage"] = "Error in connection" . mysqli_connect_error();
}
else{
$resultArray["error"] = false;
$itemCollection = array();
$sql = "select * from country ";
$res = mysqli_query($con,$sql);
if(mysqli_num_rows($res)>0)
while($row = mysqli_fetch_object($res))
$itemCollection[]=$row;
$resultArray["itemCollection"] = $itemCollection;
}
echo json_encode($resultArray);
?>
In my sample you are going to get a json result something like below;
{"error":true,"errorMessage":"ErrorMessageIfExists","itemCollection":[yourObject,yourObject]}
Hope this helps you.

Related

function in PHP not returning result

I have a simple data retrieval PHP file from Mysql and encodes in JSON string. The code below returns the result as expected
<?php
require 'dbconnection.php';
$tablename = $_GET["tabname"];
$sql = "SELECT * FROM ". $tablename ;
if (!mysqli_query($conn,$sql))
{
echo("Error description: " . mysqli_error($con));
} else {
$res = mysqli_query($conn,$sql);
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('_id'=>$row[0],
'course_name'=>$row[1],
'address'=>$row[2],
'city'=>$row[3],
'state'=>$row[4],
'zipcode'=>$row[5],
'phone'=>$row[6]));
}
echo json_encode(array("result"=>$result));
$conn->close();
?>
Sample Result...
{"result":[{"_id":"1","course_name":"Quail Valley","address":"12565 NW Aerts Rd.","city":"Banks","state":"OR","zipcode":"97106","phone":"5033244444"},...]}
My goal is to use the variable that was passed to PHP and based on it's name call function. I can't seem to figure out what I'm doing wrong!
<?php
require 'dbconnection.php';
$tablename = $_GET["tabname"];
function Course() {
$sql = "SELECT * FROM ". $tablename ;
if (!mysqli_query($conn,$sql))
{
echo("Error description: " . mysqli_error($conn));
} else {
$res = mysqli_query($conn,$sql);
}
$results = array();
while($row = mysqli_fetch_array($res)){
array_push($results,
array('_id'=>$row[0],
'course_name'=>$row[1],
'address'=>$row[2],
'city'=>$row[3],
'state'=>$row[4],
'zipcode'=>$row[5],
'phone'=>$row[6]));
}
return $results;
}
$result = call_user_func(Course());
// OR... $result = call_user_func($tablename());
echo json_encode(array("result"=>$result));
$conn->close();
?>
Here is the output...
Error description: {"result":null}
As you can see in the doc of php.net http://php.net/manual/fr/function.call-user-func.php
The function accepts a string as a parameter (see the examples).
So it should be call_user_func('Course')
Preferred way is directly go for:-
$result = Course();
But if you want to use call_user_func() then use like below:-
$result = call_user_func('Course');
It's because it take a callback as a string :-call_user_func

how to display in json format using php

using php database connection i want to display data in json format which data are fatched from database(MySql),but i can't displaying in json format. http://takeyourtime.16mb.com/fatchData.php
$con = mysqli_connect($host, $username, $pwd, $db) or die('Unable to connect');
if (mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name = $_POST['Query'];
$sql = "SELECT * FROM playerstb";
$query = mysqli_query($con,$sql);
if ($query)
{
$rows = array();
while ($r = mysql_fetch_assoc($query)) {
$rows['root_name'] = $r;
}
}
echo json_encode($rows);
mysqli_close($con);
Just use json_encode. BTW, your script has an syntax error in the ending if block:
if($query){
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows['root_name'][] = $r; // probably must be an array
}
echo json_encode($rows);
}else{
/*
This will show up when you have a query error
nothing to do with the results found.
I would consider changing the message below
*/
echo('Not Found');
}
inside your while loop you dont save all results you each one writen over the before one
you have to store it in array like note this ([])*
while($r = mysql_fetch_assoc($query)) {
$root_names[] = $r;
}
echo json_encode(['root_name'=>$root_names]);
You have to store first your result in array then after that create an array name your desire key ($array["name"])
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name=$_POST['Query'];
$sql="SELECT * FROM playerstb";
$query=mysqli_query($con,$sql);
if($query)
{
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
$data["data"]=$rows;
echo json_encode($data);
}
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>

Errors when adding data to a database with PHP

I have to make a web app that gets information from my database, that gets its info from an API). Then I have to show items under certain conditions.
But when I try to add the data from the API, I got a strange message:
Notice: Trying to get property of non-object in c:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\IMP03\inleveropdracht3\libs\php\function.php on line 21
Here is my PHP code:
<?php
require_once 'settings.php';
$mysqli = mysqli_connect($db_host, $db_user, $db_password, $db_database);
if (mysqli_connect_error()) {
echo mysqli_connect_error($mysqli) . "We are not able to connect to the online database";
}
jsondecode($mysqli);
if (isset($_GET['club']) && !empty($_GET['club'])) {
jsondecode($mysqli);
} else if (isset($_GET['thuisPoint']) && !empty($_GET['thuisPoint']) && ($_GET['uitPoint']) && ($_GET['uitPoint'])) {
updatePoints($mysqli);
} else {
getWedstrijd($mysqli);
}
function jsondecode($mysqli) {
$apiLink = 'http://docent.cmi.hr.nl/moora/imp03/api/wedstrijden?club=';
// $club = $_GET['club'];
$data = json_decode(file_get_contents($apiLink . "Ajax"));
foreach ($data->data as $info) {
$thuisClub = $info->homeClub;
$uitClub = $info->awayClub;
addWestrijden($mysqli, $thuisClub, $uitClub);
}
}
//querys
function addWestrijden($mysqli, $thuisClub, $uitClub) {
$query = "INSERT INTO wedstrijd VALUES(null, '$thuisClub', '$uitClub')";
$resultAddWedstrijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
function getWedstrijd($mysqli) {
$query = "SELECT * FROM wedstrijd ORDER BY thuisClub DESC";
$resultGetWedstijd = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
while ($result = mysqli_fetch_assoc($resultGetWedstijd)) {
$rows [] = $result;
}
header("Content-Type: application/json");
echo json_encode($rows);
exit;
}
function updatePoints($mysqli) {
$id = $_GET['id'];
$thuisPoints = $_GET['thuisPoint'];
$uitPoints = $_GET['uitPoint'];
$query = "UPDATE wedstrijd "
. "SET thuisPunt = '$thuisPoints', uitPunt = '$uitPoints') "
. "WHERE id = '$id'";
mysqli_query($mysqli, $query) or die(mysqli_error($mysqli));
getWedstrijd($mysqli);
}
I did modify it a bit so it would add data from the API. I really would appreciate it if someone could help me.
Change your foreach to:
foreach ($data as $data => $info)

Connect php with server

I am connecting to server with help of php for an android application.
Name of Database in phpmyadmin is "student" , name of table is "data" and fields are "Name" and "EmpId"
This is what I coded n php and getting the error on the "$output" part as undefined variable
Here is the code:
<?php
$connection = connectionserver ();
function connectionserver (){
$con = mysql_connect("localhost", "root", "") or die ("connection not found");
if($con)
echo "Connection Created" ,"<br>";
$database = mysql_select_db ("student1", $con);
if($database) echo "Database Connected" , "<br>";
return $con;
}
$result = mysql_query("select * from data");
while ($row = mysql_fetch_assoc($result))
{
$output [] = $row;
}
print json_encode($output);
mysql_close($connection);
?>
declare $output as array before the while
$output = array();
$undefined_array[] = 'something' will not trigger an E_NOTICE error. However it is good practice to initialize the variable.
The error comes from the line with json_encode, most likely because your query didn't return any result, didnt get into the while loop, thus $output[] was never executed.
You may try this:
<?php
$connection = connectionserver ();
function connectionserver (){
$con = #mysql_connect("localhost","root","");
if(!$con) die("Can't connect!!");
$var2 = #mysql_select_db("student1",$con);
if(!$var2)
die("<br>"."can't select dataBase");
$result = mysql_query("select * from data");
while ($row = mysql_fetch_assoc($result))
{
$output[] = $row;
}
print json_encode($output);
mysql_close($con);
}
?>
Try this,
echo connectionserver();
function connectionserver (){
$con = mysql_connect("localhost", "root", "") or die ("connection not found");
$database = mysql_select_db ("student1", $con);
$result = mysql_query("select * from data") or die(mysql_error());
$output = array();
while ($row = mysql_fetch_assoc($result))
{
$output[] = $row;
}
mysql_close($con);
return json_encode($output);
}

PHP - Check if tinyint has (1) in MySQL

I already know how could I UPDATE this values, but I am a litle confused about how can I get this current values.
So, here's my code:
<?php
//READ DB
$result = mysql_query("SELECT ativo FROM Spot", $db);
if(!$result){
die("ERRO" . mysql_error());
} else {
//RETURN RESULT
while ($result != '1') {
echo '<div>IT'S TRUE</div>';
}
echo '<div>IT'S FALSE</div>';
}
?>
The return value of mysql_query() is actually an resource identifier and not the data, you request. To get the actual data, you have to fetch it first, e.g., by using mysql_fetch_assoc():
$result = mysql_query("SELECT ativo FROM Spot", $db);
if(!$result){
die("ERRO" . mysql_error());
} else {
//RETURN RESULT
while ($row = mysql_fetch_assoc($result)) {
if( $row['ativo'] != 1 ) {
echo '<div>IT\'S TRUE</div>';
} else {
echo '<div>IT\'S FALSE</div>';
}
}
I also corrected the missing escaping of ' inside your string. See the highlighting in your question, what went wrong there.
You have to fetch the result from that query. Like this:
$query = mysql_query("SELECT ativo FROM Spot", $db);
$result = mysql_fetch_array($query);
if ($result['ativo'] == 1) {
// is 1
} else {
// not 1
}
//RETURN RESULT
while ($row=mysql_fetch_array($result)) {
echo $row['ativo'];
}
first you have to use other quotes
not
echo '<div>IT'S TRUE</div>';
should be like
echo "<div>IT'S TRUE</div>";
second
your query returns a resoure id, so it never will be 1 ^^
<?php
//READ DB
$result = mysql_query("SELECT ativo FROM Spot", $db);
if(!$result)
{
die("ERRO" . mysql_error());
}
else
{
//RETURN RESULT
while ($data = mysql_fetch_assoc($result))
{
echo $data['ativo'] . "<br/>";
}
}
?>
<?php
//READ DB
$result = mysql_query("SELECT ativo FROM Spot", $db);
if(!$result){
die("ERRO" . mysql_error());
} else {
//RETURN RESULT
while ($row = mysql_fetch_array($result)) {
$value = $row['ativo'];
if($value!=1){
echo '<div>IT\'S TRUE</div>'; // escape special chars
}
else{
echo '<div>IT\'S FALSE</div>'; // escape special chars
}
}
?>

Categories