I can't insert a json on MongoDB with PHP script - php

<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
try {
$link = mysqli_connect('localhost', 'root', '')
or die('No se pudo conectar: ' . mysqli_error());
mysqli_select_db($link,'classicmodels5') or die('No se pudo seleccionar la base de datos');
$query = "select c.customerNumber,c.customerName,c.city as customerCity, c.country as customerCountry,c.salesRepEmployeeNumber from customers as c";
$result = mysqli_query($link,$query);
$isFirst=0;
$isFirst2=0;
$isFirst3=0;
$isFirst4=0;
$json="";
while ($fila = mysqli_fetch_array($result)) {
$bulk = new MongoDB\Driver\BulkWrite;
$isFirst2=0;
$isFirst3=0;
$isFirst4=0;
extract($fila);
$json = $json."{";
//$json = $json.",{";
$json = $json.'"customerNumber":'.$fila["customerNumber"].',';
$json = $json.'"customerName":"'.$fila["customerName"].'",';
$json = $json.'"city":"'.$fila["customerCity"].'",';
$json = $json.'"country":"'.$fila["customerCountry"].'"';
//INICIO:INSERTAR PAYMENTS
$query2 = "select p.checkNumber,p.amount from payments as p where p.customerNumber=".$fila["customerNumber"];
$result2 = mysqli_query($link,$query2);
if(mysqli_num_rows($result2)>0){
$json=$json.',"payments":[';
}
while ($fila2 = mysqli_fetch_array($result2)) {
extract($fila2);
if($isFirst2==1){
$json = $json.",{";
}else{
$json = $json."{";
}
$json = $json.'"checkNumber":"'.$fila2["checkNumber"].'",';
$json = $json.'"amount":"'.$fila2["amount"].'"}';
$isFirst2=1;
}
if(mysqli_num_rows($result2)>0){
$json=$json.']';
}
//FIN:INSERTAR PAYMENTS
//INICIO: INSERTAR EMPLOYEE
$query3 = "SELECT e.employeeNumber,e.lastName,e.extension,e.officeCode FROM employees as e where e.employeeNumber=".$fila["salesRepEmployeeNumber"];
$result3 = mysqli_query($link,$query3);
if(mysqli_num_rows($result3)>0){
$json=$json.',"employees":[';
}
while ($fila3 = mysqli_fetch_array($result3)) {
extract($fila3);
if($isFirst3==1){
$json = $json.",{";
}else{
$json = $json."{";
}
$json = $json.'"employeeNumber":"'.$fila3["employeeNumber"].'",';
$json = $json.'"lastName":"'.$fila3["lastName"].'",';
$json = $json.'"extension":"'.$fila3["extension"].'"';
//INICIO:INSERTAR OFFICE
$query4 = "SELECT o.officeCode,o.city,o.country FROM offices as o where o.officeCode=".$fila3["officeCode"];
$result4 = mysqli_query($link,$query4);
if(mysqli_num_rows($result4)>0){
$json=$json.',"officeCode":';
}
while ($fila4 = mysqli_fetch_array($result4)) {
extract($fila4);
if($isFirst4==1){
$json = $json.",{";
}else{
$json = $json."{";
}
$json = $json.'"officeCode":"'.$fila4["officeCode"].'",';
$json = $json.'"city":"'.$fila4["city"].'",';
$json = $json.'"country":"'.$fila4["country"].'"}';
$isFirst4=1;
}
//FIN:INSERTAR OFFICE
$isFirst3=1;
}
if(mysqli_num_rows($result3)>0){
$json=$json.'}]';
}
//FIN:INSERTAR EMPLOYEE
$json = $json.'}';
echo $json."</br>";
//Hacer el insert
$bulk->insert(json_decode($json));
$resultFinal = $manager->executeBulkWrite('test.prueba3', $bulk);
$json="";
$isFirst=1;
}
$json = str_replace("'", " ", $json);
echo $json;
//echo $json;
/* $bulk->insert(json_decode($json));
$resultFinal = $manager->executeBulkWrite('test.customers', $bulk);
var_dump($resultFinal);*/
}catch(Exception $e) {
echo "EXCEPTION: ".$e->getMessage(), "\n";
exit;
}
?>
When I do the inserted, for every time I finish the first loop, I get the following error, I do not understand if it is because the JSON is wrong or should be inserted in another way
Warning: MongoDB\Driver\BulkWrite::insert() expects parameter 1 to be array, null given in C:\xampp2\htdocs\prac\index.php on line 111
EXCEPTION: Cannot do an empty bulk write
I need every time I finish the first loop insert the JSON document for in the next lap add another, I get that error but when validating my json in JSONLint, I get that is valid. is a migration from MySQL to MongoDB.
This is the JSON that gives error, which I think is correctly written, where do you think this error? Thank you
{"customerNumber":144,"customerName":"Volvo Model Replicas, Co","city":"Lule�","country":"Sweden","payments":[{"checkNumber":"IR846303","amount":"36005.71"},{"checkNumber":"LA685678","amount":"7674.94"}],"employees":[{"employeeNumber":"1504","lastName":"Jones","extension":"x102","officeCode":{"officeCode":"7","city":"London","country":"UK"}}]}

