So I used php to connect my android app to a mysql database. I tested both the app and the queries on several small databases. Everything worked fine.
Using the old query on a larger database made the php query load forever in the web browser thus not displaying the intended JSON. So I made a new query but it doesn't display any result in the app, plus, it only displays the last result on the query. Is there any way for this to work out correctly?
Old php query that works on small db, but loads forever in the web browser with larger db:
<?php
error_reporting(0);
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT eid,marca,investimento,marcatotal,dataconstituicao,datainicio FROM empresa") or die(mysql_error());
header('content-type: application/json; charset=utf-8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
if (mysql_num_rows($result) > 0) {
$response["empresa"] = array();
while ($row = mysql_fetch_array($result)) {
$product = array();
$product["eid"] = $row["eid"];
$product["marca"] = $row["marca"];
$product["investimento"] = $row["investimento"];
$product["dataconstituicao"] = $row["dataconstituicao"];
$product["datainicio"] = $row["datainicio"];
array_push($response["empresa"], $product);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No empresa found";
echo json_encode($response);
}
?>
New php query that I created that displays ONLY the last result in web browser and doesn't show anything in the app on new larger db:
<?php
//error_reporting(E_ALL);
error_reporting(0);
require_once('db_config.php');
$conn = mysql_connect($db_server, $db_user, $db_password) or die(mysql_error());
$db= mysql_select_db($db_database, $conn);
$sql="SELECT eid,marca,investimento,marcatotal,dataconstituicao,datainicio FROM empresa" ;
header('content-type: application/json; charset=utf-8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
$rs = mysql_query($sql,$conn);
while ($row=mysql_fetch_assoc($rs))
{
$i=0;
foreach($row as $key => $value)
{
if (is_string($key))
{
$fields[mysql_field_name($rs,$i++)] = $value;
}
}
$json_result ["empresa"] = $fields;
}
$response = json_encode($json_result);
print_r($response);
?>
The aswer from Patrick Q is correct:
$json_result ["empresa"] had to be $json_result ["empresa"][] = $fields;
Also, his suggestion helped me solve my problem further since I just removed the success=1 logic alltogether from my app in order for it to work. Thank you all for the help!
Related
I need help with some code. I want to select data from mySQL to a graph on my web page.
The data must be from the current logged in user, and when I select data to a card it works fine, but when I select it to a graph the graph disappears.
I'm using this code for the cards, and it works fine:
$sql = "SELECT energyexpenditure FROM energy4project WHERE user_id = '{$_SESSION["user_id"]}' ORDER BY time_stamp DESC LIMIT 1;";
This is the code for my current graph that don't show data based on logged in user:
<?php
header('Content-Type: application/json');
$host = "localhost";
$user = "`blabla";
$pwd = "blabla";
$db = "blabla";
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT energyexpenditure, time_stamp FROM energy4project ORDER BY time_stamp DESC LIMIT 7;";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
echo json_encode($data);
?>
When I implement the code from the cards in the graph code it doesn't work.
Why does the SELECT WHERE user = '{$_SESSION["user_id"]} not work in the graphs?
If I understood good your Mysql query return an empty result. Try to modify your code as follows:
if(!$result = $conn->query($sql)) {
echo "query error.";
die();
}
$data = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
/* free result set */
$result->free();
/* close connection */
$conn->close();
//uncomment the below line if you want to check de result of your mysql query because it seems be good.
//var_dump($data); die(); echo "<pre>";
echo json_encode($data);
So if you don't have any mysql error, verify your database name, table name are correctly and if it has data in your table.
Reference: https://www.php.net/manual/en/mysqli-result.fetch-array.php
Regards
I've used the below code to generate JSON from a MySQL table. It works great when I'm only generating 2 arrays, but for some reason when I try and generate 3 or 4 arrays, I get the "white screen of death". I thought it was happening because I needed to bump up my PHP Memory Limit, but I've done that and still get the same problem. See below:
The code that works is:
<?php
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
But when I attempt to call more values, this is where I get the blank screen:
<?php
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
$row_array['customeremail'] = $row['customeremail'];
$row_array['customertel'] = $row['customertel'];
//push the values in the array
array_push($json_response,$row_array);
}
var_dump($json_response);
echo json_encode($json_response);
?>
Update**
The error appears to be with my last line (echo json_encode ($json_response);
The following output is generated when I add print_r($row) before that last line.
Array ( [id] => 1 [customerfname] => First [customerlname] => Last [customeremail] => test#test.com [customerphone] => 000-000-0000
Update 2
Adding var_dump($json_response); before the echo json_encode line results in the blank screen.
For future reference: If someone else is visiting this question due to having a similar problem, the error with the blank page occurred since the query returned too many rows and json_encode() did not seem to be able to handle it.
Try the following, and share with us your result,
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
//Create Database connection
$db = mysql_connect("localhost","user","dbpassword");
if (!$db)
die('Could not connect to db: ' . mysql_error());
mysql_select_db("dbname",$db);
mysql_query('SET CHARACTER SET utf8');
$result = mysql_query("select `customerfname`, `customerlname`, `customeremail`, `customertel` from customer", $db) or die("Error: ".mysql_error());
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$json_response[] = $row;
}
var_dump($json_response);
/* If the var_dump works, you can try and uncomment this section
if (function_exists('json_encode'))
{
echo json_encode($json_response);
echo "JSON Error: ".json_last_error();
}
else { echo "json_encode() is not supported"; }
*/
?>
When you use flcose($db) that is going to cause some trouble. remove that line.
flcose is used to close ressources such as writing to text files.
to close connection use mysql_close():
mysql_close($db);
and also Your loop can be reduce to this:
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
//push the values in the array
array_push($json_response,$row);
}
//Close the database connection
mysql_close($db);
echo json_encode($json_response);
and I would probably echo the json after closing the connection but thats no biggie.
And I find white screen of death very funny :D
I'm outputting some multi-lingual data from my database into a JSON object, but the output isn't showing foreign characters, it just shows question marks even though I have the header charset set to utf8 as such:
header('Content-Type: application/json; charset=utf-8');
When I look at the data in phpMyAdmin, it shows the characters correctly. Is there something I'm doing wrong?
Here is the PHP code that is formatting the JSON output:
$numRows = new stdClass();
$mysqli = dbiConnect();
$query = "SELECT * FROM country_codes";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
/* store result */
$stmt->store_result();
$numRows->cc = $stmt->num_rows;
/* close statement */
$stmt->close();
}
$mysqli->close();
$count = 0;
$dataCountryCodes = '{';
$mysqli = dbiConnect();
$query = "SELECT * FROM country_codes";
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_assoc()){
$count++;
$rowData = new stdClass();
$rowData->code = $row['code'];
$rowData->name = $row['name'];
$dataCountryCodes = $dataCountryCodes.'"'.$rowData->code.'": {"Code":"'.$rowData->code.'","Country":"'.$rowData->name.'"}';
if ($count != $numRows->cc) {
$dataCountryCodes = $dataCountryCodes.',';
}
}
}
$mysqli->close();
$dataCountryCodes = $dataCountryCodes.'}';
if ($returnCountryCodes == 1) {
return $dataCountryCodes;
} else {
header('Content-Type: application/json; charset=utf-8');
echo ($dataCountryCodes);
}
This is what I am getting:
{"AE": {"Code":"AE","Country":"United Arab Emirates (???????? ???????? ????????)"}}
This is what I got when it was hand coded, this would render fine after I translated the JSON to HTML:
{"AE": {"Code":"AE","Country":"United Arab Emirates (الإمارات العربيّة المتّØدة)"}}
You didn't show dbiConnect function. Check it and try using SET NAMES 'UTF8' after connecting to MySQL:
$con=mysqli_connect("host", "user", "pw", "db");
if (!$con)
{
die('Failed to connect to mySQL: ' .mysqli_connect_errno());
}
/* change character set to utf8 */
if (!$con->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $con->error);
}
As the manual says:
SET NAMES indicates what character set the client will use to send SQL
statements to the server... It also specifies the character set that the server should
use for sending results back to the client.
try this:
$mysqli = dbiConnect();
$mysqli->query("set names utf8")
I have a Microsoft Access Database, and I am trying to query the table using PHP, and output valid JSON. I have an equivalent code for a MSSQL database, am I am trying to make my code do the same thing, but just for the Access database.
Here is the MSSQL code
$myServer = "server";
$myDB = "db";
$conn = sqlsrv_connect ($myServer, array('Database'=>$myDB));
$sql = "SELECT *
FROM db.dbo.table";
$data = sqlsrv_query ($conn, $sql);
$result = array();
do {
while ($row = sqlsrv_fetch_array ($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
sqlsrv_free_stmt ($data);
sqlsrv_close ($conn);
Here is what I tried for the MDB file
$dbName = "/filename.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$sql = "SELECT *
FROM cemetery";
$data = $db->query($sql); // I'm getting an error here
$result = array();
// Not sure what do do for this part...
do {
while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
I kind of followed this to try to connect to the database: http://phpmaster.com/using-an-access-database-with-php/
Currently this is giving me a 500 Internal Server Error. I'm expecting a string such as this to be saved in the variable $json
[
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
etc...
}
]
Can someone help me port the MSSQL code I have above so I can use it with an MDB database? Thanks for the help!
EDIT: I'm commenting out the lines one by one, and it throws me the 500 error at the line $data = $db->query($sql);. I looked in the error log, and I'm getting the error Call to a member function query() on a non-object. I already have the line extension=php_pdo_odbc.dll uncommented in my php.ini file. Anyone know what the problem could be?
You only need 1 loop,
fetchAll is your iterable friend:
while ($row = $data->fetchAll(SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
odbc_connect doesn't return an object, it returns a resource. see (http://php.net/manual/en/function.odbc-connect.php) so you would need to do something like this.
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$oexec = obdc_exec($db,$sql);
$result[] = odbc_fetch_array($oexec);
and then you can iterate over results..
see also:
http://www.php.net/manual/en/function.odbc-fetch-array.php
http://www.php.net/manual/en/function.odbc-exec.php
I finally figured it out.
<?php
// Location of database. For some reason I could only get it to work in
// the same location as the site. It's probably an easy fix though
$dbName = "dbName.mdb";
$tName = "table";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT $tName.[ColumnOne], $tName.[ColumnTwo], etc...
FROM $dbName.$tName";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
$data = array();
$i = 0;
// Grabs all the rows, saves it in $data
while( $row = odbc_fetch_array($rs) ) {
$data[$i] = $row;
$i++;
}
odbc_close($conn); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
?>
I use this code to get results from an ODBC query into a JSON array:
$response = null;
$conn = null;
try {
$odbc_name = 'myODBC'; //<-ODBC connectyion name as is in the Windows "Data Sources (ODBC) administrator"
$sql_query = "SELECT * FROM table;";
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
//this will show all results:
//echo odbc_result_all($result);
//this will fetch row by row and allows to change column name, format, etc:
while( $row = odbc_fetch_array($result) ) {
$json['cod_sistema'] = $row['cod_sistema'];
$json['sistema'] = $row['sistema'];
$json['cod_subsistema'] = $row['cod_subsistema'];
$json['sub_sistema'] = $row['sub_sistema'];
$json['cod_funcion'] = $row['cod_funcion'];
$json['funcion'] = $row['funcion'];
$json['func_desc_abrev'] = $row['desc_abreviada'];
$json['cod_tipo_funcion'] = $row['cod_tipo_funcion'];
$response[] = array('funcionalidad' => $json);
}
odbc_free_result($result); //<- Release used resources
} catch (Exception $e) {
$response = array('resultado' => 'err', 'detalle' => $e->getMessage());
echo 'ERROR: ', $e->getMessage(), "\n";
}
odbc_close($conn);
return $response;
And finnally encoding the response in JSON format:
echo json_encode($response);
I am fetching some data having UTF8 collation (utf8_unicode_ci) from a MySQL database with PHP. I am using this piece of code:
function advancedDatabaseSearch($pattern, $lpref) {
$link = mysql_connect(DB_URL, DB_USER, DB_PWD);
if (!$link) {
return 'Could not connect: ' . mysql_error();
}
$esc_value = mysql_real_escape_string($pattern);
$esc_lpref = mysql_real_escape_string($lpref);
mysql_select_db(DB_NAME, $link);
$query = "SELECT RAWVALUE FROM rawvalueitem "
."WHERE RAWVALUE LIKE '".$esc_value."' "
."AND LANGUAGE = '".$esc_lpref."' "
."ORDER BY RAWVALUE ASC";
$result = mysql_query($query);
$return = "";
while($row = mysql_fetch_array($result)) {
$return = $return.$row['RAWVALUE']." ";
}
mysql_close($link);
return $return;
}
and then from the php called by Ajax:
$result = advancedDatabaseSearch($tttmp, $lpref);
echo $result;
return;
Yet, when I display the result in a text area, the accents are not displayed properly:
On the other side, when I fetch UT8 data from a file:
if ( $file_loc != NULL ) {
if ( file_exists($file_loc) ) {
$handle = fopen($file_loc, "rb");
$contents = fread($handle, filesize($file_loc));
fclose($handle);
$result = $contents;
}
}
echo $result;
return;
I don't get this issue !!! How can I solve it when using PHP to fetch data from MySql?
Did you set UTF-8 as the default character set of your database connection?
mysql_set_charset('utf8', $link);
http://www.php.net/manual/en/function.mysql-set-charset.php
Also, does your page have a <meta> tag with the correct character set?
This is working like a.. you now!
<?php
$config_db_server='localhost';
$config_db_server_username='root';
$config_db_server_password='';
$config_db_database='test';
$config_db_charset='utf8';
$config_db_collation='utf8_general_ci';
$config_table_prefix='class_';
$config_live_site='http://localhost';
$config_abs_path='C:\xampp\htdocs';
$config_debug=0;
$dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password);
mysql_query("SET character_set_results=utf8", $dbLink);
mb_internal_encoding('utf8');
mysql_query("set names 'utf8'",$dbLink);
?>
Change here your db connect: ( $dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password); )