<?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();
?>
....
Related
I have developed this code below to the user upload a file and save the name of this file in the database, to be able to access it later, the upload is done normally, it goes to the designated folder, but the name is not saved in the database, does anyone know what's wrong with the code? Especially below the move_uploaded_file, because so far it works, then it goes wrong.
<?php
if (isset($_POST['enviar'])) {
$arq = $_FILES['arquivo']['name'];
$arq = str_replace(" ", "_", $arq);
$arq = str_replace("ç", "c", $arq);
if (file_exists("uploads/$arq")) {
$a = 1;
while (file_exists("uploads/[$a]$arq")) {
$a++;
}
$arq = "[".$a."]".$arq;
}
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], 'uploads/'.$arq)) {
$objDb = new db();
$link = $objDb->conecta_mysql();
$sql = "insert into arquivos (email_vol, nomearq) values ('$email', '$arq')";
if (mysqli_query($link, $sql)){
echo 'Plano de aula 1 enviado com sucesso!';
} else {
echo (mysqli_error($link));
echo 'Erro ao enviar o plano de aula!';
}
} else {
echo "Nenhum arquivo selecionado!";
}
}
?>
That is the code used to connect with the database:
class db {
//host
private $host = 'localhost';
//usuario
private $usuario = '111111';
//senha
private $senha = '11111111';
//banco de dados
private $database = 'dsfadsfasd';
public function conecta_mysql(){
//criar a conexão
$con = mysqli_connect($this->host, $this->usuario, $this->senha, $this->database);
//ajustar a charser de cominicação entre a aplicação e o bd
mysqli_set_charset($con, 'utf8');
//verificar se houve erro de conexão
if (mysqli_connect_errno()) {
echo 'Erro ao tentar se conectar com o banco de dados'.mysqli_connect_error();
}
return $con;
}
}
?>
Don't have the privilege to comment right now but shouldn't this be like this plus you don't have a semicolon at the end of your sql script
$sql = "insert into arquivos (email_vol, nomearq) values ('" . $email . "', '"
.$arq . "');";
and also this
if (file_exists("uploads/" . $arq)) {
$a = 1;
while (file_exists("uploads/". $a . ".". $arq)) {
$a++;
}
$arq = $a.".".$arq;
}
with a full stop between your file number and name
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
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'm new with PHP and SQL...
I'm trying to create new tables based on the url, but it's only working the first time I use it. After that, it's not possible.
Here is my PHP code:
if(isset($_GET['id'])){
$tabela = $_GET['tabela'];
$_GET['id'];
$criar = $tabela . $nivel . $page_id;
// Se clicar no botão 'confirmar', então ele faz o seguinte:
if(isset($_POST['submit'])){
$titulo = $_POST['titulo'];
$_FILES['imagem']['tmp_name'];
$texto = $_POST['texto'];
// Se um destes campos estiver vazio:
if($titulo=='' or $imagem=='' or $texto==''){
echo "Preencha todos os campos para o menu!";
exit(); }
// Se não houver campos vazios, ele faz: else {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "site";
// Ligação à base de dados:
$conn = new mysqli($servername, $username, $password, $dbname);
// Verifica a ligação:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
// Se conseguir ligar-se à base de dados e criar uma nova tabela, ele insere os dados na nova tabela:
if ($conn->query($sql) === TRUE) {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Se inserir os dados na nova tabela, ele dá uma mensagem de sucesso:
if(mysql_query($insert_query)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "Erro: " . $insert_query . "<br>" . $conn->error;
}
}
// Caso ele não consiga criar uma nova tabela (porque já existe), ele insere os dados na tabela já existente:
else {
include("includes/connect.php");
mysql_query("SET NAMES 'utf8'");
// Cria a nova tabela:
$sql = "CREATE TABLE IF NOT EXISTS $criar (
id INT(9) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
titulo VARCHAR(255),
imagem LONGBLOB,
texto TEXT,
grupo INT(9),
FOREIGN KEY (grupo) REFERENCES $tabela(id)
)";
if(mysql_query($sql)){
echo "sim!";
}
else {
echo "não!";
}
move_uploaded_file($image_tmp,"../imagens/$imagem");
$insert_query = "INSERT INTO $criar (titulo, imagem, texto, grupo) VALUES ('$titulo','$imagem','$texto','$page_id')";
// Caso consiga inserir os dados na tabela já existente, dá uma mensagem de sucesso:
if(mysql_query($insert_query&&$sql)){
echo "<script>alert('Menu inserido com sucesso!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "isto não está a correr bem!";
}
// Fecha a ligação à base de dados:
$conn->close();
} } }$nivel = $_GET['grupo']; $page_id =$imagem = $_FILES['imagem']['name']; $image_tmp =
What do you mean 1st time, 2nd time? Do you try to create another table with the same name you just have created? You'll get a table already exists error.
CREATE TABLE IF NOT EXISTS $criar
This explicitly tells MySql not to create the table if it exists, so if you pass the same query parameters to your php then it'll not be able to create the same table again.
Probably you could change it to:
$page_id = $_GET['id'];
$criar = $tabela . $nivel . $page_id;
And then pass a different id and/or different tabela every time.
this code looks behind the issue to me :
$tabela = $_GET['tabela'];
$_GET['id']; //this line looks odd
$criar = $tabela . $nivel . $page_id;
and maybe it's not creating new tables because you give the same $criar every time.
After hours of trying to solve this issue, i finally got good news! :) i was working in my local server (via xampp) and decided to put it online to check if something changes... and dont know why, but it works perfectly online and dont work with xampp! What a mess!! but its working!! thanks all for your help!! ;)
I want to browse data from my postgre database with a "foreach". So I made my request like that :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And I get my values with "pg_fetch_all".
After that, I'm looking for compare the data in my database (get with the request) and the data in my web page. So I created this loop :
foreach($array as $ligne_web)
{
foreach($data['id_traitement'] as $ligne_base)
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) and ($flag2))
{
insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}
When I try to run it, firebug tells me : Invalid argument supplied for foreach(). So I don't know how to browse the rows in the database. Certainly my problem is in my foreach, but I don't find what's wrong.
Help please !
It seems your second foreach needs to be '$data' instead of $data['id_traitement']
So your code need to changed to ,
foreach($arr as $ligne_web)
{
foreach($data as $ligne_base) // <-- Here is the correction
{
if(($ligne_web[0] == $ligne_base) and ($flag))
{
------ REST of your Codes ------
Ok, I found an answer. Instead of an array $data from my database, and directly after the request, I created a new array.
Here is my code :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT id_traitement FROM public.traitement WHERE id_essai='.$id_essai.';";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$tableau_database_final = array();
while ($data = pg_fetch_all($res)) //Here is my array
{
$tableau_database = array('id_traitement'=>$data['id_traitement']);
array_push($tableau_database_final,$tableau_database);
}
$flag2 = true;
foreach($array as $ligne_web)
{
foreach($tableau_database_final as $ligne_base)
{
echo ($ligne_web[0]);
echo ($ligne_base);
if(($ligne_web[0] == $ligne_base)) //Si il existe une ligne ayant déjà le même id traitement
{
//update de la ligne
update_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
$flag2 = false;
break 1;
}
}
if(($flag) && ($flag2))
{
//insert_traitement($id_traitement,$traitement,$code_traitement,$id_essai);
}
}