I simplified your code to this:
<?php
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
try {
$json='{"customerNumber":144,"customerName":"Volvo Model Replicas, Co","city":"Lule�","country":"Sweden","payments":[{"checkNumber":"IR846303","amount":"36005.71"},{"checkNumber":"LA685678","amount":"7674.94"}],"employees":[{"employeeNumber":"1504","lastName":"Jones","extension":"x102","officeCode":{"officeCode":"7","city":"London","country":"UK"}}]}';
$bulk = new MongoDB\Driver\BulkWrite;
echo $json."</br>";
//Hacer el insert
$bulk->insert(json_decode($json));
$resultFinal = $manager->executeBulkWrite('test.prueba3', $bulk);
$json="";
$isFirst=1;
}catch(Exception $e) {
echo "EXCEPTION: ".$e->getMessage(), "\n";
exit;
}
And is printed JSON and saved data do mongodb
> db.prueba3.find().pretty()
{
"_id" : ObjectId("5b13bbda65b9bb1f3e6b9922"),
"customerNumber" : 144,
"customerName" : "Volvo Model Replicas, Co",
"city" : "Lule�",
"country" : "Sweden",
"payments" : [
{
"checkNumber" : "IR846303",
"amount" : "36005.71"
},
{
"checkNumber" : "LA685678",
"amount" : "7674.94"
}
],
"employees" : [
{
"employeeNumber" : "1504",
"lastName" : "Jones",
"extension" : "x102",
"officeCode" : {
"officeCode" : "7",
"city" : "London",
"country" : "UK"
}
}
]
}
Please confirm that this example works in your case. If not you can compare $json that is defined in this example and your $json before comment //Hacer el insert.
Any way if is it possible please isolate your problem. Including such huge amount of code is not so useful as smaller. To help other to response you can use exemplary data instead of pasting code with selects from database.
Concatenating JSON from string is very bad practice. Imagine that one of your string contains character like this: "{". Did you escaped it?
Potentially problem can be connected with encoding Lule�. You are using Windows, maybe your text of your code or SQL database has encoding different than UTF-8.

Related

JSON encode is not working properly with varchar

