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
Related
<?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.
I wrote a php web service to get all data when coins were greater than 0. Here is the code:
organisationListClient-Copy.php
<?php
require_once("lib/nusoap.php");
// Create the client instance
$client = new nusoap_client("http://localhost/TTrockstars/ws/organisationListWS-copy.php");
//check if there were any instantiation errors, and if so stop execution with an error message:
$error = $client->getError();
echo ($error);
if ($error) {
die("client construction error: {$error}\n");
}
// Call the SOAP method
$result = $client->call("getOrganisationList");
$error = $client->getError();
if ($error) {
print_r($client->response);
print_r($client->getDebug());
die();
}
// Display the result
// echo "<pre>";
print_r($result);
//$fichero = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/images/'.$imgname, FILE_USE_INCLUDE_PATH);
//echo ($_SERVER['DOCUMENT_ROOT'].'/data/');
// echo "</pre>";
?>
organisationListWS-Copy.php
<?php
//****including config file****
include 'config.php';
function getOrganisationList() {
$db = dataBaseConn();
$con = mysqli_connect($db['DB_SERVER'],$db['DB_USER'],$db['DB_PASSWORD'],$db['DB_DATABASE']);
if($con){
mysqli_set_charset($con,"utf8");
/*$orgListRS = mysqli_query($con,"SELECT name FROM prop ");*/
$orgListRS = mysqli_query($con,"SELECT id, name, image, extra_image FROM prop where coins > 0");
$orgList = [];
while($orgListRow = mysqli_fetch_array($orgListRS, MYSQLI_BOTH)){
//id
$usrId = $orgListRow['id'];
$usrId = str_replace(",", ",", $usrId);
$usrId = str_replace(" ", " ", $usrId);
$orgList[] = $usrId;
//name
$usrName = $orgListRow['name'];
$usrName = str_replace("’", "'", $usrName);
$usrName = str_replace(" ", " ", $usrName);
$orgList[] = $usrName;
//image
$usrImage = $orgListRow['image'];
$usrImage = str_replace("", "", $usrImage);
$usrImage = str_replace(" ", " ", $usrImage);
$orgList[] = $usrImage;
//extra image
$usrExtimage = $orgListRow['extra_image'];
$usrExtimage = str_replace(",", ",", $usrExtimage);
$usrExtimage = str_replace(" ", " ", $usrExtimage);
$orgList[] = $usrExtimage;
}
mysqli_free_result($orgListRS);
$replyJson["status"]="SUCCESS";
$replyJson["orgList"]= $orgList;
mysqli_close($con);
return json_encode($replyJson);
}else{
$replyJson["status"]="FAILED";
return json_encode($replyJson);
}
}
require_once("lib/nusoap.php");
$urlPrefix = nameSpaceURL();
$URL = $urlPrefix . "/ws/organisationListWS-copy.php";
$namespace = $URL . '?wsdl';
$server = new soap_server();
$server->configureWSDL("WebServices for getting list of organisations");
$server->register("getOrganisationList",
array(),
// return value(s):
array('return'=>'xsd:string'),
// namespace:
$namespace,
// soapaction: (use default)
false,
// style: rpc or document
'rpc',
// use: encoded or literal
'encoded',
// description: documentation for the method
'Return list of organistaions');
$_HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : "";
$server->service($_HTTP_RAW_POST_DATA);
?>
When I run it in browser, I get all ids, names, images and extra images whose coins are greater than 0. Here is a screen shot:
Here is my table structure:
now I need to change the sql query like this:
if (updated_date=="new_date") {
//Send all data (return ids, names, images, extra images whose coins are greater than 0)
}
else {
//Get ids, names, images and extra images which are added after updated date
}
How can I modify current sql query to achieve that?
Thats fairly simple, you just need to create the new criteria for your query if the condition exists, and add it to the original query. If the condiftion does not exist $extraCriteria will be empty and no chnage will be made to the original query.
$extraCriteria = '';
if ($updated_date !== "new_date") {
//Get ids, names, images and extra images which are added after updated date
$extraCriteria = " AND updated_date > '$updated_date'";
}
$orgListRS = mysqli_query($con,"SELECT id, name, image, extra_image
FROM prop
where coins > 0
$extraCriteria");
I am of course guessing the actual names of your columns and variables but I hope this gives you a basic idea.
I have a problem when I create a sql query which depends on many variables that the user select in different checkboxes.
I make a httprequest GET and them, when I proposed to create the query, I check the variable and I create the query, gradually. I show you the PHP code:
$link = mysql_connect($hostname, $username, $password) or die('No se pudo conectar: ' . mysql_error());
//echo 'Conectado satisfactoriamente';
mysql_select_db('Agenda Juvenil') or die('No se pudo seleccionar la base de datos');
mysql_query('SET CHARACTER SET utf8');
$query="SELECT id, title, barrio_smultiple, coordenadas_p_0_coordinate, coordenadas_p_1_coordinate, gratuita_b FROM eventosDiarios WHERE";
// check for post data
if (isset($_GET['franjas0'])){
$franja0 = $_GET['franjas0'];
$query.="franja_smultiple IN ('$franja0'";
}
if (isset($_GET['franjas1'])){
$franja1 = $_GET['franjas1'];
$query.=",'$franja1'";
}
if (isset($_GET['franjas2'])){
$franja2 = $_GET['franjas2'];
$query.=",'$franja2'";
}
$query.=")";
// get a product from products table
$result = mysql_query($query) or die('Consulta fallida: ' . mysql_error());
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["eventos"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$evento = array();
$evento["id"] = $row["id"];
$evento["title"] = $row["title"];
$evento["barrio_smultiple"] = $row["barrio_smultiple"];
$evento["coordenadas_p_0_coordinate"] = $row["coordenadas_p_0_coordinate"];
$evento["coordenadas_p_1_coordinate"] = $row["coordenadas_p_1_coordinate"];
$evento["gratuita_b"] = $row["gratuita_b"];
// push single product into final response array
array_push($response["eventos"], $evento);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No se han encontrado eventos";
// echo no users JSON
echo json_encode($response);
}
The query must return something, but I have nothing. The variables are sent throught
List<NameValuePair> params = new ArrayList<NameValuePair>();
I am using Android.
Can someone help me please??
Thanks in advance.
Regards.
Your code needs to have a space after the WHERE. It needs to say
...b FROM eventosDiarios WHERE ";
rather than
....b FROM eventosDiarios WHERE";
or you'll get an illformed query.
I've found an existing script on the internet that grabs data from WHOIS servers and extracts the relevent data (Eg. Expiry date, Status). As it was long abandoned I have been modifying it and created my own script.php?id=domain.com which lets me enter any domain and whois data comes up,
What I'm having trouble with is I have my whois.php file which I want to grab a list of domains out of my MySQL database and attempt to extract the Expiry/Status data of each domain using (file_get_contents to my script.php and foreach) then update the database with the relevant information.
I'm fairly certain I have coded everything apart from the "Foreach" & "File_get_contents" part right therefore my script encounters errors.
"Warning: Invalid argument supplied for foreach() in /home/user/public_html/mydomain.com/domains/whois.php on line 39"
is the error I receive.
Snippet of my whois.php:
include("database.php");
// Select one domain from the database that hasn't been checked yet
$sql = "SELECT domainName from domains WHERE 1 ORDER BY lastChecked ASC";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$domain = $row[0];
if(mysql_num_rows($result) == 0){
die("No domains found in the database.");
}
// Grab the WHOIS information for the domain selected
// ---------------------------------------------------------------
$domainExt = substr($domain, -3); // grab the domain extension
//var_dump($whois);
$arr = array($content);
foreach($arr as $id) {
echo $id, '<br>';
$data = file_get_contents('http://codestrike.net/domains/script.php?id='.$domain.'');
echo $data, '<br>';
}
foreach($data as $whoisline){
if(strstr($whoisline,"Expiration")){
$whoisline = str_replace("Expire Date:","",$whoisline);
$whoisline = trim($whoisline);
$expiration = substr($whoisline,0,11);
}
if(strstr($whoisline,"Status")){
$statusline = $whoisline;
}
}
$status = str_replace("Status:","",$statusline);
$status = trim($status);
Script.php?id=domain.com works fine, its just a matter of having the whois.php finding the expiry date/status for each domain out of my MySQL Database.
Cheers.
Change:
$data = file_get_contents('http://mydomain.com/domains/script.php?id='.$domain.'');
to:
$data = file('http://mydomain.com/domains/script.php?id='.$domain);
file_get_contents returns the entire file as a single string. file splits it up into an array, where each element is a line of the file.
You also need to process $data in the first foreach loop. Otherwise, you're just overwriting $data each time through the loop, and the code that uses it just gets the last one.
include("database.php");
// Select one domain from the database that hasn't been checked yet
$sql = "SELECT domainName from domains WHERE 1 ORDER BY lastChecked ASC";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$domain = $row[0];
if(mysql_num_rows($result) == 0){
die("No domains found in the database.");
}
// Grab the WHOIS information for the domain selected
// ---------------------------------------------------------------
$domainExt = substr($domain, -3); // grab the domain extension
//var_dump($whois);
$arr = array($content);
foreach($arr as $id) {
echo $id, '<br>';
$data = file('http://mydomain.com/domains/script.php?id='.$domain);
var_dump($data); echo '<br>';
foreach($data as $whoisline){
if(strstr($whoisline,"Expiration")){
$whoisline = str_replace("Expire Date:","",$whoisline);
$whoisline = trim($whoisline);
$expiration = substr($whoisline,0,11);
}
if(strstr($whoisline,"Status")){
$statusline = $whoisline;
}
}
$status = str_replace("Status:","",$statusline);
$status = trim($status);
}
I am creating a login based application and this is what I have so far. I am trying to read each field into a separate textarea. I have tried to bind the data etc. I do get a output in the textarea, but it prints all the fields in one textarea. Please help.
<?php
selectDB();
function selectDB() {
$usertoken = $_POST['usertoken'];
//Database service vars
$databasehost = "localhost";
$databasename = "morerandom";
$databasetable = "random";
$databaseusername = "root";
$databasepassword = "root";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT username, useremail, firstname, lastname FROM $databasetable WHERE usertoken='$usertoken'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count)
{
$rows = array();
while ($row = mysql_fetch_object($result)) {
$rows[] = $row;
}
echo $rows[0]->username . "\n";
echo "\n";
echo $rows[0]->useremail . "\n";
echo $rows[0]->firstname . "\n";
$first = $rows[0]->lastname;
echo $first;
// echo "$lastname;"
}
else
{
echo 'Token not valid';
}
mysql_free_result($result);
mysql_close($con);
}
?>
What you are getting is just one string. There are better way to retrieve this kind of data from the server side(XML or AMF).
If you want to go ahead with your method then split the string using '\n' as a delimiter but check first that the server response is not 'Token not valid'.
So something like this should work:
First remove the echo "\n"; line under the echo $rows[0]->username . "\n";
var responseArray:Array = theStringResult.split('\n');
So now the responseArray stores the username at position 0, useremail at position 1, firstname at position 2 and lastname at position 3.
But again, you are sending data from the server as raw text and this is not the best way to do it. Check this link to see how this can be done using AMFPHP.