I'm trying to pull some records from the DB with the code below, but my echo json_encode($contacts); at the end of the code doesn't print anything. Nor does any echo put right above that.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
//Create query to retrieve all contacts
$query = 'SELECT Numero_Leccion,Titulo_Leccion,Ejemplo_Leccion FROM leccion';
$stmt = sqlsrv_query($connectionInfo->conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("Numero_Leccion"=>$row['Numero_Leccion'],"Titulo_Leccion"=>$row['Titulo_Leccion'],"Ejemplo_Leccion"=>$row['Ejemplo_Leccion']);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
}
}
?>
Put error_reporting(E_ALL & ~E_NOTICE); ini_set('display_errors', '1'); somewhere on top of your script and see if there are any errors
(taken from Why echoing JSON encoded arrays won't produce any output)
Try this:
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$contacts[] = array("Numero_Leccion"=>$row['Numero_Leccion'],"Titulo_Leccion"=>$row['Titulo_Leccion'],"Ejemplo_Leccion"=>$row['Ejemplo_Leccion']);
}
header('Content-Type: application/json');
echo json_encode($contacts);
Related
<?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.
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
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
I have this code is working fine my application gets the data with json and is all fine but when I insert special characters like ñ which I need to get I can't have been told that I should use the utf8_encode but I just don't know how to apply it here since.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
if (isset($_POST['mod']) && isset($_POST['lec']) && isset($_POST['clase']))
{
$mod = $_POST['mod'];
$lec = $_POST['lec'];
$clase = $_POST['clase'];
//Create query to retrieve all contacts
$query = 'SELECT TituloEjercicio,PreguntaEjercicio,Opcion1Ejercicio,Opcion2Ejercicio,Opcion3Ejercicio,Opcion4Ejercicio,EstaCorrectaEjercicio FROM ejercicios WHERE QueModulo = ? and QueLeccion = ? and Queclase = ?';
$params = array($mod,$lec,$clase);
$stmt = sqlsrv_query($connectionInfo->conn, $query,$params);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("lbl_variable_cuestionario_titulo" => $row['TituloEjercicio'],
"lbl_variable_pregunta" => $row['PreguntaEjercicio'],
"opcion1" => $row['Opcion1Ejercicio'],
"opcion2" => $row['Opcion2Ejercicio'],
"opcion3" => $row['Opcion3Ejercicio'],
"opcion4" => $row['Opcion4Ejercicio'],
"EstaCorrecta" => $row['EstaCorrectaEjercicio']
);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
sqlsrv_close($connectionInfo->conn);
}
}
sqlsrv_close($connectionInfo->conn);
}
sqlsrv_close($connectionInfo->conn);
?>
If your issue lies with pushing non-latin characters to MySQL then you might just have to configure your database to use UTF8. There are good tutorials online that show you how to do that.
I am unable to parse data in PHP from MySQL.
Here's my code
<?php
header('Content-Type: text/html; charset=utf-8');
// array for JSON response
$response = array();
echo 'भगवान';
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT *FROM create_event") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["create_event"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["desc"] = $row["desc"];
$text;
array_push($response["create_event"], $product);
}
// success
$response["success"] = 1;
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
It's my database, I have set all the collation in utf-8 ci format but still not working:
I have tried all possible solutions and help online and have gone through popular posts and answers and also have set browsers settings to support Hindi lang but still displaying ? marks in output. Here is the output format
भगवान{"id":"1","desc":"???? ??????"}
mysql_query('SET character_set_results=utf8');
Use this after connecting to database or before using any select statement.