I created an API for the Java desktop application because I want to get the data from an online database. The beginning was fine. But some parts were not shown as required. Below is how the data is in the database.
patient_id patient_name patient_nic patient_dob patient_note
PTT00001 Rebecca J Burns 988249675V 1998-12-17 Had previously taken medicine for...
PTT00002 Erica L Prom 926715648V 1992-06-21 To show up a second time for...
The PHP code I used to get this as JSON is as follows and it doesn't show any output(A blank page appeared)
PHP Code :
<?php
$con = mysqli_connect("localhost", "root", "", "on_dam_sys");
$response = array();
if($con){
$sql = "select * from patient";
$result = mysqli_query($con,$sql);
if($result){
header("Content-Type: JSON");
$i = 0;
while($row = mysqli_fetch_assoc($result)){
$response[$i]['patient_id'] = $row ['patient_id'];
$response[$i]['patient_name'] = $row ['patient_name'];
$response[$i]['patient_nic'] = $row ['patient_nic'];
$response[$i]['patient_dob'] = $row ['patient_dob'];
$response[$i]['patient_note'] = $row ['patient_note'];
$i++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
}
?>
But when the patient_name is removed using the same code, everything except it appears as below. What is the reason for that?
PHP code 2 :
<?php
$con = mysqli_connect("localhost", "root", "", "on_dam_sys");
$response = array();
if($con){
$sql = "select * from patient";
$result = mysqli_query($con,$sql);
if($result){
header("Content-Type: JSON");
$i = 0;
while($row = mysqli_fetch_assoc($result)){
$response[$i]['patient_id'] = $row ['patient_id'];
$response[$i]['patient_nic'] = $row ['patient_nic'];
$response[$i]['patient_dob'] = $row ['patient_dob'];
$response[$i]['patient_note'] = $row ['patient_note'];
$i++;
}
echo json_encode($response, JSON_PRETTY_PRINT);
}
}
?>
Output for PHP code 02 :
[
{
"patient_id": "PTT00001",
"patient_nic": "988249675V",
"patient_dob": "1998-12-17",
"patient_note": "Had previously taken medicine for fever and still not cured. The body is lifeless."
},
{
"patient_id": "PTT00002",
"patient_nic": "926715648V",
"patient_dob": "1992-06-21",
"patient_note": "To show up a second time for heart disease. She is ready for surgery"
}
]
I also need to get the patient_name
Probably in one of the patient "name" there is some invalid char, in this case json_encode() simply return false, add JSON_THROW_ON_ERROR so the execution stop throwing an error.
echo json_encode($response, JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
Probably, adding also JSON_INVALID_UTF8_IGNORE will solve the problem.
Anyway, it is worth to find the offending row.

PHP Script does not echo json encoded array

I have a php script which should echo a bunch of datasets in a json encoded string. Though the page is blank.
<?php
$con = mysqli_connect("SERVER", "USER", "PASSWORD", "DATABASE");
if(!$sql = "SELECT news.title, news.content, login.username, news.id, news.date, news.timestamp, news.importance, news.version FROM news INNER JOIN login ON news.id = login.id ORDER BY timestamp DESC") {
echo "FAIL";
}
mysqli_query($con,$sql);
$res = mysqli_query($con,$sql);
$result = array();
while($row = $res->fetch_array())
{
array_push($result,
array('title'=>$row[0],
'content'=>$row[1],
'author'=>$row[2],
'id'=>$row[3],
'date'=>$row[4],
'timestamp'=>$row[5],
'importance'=>$row[6],
'version'=>$row[7]
));
}
$oldjson = json_encode(["result"=>$result]);
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
What is the problem here? I tried some error detection with if(!..) but it did not help. I think the problem may be the array creation and/or echo, though I cannot figure out how to fix that.
You should check the result of json_encode, since you are encoding data that comes from the database you might have some stuff that requires escaping.
$json = json_encode(...);
if ($json === false) {
echo "Error = " . json_last_error() . " " . json_last_error_msg();
// You may want to var_dump the $result var here to figure out what the problem is
} else {
echo $json; // Should be ok
}

filter and get data from Mysql

I have this table:
I need to get in an array all data from column "codigo" which has rows codidopostal = 1001. For this pourposse I am sending by "post" codigopostal = 1001.
Once I get it, then I need the first data from array to be extracted because later I will use it to add in an URI to make and query to an external server which have file in xml.
The uri I am building is:
"http://www.aemet.es/xml/municipios/localidad_01059.xml"
I make this.
http://www.aemet.es/xml/municipios/localidad_ + "0" + "codigo" + ".xml
but it do not add me "codigo". As it can be seen in photo, add only "0" but not "0" + "codigo".
Here I leave full code, any help will be welcome:
<?php
require_once 'login_mysql.php';
if(isset($_POST['postCode']) && !empty($_POST['postCode'])){
$sql = "SELECT alava.codigo FROM alava WHERE alava.codigopostal = '$postCode'";
if (mysqli_connect_error()){
echo 'Error de Conexión: ' . mysqli_connect_error();
exit();
}
$r = mysqli_query($con,$sql);
if (!$r){
echo 'No se pudo hacer la consulta: ' . mysqli_error($con);
echo json_encode("Registro inexistente");
exit();
}
$result = array();
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"codigo"=>$row['codigo']
));
$codigo = array_values($result)[0];
}
echo json_encode(array('result'=>$output_result));
// Close mysql connection
mysqli_close($con);
}else{
echo "Operacion fallida";
}
$json_object = json_decode( json_encode(array('result'=>$result)) );
$localidad = "$codigo";
$cadena1 = "http://www.aemet.es/xml/municipios/localidad_";
$cadena2 = "$localidad";
$cadena3 = ".xml";
$prefijo = "0";
$url=$cadena1 . $prefijo . $cadena2 . $cadena3 ;
$texto = file_get_contents($url);
$texto = str_replace(array("\n", "\r", "\t"), '', $texto);
$texto = trim(str_replace('"', "'", $texto));
$simpleXml = simplexml_load_string($texto);
$json = json_encode($simpleXml);
echo $json;
return $json;
I found solution-
First query correctly to table extracting all data with specific index. In this case is "codigopostal.
require_once 'login_mysql.php';
if(isset($_POST['postCode']) && !empty($_POST['postCode'])){
$postCode = $_POST['postCode'];
$sql =
"SELECT * FROM wp_alava WHERE wp_alava.codigopostal = '$postCode'";
Then we take data and we input it in array. Once it is inside, then we take the first one, since all are duplicated and we only need one, and because we do not know how many there are, we are sure that there is one which is the first one.
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
array_push($result,array(
//Pushing codigo in the blank array created
"codigo"=>$row['codigo']
));
}
//Displaying the array in json format
$codigo_poblacion = json_encode(array('result'=>$result));
$primer_codigo_encontrado = json_decode($codigo_poblacion);
$primer_codigo_encontrado->result[0]->codigo;
$codigo_poblacion_aemet = $primer_codigo_encontrado->result[0]->codigo;
then we build our URI and send it geting data. Because data we need in Json, we parse it inrto JSon Format in order to be used later in our APP or any other User Interface.
That is all, here you have an API to build an URI for Spanish Weather Web which did not give it, they only give you XML for forecasts.
Regards

