I'm importing data from variables in php (from read csv) and send it to a MySQL table. But they appear this:
The data has like spaces in it, but if we want to edit the content... go to image 2
IMAGE 1: https://i.stack.imgur.com/6PvFE.png
It says that have only one character!!
IMAGE 2: https://i.stack.imgur.com/crjE3.png
I test that if you print the variables before import it all data are good, without any spaces.
This is my query in php:
mysql_query("INSERT INTO $name(keyword, adGroup, currency, busquedasMes, competencia, puja) VALUES('$adgroup','$adgroup','$currency','$busquedasMes','$competencia','$puja')");
EDIT:
This is my import.php code, the CSV is delimited by tabs, so I need to change it to ";"
<?php
$link = mysql_connect('localhost', 'user', 'pass')
or die('No se pudo conectar: ' . mysql_error());
$nombre = $_FILES['archivo']["name"];
$trozos = explode("." , $nombre);
$cuantos = count($trozos);
$nombreLimpio = $trozos[$cuantos - 2];
mysql_select_db('prueba1') or die('No se pudo seleccionar la base de datos');
mysql_query("CREATE TABLE $nombreLimpio (keyword VARCHAR(30), adGroup VARCHAR(30), currency VARCHAR(30), busquedasMes VARCHAR(30), competencia VARCHAR(30), puja VARCHAR(30))");
$tipo = $_FILES['archivo']['type'];
$tamanio = $_FILES['archivo']['size'];
$archivotmp = $_FILES['archivo']['tmp_name'];
$lineas = file($archivotmp);
$i=0;
foreach ($lineas as $linea_num => $linea)
{
if($i != 0)
{
$lala = str_replace('/\t/', ';', $linea);
$datos = explode(";",$lala);
$adgroup = trim($datos[0]);
$keyword = trim($datos[1]);
$currency = trim($datos[2]);
$busquedasMes = trim($datos[3]);
$competencia = str_replace('"', "", trim($datos[4]));
echo $keyword;
$puja = str_replace(' ', "",$competencia);
mysql_query("INSERT INTO $nombreLimpio(keyword, adGroup, currency, busquedasMes, competencia, puja) VALUES('$keyword','$adgroup','$currency','$busquedasMes','$competencia','$puja')");
}
$i++;
}
mysql_close($link);
?>
Example of my CSV file:
Seed Keywords android EUR 2740000 "0,12" "0,61" Y N
Related
I have the next problem doing a json to read in Andorid
(the credentials are hidden but connection going good in others files)
class reportes
{
var $parametro;
var $conexion;
function __construct(){
$host = "IP"; $DBName = "DbName";
$usuario="user"; $contrasena="pass";
$driver = "DRIVER={iSeries Access ODBC Driver};
SYSTEM=$host;Uid=$usuario;
Pwd=$contrasena;Client_CSet=UTF-8;";
$this->conexion = odbc_connect($driver, $usuario, $contrasena);
}
function consulta($parametro){
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
echo $query."<br><br>";
if ($this->conexion == 0) {echo "Ha fallado la conexion a la BBDD </br>";}
else{
$datos = array();
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$datos[]= $row;
}
echo json_encode($datos);
}
}//Fin funcion consulta()
}//Fin de la clase
$consultar = new reportes();
$nota_venta = $_REQUEST['parametro'];
$consultar->consulta($nota_venta);
the response JSON that i get is:
SELECT OHSNME,OHTOT$,OHREPÑ FROM DELLORTO.SANFPRD.FOMHDR WHERE OHORDÑ= 366
[{"OHSNME":"E.C. GM. ","OHTOT$":"1861.00",null:" A07"}]
you can see that OHORDÑ is probably the problem with the 'Ñ'
but this table are part a productive database and i can't update
Solution #1, alias the column name to a name without non-ascii characters:
$query=
"SELECT OHSNME,OHTOT$,OHREPÑ AS OHREPN
FROM MYDB.SANFPRD.FOMHDR
WHERE OHORDÑ= $parametro ";
Solution #2, manually serialize using utf8_encode():
$result=odbc_exec($this->conexion,$query);
while($row = odbc_fetch_object($result)){
$_row_fix = array();
foreach ($row as $field => $val) {
$_row_fix[utf8_encode($field)] = utf8_encode($val);
}
$datos[]= $_row_fix;
}
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
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.
<?php
$url = "http://rates.fxcm.com/RatesXML";
$xml = simplexml_load_file($url);
print_r($xml);
?>
This script really works and the output is here:
http://sitoxte.com/test%20mercato/array.php
But what I want to do is put this data to MySQL tabs, I need some help because I want to store the data each minute.
So i Try:
json-to-mysql
but I think that array in xml variable is not adeguate.
I want create a for cicle
and create 69 table like this:
table 1 eur/usd
id - Bid - Ask - High - Low - Direction - Last - timestamp
1
2
3
4...
and so on
refresh mode is simple and I do in this way whit javascript:
<script>
setInterval(function () {}, 3000);
var myVar=setInterval(function(){myTimer()},10000);
function myTimer()
{
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
location.reload();
}
</script>
connetion is simple too and is like this:
//Host:
$localhost="******";
//database
$mioblog=*******;
//Nome utente:
$username=********;
//Password:
$password=*******;
// connessione a MySQL con l'estensione MySQLi
$mysqli = new mysqli("$localhost", "$username", "$password", $mioblog);
// verifica dell'avvenuta connessione
if (mysqli_connect_errno()) {
// notifica in caso di errore
echo "Errore in connessione al DBMS: ".mysqli_connect_error();
// interruzione delle esecuzioni i caso di errore
exit();
}
else
{
// notifica in caso di connessione attiva
echo "Connessione avvenuta con successo";
}
This depends on what you're using for your database, but assuming PDO, something like the below. If you need more details then look up a MySQL tutorial, but hopefully this gets you started and shows you how to traverse the XML.
foreach($xml->Rate as $rate) {
$query = "INSERT INTO tblrate (time, symbol, bid) VALUES (NOW(), :symbol, :bid)";
$query = $pdo->prepare($query);
$query->execute(array(
':symbol' => $rate->#attributes['Symbol'],
':bid' => $rate->Bid;
));
}
edit: If you only need one currency, something like this should work
foreach($xml->Rate as $rate) {
if($rate->#attributes['Symbol'] == 'EURUSD') {
$query = "INSERT INTO tblrate (time, bid) VALUES (NOW(), :bid)";
$query = $pdo->prepare($query);
$query->execute(array(
':bid' => $rate->Bid;
));
}
}
My friend Biagio help me to write code:
foreach($xml->children() as $xml_child){
$Symbol = $xml_child['Symbol'];
$Bid = $xml_child->Bid;
$Ask = $xml_child->Ask;
$High = $xml_child->High;
$Low = $xml_child->Low;
$Direction = $xml_child->Direction;
$Last = $xml_child->Last;
echo('$Symbol = '.$Symbol.'<br>');
echo('$Bid = '.$Bid.'<br>');
}
final code of php scrip that write in mysql tables every second forex data:
...
<body id="top">
<!-- <button onclick="myFunction()">Reload page</button> -->
<a id=demo> <a>
...
<?php
echo date("F j, Y, g:i a", time()).'<br>';
$html="";
$url = "http://rates.fxcm.com/RatesXML";
$xml = simplexml_load_file($url);
//Host:
//echo('var_dump( $xml)<br>');
//var_dump( $xml);
//SimpleXMLElement
//Host:
$localhost="----";
//database
$mioblog=----;
//Nome utente:
$username=-----;
//Password:
$password=-----;
// connessione a MySQL con l'estensione MySQLi
$mysqli = new mysqli("$localhost", "$username", "$password", $mioblog);
// verifica dell'avvenuta connessione
if (mysqli_connect_errno()) {
// notifica in caso di errore
echo "Errore in connessione al DBMS: ".mysqli_connect_error();
// interruzione delle esecuzioni i caso di errore
exit();
}
else {
// notifica in caso di connessione attiva
// echo "Connessione avvenuta con successo";
}
// sql to create table
// sql to create table
foreach($xml->children() as $xml_child){
$Symbol = $xml_child['Symbol'];
$Bid = $xml_child->Bid;
$Ask = $xml_child->Ask;
$High = $xml_child->High;
$Low = $xml_child->Low;
$Direction = $xml_child->Direction;
$Last = $xml_child->Last;
// sql to create table
/*
$sql = "CREATE TABLE $Symbol (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Bid VARCHAR(30) NOT NULL,
Ask VARCHAR(30) NOT NULL,
High VARCHAR(30) NOT NULL,
Low VARCHAR(30) NOT NULL,
Direction VARCHAR(30),
Last VARCHAR(30) NOT NULL,
reg_date TIMESTAMP
)";*/
$sql = "INSERT INTO $Symbol (Bid,Ask,High,Low,Direction,Last)
VALUES ('$Bid','$Ask',$High,$Low,$Direction,'$Last')";
if ($mysqli->query($sql) === TRUE) {
// echo "Inserito in table ".$Symbol." / bid=".$Bid." / ask=".$Ask."/ High=".$High."/ Low=".$Low."/ Direction=".$Direction."/ Last=".$Last."<br>";
} else {
echo "Error creating table: " . $mysqli->error;
}
// echo('$Symbol = '.$Symbol.'<br>');
//echo('$Bid = '.$Bid.'<br>');
//echo('$Ask = '.$Ask.'<br>');
//echo('$High = '.$High.'<br>');
//echo('$Low = '.$Low.'<br>');
// echo('$Direction = '.$Direction.'<br>');
// echo('$Last = '.$Last.'<br>');
}
$mysqli-->close();
?>
....
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.