So I am trying to get conversion rates from an API and I get the following data:
https://api.exchangeratesapi.io/history?start_at=2017-01-01&end_at=2018-09-01&symbols=EUR&base=GBP
How can I loop over the data and insert date & conversion rate into MYSQL DB.
Any help is greatly appreciated.
I am currently standing here:
$host="localhost";
$user="conversion";
$pass="password";
$db="areporting";
$connect= new mysqli($host,$user,$pass,$db) or die("ERROR:could not connect
to the database!!!");
$string = file_get_contents("https://api.exchangeratesapi.io/history?start_at=2017-01-01&end_at=2018-09-01&symbols=EUR&base=GBP");
$json = json_decode($string, true);
var_dump($json);
here a screenshot of the Data I get:
You can use foreach on json result :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$string = file_get_contents("https://api.exchangeratesapi.io/history?start_at=2017-01-01&end_at=2018-09-01&symbols=EUR&base=GBP");
$json = json_decode($string, true);
foreach($json['rates'] as $date =>$conversion){
$sql = "INSERT INTO Mytable (id, date, conversion)
VALUES ( '$date', ".$conversion['EUR'].")";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully"."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
}
$conn->close();
?>
Thanks for all the Tips, here I have my working solution:
foreach($json['rates'] as $date => $conversion){
$timestamp = strtotime($date);
$sql = "INSERT INTO m_fx_rate_temp
(`base`, `counter`, `fxRate`, `date`) VALUES ('gbp', 'eur', ".$conversion['EUR'].", Date_format(FROM_UNIXTIME($timestamp), '%Y-%m-%d'))";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully"."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
}
Related
I want to set up a website with a form in it. The form will transfer the data to the DB, but I think it is not safe to let the personal data in the DB which is external reachable.
So I thought I should transfer the data via PHP from the DB1(server1 - external reachable) to DB2(server2 - only internal reachable).
The following picture should help to know what I am searching for.
Is there any names/methods to google for?
From php you just have to create a new connection for DB2.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servername2 = "localhost";
$username2 = "database2";
$password2 = "xxxxxxxx";
$dbname2 = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn2 = new mysqli($servername2, $username2, $password2, $dbname2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
if ($conn2->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn2->error;
}
$conn->close();
$conn2->close();
?>
I"m sending to a php code a json string named- student
$scope.student = {name: "Joe", grades: "85", info: ""};
Now the php code is simple -
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//read the json file contents
$jsondata = file_get_contents("php://input");
//convert json object to php associative array
$data = json_decode($jsondata, true);
$studentname = $data['studentname'];
$stuedentgrades = $data['stuedentgrades'];
$studentinfo = $data['studentinfo'];
$sql = "INSERT INTO students (name, grades, info)
VALUES ('$studentname', '$stuedentgrades', '$studentinfo')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The thing is that sometimes the "info" can be empty and i would like to pass it empty to the server - but I'm getting -
Undefined index: info
Now i tried to add to the code the isset -
`if(isset($_POST('info'))){
$info= $data['info'];
}else{
echo "NOOOOOOOOOO";
} `
$studentname = $data['studentname'];
$stuedentgrades = $data['stuedentgrades'];
$studentinfo = $data['studentinfo'];
$sql = "INSERT INTO students (name, grades, info)
VALUES ('$studentname', '$stuedentgrades', '$studentinfo')";
but it didn't seems to do the work.
So what am I doing wrong?
How can I pass empty value into the table?
As you can see I'm novice when it comes to PHP so any help would be nice
Hope it will help you (please read comments (//...) carefully and check changes):-
$scope.student = [name: "Joe", grades: "85", info: ""]; // `.` from variable name eed to be removed in any manner
Now i assume it's:-
$scope = [name: "Joe", grades: "85", info: ""];
Now the php code is simple -
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//read the json file contents
$jsondata = file_get_contents("php://input");
//convert json object to php associative array
$data = json_decode($jsondata, true);
// here i assume that $data is exactly equals what you shown above that means $data = [name: "Joe", grades: "85", info: ""];
//Now change here:-
$studentname = (!empty($data['name']))? $data['name'] : ""; //check change here
$stuedentgrades = (!empty($data['grades']))? $data['grades'] : "";
$studentinfo = (!empty($data['info']))? $data['info'] : "Nooooo";
$sql = "INSERT INTO students (name, grades, info)
VALUES ('$studentname', '$stuedentgrades', '$studentinfo')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
$_POST('info') is not the correct way to access an array from post
try
if(isset($_POST['info'])){
$info= $_POST['info'];
}else{
echo "NOOOOOOOOOO";
}
or
if(isset($data['student']['info'])){
$info= $data['student']['info'];
}else{
echo "NOOOOOOOOOO";
}
function inseartinto()
{
$DEL_LOG_REP = $connection->prepare("DELETE FROM test WHERE itemname='111'")$DEL_LOG_REP->execute()$DEL_LOG_REP->close()return $DEL_LOG_REP
}
This is short tutorails on connection in insert query into php...
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
For more better understand..go to http://www.w3schools.com/php/default.asp
What code are you trying to writing man..
This is not a valid code for just not insert but also for connetion..
ya go onto W3School.com as mention by #Sasa.D... it provide you with knowledge from basic to expertise..
I need some help finding my error on the enclosed code. When I run either of the two queries using the if ($conn->query($sql) === TRUE) { method each works correctly. But when I try to combine them with the if ($conn->multi_query($sql) === TRUE) { method. No records are uploaded. What am I doing wrong here.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload'];
echo $payload_dump;
$payload_array = json_decode($payload_dump,true);
if(is_array($payload_array)){
foreach($payload_array as $row){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
$sql = "INSERT INTO data(device, type, zone, sample, count, date_time, epoch_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch');";
$sql . = "UPDATE data SET date_time = FROM_UNIXTIME(epoch_stamp);";
if ($conn->multi_query($sql) === TRUE) {
//if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
... and yes I realize this code is not secure but it's ok for my testing purposes.
Intrinsically the code below is the same until we get to the loop where we build up an array of queries to be executed and execute the multi_query() once at the end once we leave the loop. I have removed some of the comments and statements that echo out info at the start for brevity. I hope this looks ok and works....
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) die("Connection failed: " . $conn->connect_error);
$payload_dump = $_POST['payload'];
$payload_array = json_decode($payload_dump,true);
if( is_array( $payload_array ) ){
$queries=array();
foreach( $payload_array as $row ){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
/*note: we do not need to add the semi-colon here as it gets added later when we implode the array */
$queries[]="INSERT INTO `data` ( `device`, `type`, `zone`, `sample`, `count`, `date_time`, `epoch_stamp` ) VALUES ('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch')";
}
/*
Previously the below query was being execute on every iteration
~ because $epoch is now the last one encountered in the array,
the value that is updated in ALL records is as it would have been
previously.
*/
$queries[]="UPDATE `data` SET `date_time` = from_unixtime( $epoch );";
$sql=implode( ';', $queries );
if ( $conn->multi_query( $sql ) === TRUE ) {
echo "New records created and updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
What do I have wrong in the following code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
//$payload_dump = $_POST['payload']
$payload = '{"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}'
$payload_array = json.decode($payload,true);
//get the data_payload details
$device = $payload_array['device'];
$type = $payload_array['data_type'];
$zone = $payload_array['zone'];
$sample = $payload_array['sample'];
$count = $payload_array['count'];
$time = $payload_array['time_stamp'];
$sql = "INSERT INTO data(device, data_type, zone, sample, count, time_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I get the following error:
Parse error: syntax error, unexpected '$payload_array' (T_VARIABLE) in /Applications/XAMPP/xamppfiles/htdocs/insert_from_json.php on line 18
This PHP file receives the "payload" from a python file via JSON. The PHP file inserts that data into a table. $payload is a test variable to "simulate" the data coming in from the python code in the line above it. The payload could contain multiple rows. Maybe there is a better way to insert multiple rows than what I am attempting?
On line 18 you have the following:
$payload_array = json.decode($payload,true);
When it should be
$payload_array = json_decode($payload,true);
You used a period (.) instead of an underscore (_).