Insert data from json to mysql table from php

im trying to insert data into a table from a json file but the rows gets 0. not the value from json
DB
JSON code:
{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
}]
}
$connection = mysql_connect("localhost", "***", "!*****!");
if (!$connection)
{
die('PHP Mysql database connection could not connect : ' . mysql_error());
}
$db_selected = mysql_select_db("*****", $connection);
$result=mysql_query("SELECT * FROM $tbl_name wHERE ad_IMEI=ad_IMEI ");
$i=0;
while($row=mysql_fetch_array($result)) {
$response[$i]['dr_DeviceID'] = $row['ad_IDDevice'];
$response[$i]['dr_UserLocalLat']= $row['user_location_lat'];
$response[$i]['dr_UserLocalLong']= $row['user_location_long'];
$data['posts'][$i] = $response[$i];
$i=$i+2;}
$json_string = json_encode($data);
$file = 'select.json';
file_put_contents($file, $json_string);
$jsondata = file_get_contents('select.json');
$obj = json_decode($jsondata, true);
$id = $obj['posts']['dr_DeviceID'];
$dr_UserLocalLat = $obj['posts']['dr_UserLocalLat'];
$dr_UserLocalLong = $obj['posts']['dr_UserLocalLong'];
$sqlj = "INSERT INTO $tbl_name1 (dr_DeviceID, dr_UserLocalLat, dr_UserLocalLong) VALUES('$dr_DeviceID', '$dr_UserLocalLat', '$dr_UserLocalLong')";
$result=mysql_query($sqlj,$connection);
The problem is that you're trying to access an array of objects as if it was a single one.
With this line here
$data['posts'][$i] = $response[$i];
you add an item to the $data['posts'] array. If your result had more than one row, the json example you've left above would be
{
"posts": [{
"dr_DeviceID": "323",
"dr_UserLocalLat": "38.7482572",
"dr_UserLocalLong": " -9.1847516"
},
{
"dr_DeviceID": "324",
"dr_UserLocalLat": "39.7482572",
"dr_UserLocalLong": " -19.1847516"
}]
}
So, when you decode your json afterwards, you get an array of objects. To access every item in the array, you need some loop cycle. Otherwise, to get the first item from the json, you would need to do
$obj['posts'][0]['dr_UserLocalLat'], instead of $obj['posts']['dr_UserLocalLat'].

