I developed an android application with Mysql database. I would like the result of my sql query is displayed in a JSON variable in a table. If I use a single column of my TableA "country" ---> "id_country" or "name_en_country" it works but if I want to display more columns ---> "id_country" AND "name_en_country" AND more .. ... The result Requet php send me a blank page. Could you help me please thank you!
<?php
// Create Database connection
$mysqli = new mysqli("localhost", "root", "", "whenmeeat");
if (!$mysqli) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
}
// Replace * in the query with the column names.
$result = $mysqli->query("select id_country, name_en_country, name_fr_country from country", MYSQLI_USE_RESULT);
// Create an array
$json_response["country"] = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row_array['id_country'] = $row['id_country'];
$row_array['name_en_country'] = $row['name_en_country'];
// push the values in the array
array_push($json_response["country"],$row_array);
}
echo json_encode($json_response["country"]);
// Close the database connection
$mysqli->close();
?>
Based on the example set here json_encode() array in while loop for mySQL for calendar your code should alter like this:
<?php
// Create Database connection
$mysqli = new mysqli("localhost", "root", "", "whenmeeat");
if (!$mysqli) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
}
// Replace * in the query with the column names.
$stmt = $mysqli->prepare("SELECT `id_country`, `name_en_country`, `name_fr_country` FROM `country`");
$stmt->execute();
$res = $stmt->get_result();
// Create an array
$json = array();
while ($row = $res->fetch_assoc()) {
$country = array(
'id_country' => $row['id_country'],
'name_en_country' => $row['name_en_country'],
'name_fr_country' => $row['name_fr_country']
);
$json[] = $country ;
}
echo json_encode($json);
// Close the database connection
$mysqli->close();
?>
Related
I am stuck in my PHP page for a json_encode since a couple of days after having done 9999 tests.
The goal is to log on a swift app using mySql database.
So I guess i have something wrong in my query, and i dont know how to send answer of found/not found user in json_encode().
Here is my php code:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
// i get the email and password sent as parameter
// my swift code is working, and the next line is ok.
$logs[] = array('email' => $obj->email, 'pass' => $obj->pass);
//echo json_encode($logs); // to send back my logs (ok)
// Create connection
$con = mysqli_connect("localhost", "xx", "xx", "xx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//echo json_encode($logs);
// its working until here if i execute the previous line and put the rest in comment
// from the next line its making errors such :
// Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set."
$sql = "SELECT * FROM clients WHERE email = '".$logs['email']."'";
//echo json_encode($logs); //not working at this place if i put the rest in comment.
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object()) {
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
//check the corresponding password
if ( $logs['pass'] == $resultArray[4]) {
// i m not sure how to send the answer as a json
echo json_encode(true);
} else {
echo json_encode(false);
}
}
// Close connections
mysqli_close($con);
?>
If I try in php without all json stuff, its working since I put
$sql = "SELECT * FROM clients WHERE email = 'ben#test.be'";
as a test.
The following code works:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
$logs[] = array('email' => $obj->email, 'pass' => $obj->pass);
$con = mysqli_connect("localhost", "xx", "xx", "xx");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM clients";
if ($result = mysqli_query($con, $sql))
{
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
}
mysqli_close($con);
?>
But if I put $sql = "SELECT * FROM clients WHERE email = '$logs['email']'"; instead of $sql = "SELECT * FROM clients";
Its not working anymore. It doesn't like my conditional query. What did I misunderstood?
I need to connect to two databases using PHP and use the results from the first query to get the rest of the data I need out of a second database.
So for the second connection, I need to connect to the second database and Select state and zipcode where the results from connection 1 (client) is equal to the firstname in database 2. How would I do this?
<?php
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['cd']) && is_numeric($_GET['cd'])) {
// get id value
$id = intval($_GET['cd']);
}
$results = $id;
//Open a new connection to the MySQL server
require "calendarconnect.php";
//chained PHP functions
$client = $mysqli->query("SELECT client FROM appointments WHERE ID = $results")->fetch_object()->client;
print $client; //output value
$mysqli->close();
Connection To Database Code is similar to the below
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some database','some password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
This isn't tested, but I think it would go something like this.
<?php
$dbc1 = new MySQLi()or die('error connecting to database');
$dbc2 = new MySQLi()or die('error connecting to database');
//build query 1
$query1 = "SELECT * FROM Table";
$result1 = $dbc1->query($query) or die("Error in query");
$thing1 = '';
// check result
if($result1->num_rows){
//fetch result as object
$row = $result1->fetch_object();
//set attributes
$thing1 = $row->Name;
}
//build query 2
$query2 = "SELECT * FROM AnotherTable WHERE Id = '$thing1'";
$result2 = $dbc2->query($query) or die("Error in query");
$thing2 = '';
// check result
if($result2->num_rows){
//fetch result as object
$row = $result2->fetch_object();
//set attributes
$thing2 = $row->Name;
}
?>
You would need to make 2 different connections
<?php
$mysqliDB1 = new mysqli('localhost', 'DB1UserId', 'pwd', 'db1');
$mysqliDB2 = new mysqli('localhost', 'DB2UserId', 'pwd', 'db2');
Now when you use the $mysqliDB1->.... you are talking to the DB1 database and when you use the $mysqliDB2->.... you are talking to the DB2 database
So
$client = $mysqliDB1->query("SELECT client FROM appointments WHERE ID = $results")
->fetch_object();
$locn = $mysqliDB2->query("SELECT state,zipcode
FROM location
WHERE ClientID = {$client->FirstName}")
->fetch_object();
echo $locn->state;
echo $locn->zipcode;
I am guessing the table name and so on, but I am not clarevoyant so you will have to fill that in for yourself.
If you want to perform queries in two databases at the same time you need to have two separate mysqli objects. To open the connection you can use the following code:
// Don't forget to enable error reporting!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db1 = new mysqli('localhost', 'user', 'pass', 'dbName');
$db1->set_charset('utf8mb4'); // always set the charset
$db2 = new mysqli('localhost', 'user', 'pass', 'dbName2');
$db2->set_charset('utf8mb4'); // always set the charset
Then you can perform your two statements in each database separately.
// get id value
$id = intval($_GET['cd']);
// Get client name from DB1
$stmt = $db1->prepare('SELECT client FROM appointments WHERE ID = ?');
$stmt->bind_param('s', $id);
$stmt->execute();
$client = $stmt->get_result()->fetch_object();
// Get state and zipcode from DB2
$stmt = $db2->prepare('SELECT state,zipcode FROM location WHERE ClientName = ?');
$stmt->bind_param('s', $client->client);
$stmt->execute();
$location = $stmt->get_result()->fetch_object();
echo $location->state;
echo $location->zipcode;
Hi I have the following code below in a php file
global $server, $mysqlusername, $mysqlpassword, $db;
$conn = new mysqli($server, $mysqlusername, $mysqlpassword, $db);
function getCategories() {
global $conn;
$categories = array();
$sql = "SELECT categoryName FROM reportcategorys";
$maincat = $conn->query($sql);
while($row = $maincat->fetch_array(MYSQLI_ASSOC)) {
// do something with the $row
array_push($categories, $row);
}
$sql1 = "SELECT * FROM reportsubcategorys";
$subcats = $conn->query($sql1);
// Loop through sub categories and append to parent array
while($row = $subcats->fetch_array(MYSQLI_ASSOC)) {
$parent = $row['categoryName'];
$name = $row['subCategoryName'];
// Append subcategory name as child to the parent category
for ($i=0; $i<count($categories); $i++) {
if ($categories[$i]['categoryName'] == $parent) {
array_push($categories[$i], $name);
}
}
}
//print_r($categories);
return $categories;
}
It is giving me an error message saying
"Fatal error: Call to a member function fetch_array() on a non-object in"
Any idea what may be causing this?
Thanks
It is likely that your query has not executed properly.
mysqli->query() will return a boolean value FALSE if the query has not been executed properly, else it will return a mysqli_result object. So after every query, before calling fetch_array() method, check the result of the query. Something like this.
$maincat = $conn->query($sql) or die($conn->error);
or
$maincat = $conn->query($sql);
if(!$maincat){
echo $conn->error;
}
Also, when you established your connection with the database, check if the connection was error-free.
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
Are you using fetch_array for any reason in particular?
Try it like this one...
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* verificar la conexión */
if (mysqli_connect_errno()) {
printf("Conexión fallida: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* obtener array asociativo */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* liberar el resultset */
$result->free();
}
/* cerrar la conexión */
$mysqli->close();
?>
I'm attempting to set up an API for an app project.
I've got a mysql table called 'users', which I've added a row to.
using the code:
// Create connection
$mysqli = new mysqli("localhost","user", "pass", "db");
// Check connection
if($mysqli->connect_errno){
$result = "Failed to connect to MySQL: " . mysqli_connect_error();
print_r( json_encode($result) );
return false;
}
$row = $mysqli->query("SELECT * FROM users");
print_r( json_encode($row) );
I get an empty result, how come? (connection doesn't throw an error)
to be exact i get:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
EDIT:
got the answer to ym original question, thanks!
so now using the code:
$row = $mysqli->query("SELECT * FROM users WHERE email = '".$email."'");
$result = $row->fetch_array();
print_r( json_encode($result) );
I get the result:
{"0":"test","username":"test","1":"test#test.com","email":"test#test.com","2":"test","password":"test","3":"2013-10-18 22:22:53","date_registered":"2013-10-18 22:22:53","4":"1","id":"1"}
where what i want is something like:
{"username":"test","password":"test","email":"test#test.com", ...etc }
how do i get that?
Try this:
$result = $mysqli->query("SELECT * FROM users");
$row = $result->fetch_array(MYSQLI_ASSOC);
print json_encode($row); // json_encode returns a string...
Try this for your associative array:
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$rows[] = $row;
}
print json_encode($rows);
or you can try... $rows = $result->fetch_all(MYSQLI_ASSOC);
mysqli_query() will return a mysqli_result, you need to fetch (as an array in this case) your rows before doing anything with them. Added a line:
// Create connection
$mysqli = new mysqli("localhost","user", "pass", "db");
// Check connection
if($mysqli->connect_errno){
$result = "Failed to connect to MySQL: " . mysqli_connect_error();
print_r( json_encode($result) );
return false;
}
// Get a mysql_result
$row = $mysqli->query("SELECT * FROM users");
// Get it into an array without numeric indexes
$result = $row->fetch_assoc();
// Display the row
print_r( json_encode($result) );
I am storing MySQL Query value in PHP variable, but its not displaying data. P.S: Data is available in MySQL table column.
<?php
$cmsca= mysql_query("SELECT SUM(qa_effort) FROM tbl_uat WHERE product='CAP'");
while ($cresulta = mysql_fetch_array ($cmsca))
$arra[0] = $cresulta[0];
echo $arra[0];
?>
I am out of clues, what is wrong in above code? Need help!
Regards
try this
<?php
$cmsca= mysql_query("SELECT SUM(qa_effort) as sums FROM tbl_uat WHERE product='CAP'");
while ($cresulta = mysql_fetch_array($cmsca))
{
echo $cresulta['sums'];
}
?>
first of all, do not use mysql_query, - it's deprecated, use http://www.php.net/manual/en/mysqli.query.php instead.
Next, you need to connect to the db, before running query;
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$result = mysqli->query("SELECT SUM(qa_effort) as sums FROM tbl_uat WHERE product='CAP'");
while ($row = $result->fetch_array()) {
var_dump($row);
}
$mysqli->close();
?>
How about trying this:
<?php
$arra = array();
$cmsca= mysql_query("SELECT SUM(qa_effort) FROM tbl_uat WHERE product='CAP'");
while ($row = mysql_fetch_array ($cmsca))
$arra = $row;
print_r($arra);
?>