I know this question has already been asked here, but there is still no solution for me ...
I have $http.post request to the server. It should return me the JSON file.
$http.post(getCountry, angular.toJson({country: true})).then(function (data) {
$scope.countries = data.data;
console.log( 'Success', $scope.countries);
}, function (err) {
console.log('err');
});
The php code, which should send request to MySQL is as fallows:
$connection = mysqli_connect($server, $login, $password, $db) or die("Connection error" . mysqli_error($connection));
if ($country == 1) {
$sql = "SELECT name_ru, id FROM net_country ORDER BY name_ru";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
}
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
This one returns JSON with "?????" instead of the "name_ru"
When I change "name_ru" to "name_en" - everything is ok.
I have no idea how to fix it.
UTF-8 charset is everywhere
Related
I am trying to make a php REST API for my mobile backend to interact with a MySQL database. I have written out the following code to try and retrieve data from a MySQL query:
<?php include "FILE WITH DB_INFO"; ?>
<html>
<body>
<h1>Testing page</h1>
<?php
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL" . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
if (strlen($username_query)) {
doesUsernameExist($connection, $username_query);
}
doesUsernameExist($connection, $username_query);
$username_query = $_GET['usernameToQuery'];
echo($_GET['usernameToQuery']);
function doesUsernameExist($connection, $username) {
$u = mysqli_real_escape_string($connection, $username);
$query = "SELECT username from users WHERE username = ('$u');";
if (!mysqli_query($connection, $query)) {
$response = array("success" => false, "message" => mysqli_error($connection), "sqlerrno" => mysqli_errno($connection), "sqlstate" => mysqli_sqlstate($connection));
echo json_encode($response);
} else {
$sth = mysqli_query($connection, $query);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
$response = array("success" => true);
echo json_encode($rows);
}
}
?>
This is what the actual request looks like: http://my_ec2_instance/DoesUsernameExist.php?usernameToQuery=lmao.
This is sent through POSTMAN.
Because the MySQL database that I am using contains usernames with the value lmao, the php function should return an array that is not empty. But the json_encode($rows); line returns an empty array []. What am I doing wrong.
It seems you call doUsernameExiste() and just before strlen with a variable $username_query. But you define $username_query only after.
You should first do your affectation. Put this after your line with the mysqli_select_db
$username_query = $_GET['usernameToQuery'];
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 keep receiving my JSON from my web service inside quotation marks, like this:
"[{"id":"1","nombre":"Cecilia","correo":"csoto#ts.edu.mx","telefono":"5529964"},{"id":"2","nombre":"Romero","correo":"","telefono":"5435432"},{"id":"3","nombre":"nick","correo":"carlos#mail.com","telefono":"12345"}]"
Notice the "" before the brackets and I don't know why.
I'm using jacwright's restServer (https://github.com/jacwright/RestServer) with this function:
public function getUsers()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "estudiantes";
// Create connection
$array = array();
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, nombre, correo, telefono FROM estudiante";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$res = array("id" => $row["id"], "nombre" => $row["nombre"], "telefono" => $row["telefono"], "correo" => $row["correo"]);
array_push($array, $res);
//echo "id: " . $row["id"]. " - Name: " . $row["nombre"]. " " . $row["correo"]. "<br>";
}
}
$conn->close();
return json_encode($array) ;
}
Can somebody insight me why it keeps adding these quotation marks?
Just a quick example simulating your case, using echo to return JSON encoded array:
JS:
$.get('json.php', function(data) {
console.log(data);
if (data) {
//Check the console, everything is working like charm
newData = $.parseJSON(data);
console.log(data);
console.log('--------------' + 'Elements count:' + newData.length);
console.log('--------------' + newData);
}
});
json.php:
<?php
$myArr = array(
array("id"=>"1","nombre"=>"Cecilia","correo"=>"csoto#ts.edu.mx","telefono"=>"5529964"),
array("id"=>"2","nombre"=>"Romero","correo"=>"","telefono"=>"5435432"),
array("id"=>"3","nombre"=>"nick","correo"=>"carlos#mail.com","telefono"=>"12345")
);
$jsonData = json_encode($myArr);
echo $jsonData;
?>
Same above code using return $jsonData; instead of echo $jsonData; in json.php it gives me the following in the console:
emptiness for data
console error:
ReferenceError: newData is not defined
The reason of getting the quotes in the returned string is because the server (https://github.com/jacwright/RestServer) is doing json_encode itself. So when you return the data from your function getUsers and you have used json_encode it is converted to a json string and when RestServer returns it to you it sees it only as a string therefore adding quotes around it.
If you look at the TestController you will see that it returns an object $user not json_encode($user) and RestServer in it's sendData function actually uses the json_encode function.
So your code needs to be:
public function getUsers()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "estudiantes";
// Create connection
$array = array();
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, nombre, correo, telefono FROM estudiante";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$res = array("id" => $row["id"], "nombre" => $row["nombre"], "telefono" => $row["telefono"], "correo" => $row["correo"]);
array_push($array, $res);
//echo "id: " . $row["id"]. " - Name: " . $row["nombre"]. " " . $row["correo"]. "<br>";
}
}
$conn->close();
return $array;
}
Also check out the function sendData in https://github.com/jacwright/RestServer/blob/master/source/Jacwright/RestServer/RestServer.php#L414 on line 414.
This query works fine for me, it gets my results and echos them back. But what I am missing and can not get to work is to get a separator in between the results. I have tried to use the implode function but was unable to. What I would like is a "|" in between the results in the echo. Below is my code I am using, any help or direction would be greatly appreciated.
$dbh = mysqli_connect("xxxxxxxxxxx", $user_name, $password, $database_name);
if (!$dbh)
{
die("Not connected : " . mysqli_error($dbh));
}
else
{
$query = "SELECT value FROM `$table_name` WHERE field IN('$field1', '$field2')";
$result = mysqli_query($dbh,$query);
if (mysqli_num_rows($result) == 0) {
echo "NO_DATA_FOUND";
}
else
{
while ($result_list = mysqli_fetch_array($result, MYSQL_ASSOC))
echo '' .$result_list["value"] . '';
}
mysqli_close($dbh);
}
?>
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);