Connect php with server - php

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

Related

MySQL Query Returns 0 When Running Multirowed Response Query

When I run the following code In PHP
$connect = mysqli_connect("localhost", "root", "dbpass", "db");
function csvfromarray($array) {
$result = $array[0]+","+$array[1];
return $result;
}
$query = mysqli_query($connect, "SELECT * FROM dbtable");
$row = mysqli_fetch_assoc($query);
$data = array();
$i = 0;
while($row = mysqli_fetch_assoc($query)) {
$data[$i] = $row['last'];
$i++;
}
$csv = csvfromarray($data);
echo $csv;
mysqli_close();
I end up getting an echoed response of "0" when I should be returning "lname1,lname2".
All of chris85's stuff is correct...
Here's a tidy up:
$query=mysqli_query($connect,"SELECT `last` FROM dbtable");
$data=array();
while($row=mysqli_fetch_assoc($query)) {
$data[]=$row['last']; // push into array
}
echo implode(',',$data); // echo comma-separated values
mysqli_close();

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);
?>

Using Php mysql query do not get data from php class, though there are data

class book {
function __construct() {
$conn = mysql_connect('localhost', 'root', '') or die('can nit connect to DB');
mysql_select_db('atomic_project', $conn) or die('can not connect to db');
}
public function listView() {
$allData = array();
$query = "SELECT * FROM `book`";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
$allData [] = $row;
}
return $allData;
}
}
My index page
$listViewObj = new book();
$allData = $listViewObj->listView();
echo "<pre>";
print_r($allData);
echo "<pre>";
Here is my code and the table here is my table data , i can insert data into table but no row is found
i can't understand why no data is shown, please help me
<?php
class book {
public function listView() {
$conn = mysql_connect('localhost', 'root', '') or die('can nit connect to DB');
mysql_select_db('atomic_project', $conn) or die('can not connect to db');
$allData = array();
$query = "SELECT * FROM `book`";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
//echo "<pre>";
//print_r($row);
$allData [] = $row;
}
return $allData;
}
}
book::listView(); //scope resolution operator
?>
or calling function by object
$obj = new book();
$obj->listView();

Return mysqli query as comma separated values with PHP

I have the following query that is returning:
"Code1""Code2""Code3"
What I need is for the result to be in CSV format like this:
'Code1','Code2','Code3'
How do I modify my code to accomplish this?
<?php
$conn = new mysqli("127.0.0.1", "user", "password", "table", "3306");
if(mysqli_connect_errno($conn)) {
echo "Unable to connect to database server";
}
$result = mysqli_query($conn,"SELECT code FROM sourcecodes");
while($row = $result->fetch_assoc()) {
$mydata = ($row['code']);
echo json_encode($mydata);
}
$result->free();
$conn->close();
?>
Per every iteration you should be pushing to an array. Once the array is built, you can turn it into json and echo it.
$mydata = array();
while ($row = $result->fetch_assoc()) {
$mydata[] = $row['code'];
}
$json = json_encode($mydata);
$string = str_replace(array('[', ']'), '', $json);
echo $string;
Try this
<?php
$conn = new mysqli("127.0.0.1", "user", "password", "table", "3306");
if(mysqli_connect_errno($conn)) {
echo "Unable to connect to database server";
}
$result = mysqli_query($conn,"SELECT code FROM sourcecodes");
while($row = $result->fetch_assoc()) {
$mydata[] = $row['code'];
}
$result->free();
$conn->close();
echo "'".implode("','",$mydata)."'";
?>
Or you need json_encode?

JSON Array of objects with MySql

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.

Categories