Null values returned in JSON response to query even though no null values present in database

I want to fetch the above data using php, I pass the email as a parameter and I want to retrieve all records which have user = email. However, the response I get is a bit odd. My main concern is the odd formatting and the presence of null values. I'm sure I have a minor mistake in the code somewhere, but as I am not that familiar with php I'm finding it difficult to identify the error. The output looks like this:
{"0":"5phd6ure1lj941cv81o00tb4jr","id":null,"1":"8","stake":"8","2":"tester#tester.com","user":"tester#tester.com","3":"29","returns":"29","4":"(9\/X)","teams":"(9\/X)","5":"open","status":"open","bet":{"stake":null,"user":null,"returns":null,"teams":null,"status":null}}
These are the two files I use:
Get_Bets.php
<?php
class Get_Bets {
private $db;
function __construct() {
require_once 'DB_Connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
function __destruct() {
}
public function getUsersBets($email) {
$conn=mysqli_connect("****", "***", "***","***");
$result = mysqli_query($conn,"SELECT id,stake,user,returns,teams,status FROM bet WHERE user = '$email'");
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
$result = mysqli_fetch_array($result);
return $result;
}
}
}
?>
Get_All_Bets.php
<?php
if (isset($_POST['email']) && $_POST['email'] != '') {
// get tag
$email = $_POST['email'];
// include db handler
require_once 'include/Get_Bets.php';
$db = new Get_Bets();
// response Array
$response = $db->getUsersBets($email);
$response["id"] = $bet["id"];
$response["bet"]["stake"] = $row["stake"];
$response["bet"]["user"] = $row["user"];
$response["bet"]["returns"] = $row["returns"];
$response["bet"]["teams"] = $row["teams"];
$response["bet"]["status"] = $row["status"];
echo json_encode($response);
}
?>
In Get_All_Bets.php, this code segment causes the error
$response["id"] = $bet["id"];
$response["bet"]["stake"] = $row["stake"];
$response["bet"]["user"] = $row["user"];
$response["bet"]["returns"] = $row["returns"];
$response["bet"]["teams"] = $row["teams"];
$response["bet"]["status"] = $row["status"];
Remove it and the output will be O.K
Now let's discuss what's happening
after this line $response = $db->getUsersBets($email); the $response variable looks like that:
{
"0": "5phd6ure1lj941cv81o00tb4jr",
"id": "5phd6ure1lj941cv81o00tb4jr",
"1": "8",
"stake": "8",
"2": "tester#tester.com",
"user": "tester#tester.com",
"3": "29",
"returns": "29",
"4": "(9\/X)",
"teams": "(9\/X)",
"5": "open",
"status": "open"
}
At line 1 in the wrong code $response["id"] = $bet["id"]; you are overriding the key id in $response array with a new value, it's not O.K because there is no variable defined before with the name $bet so $bet[$id] will give you a null, that's why the id entry is null, the same applies for the the entry $response["bet"], there is no previously defined variable with the name $row and that's why all the entries is null
P.S: in mysqli_fetch_array you can pass another parameter that indicates the fetch mode, if you don't need the numeric entries just call it like that mysqli_fetch_array($result, MYSQLI_ASSOC);

Categories