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();
?>
Related
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>";
}
}
Select Queries are working properly but insert commands are not saving data in database, i think that i have not done transaction correctly or it could be roll backing transactions due to improper use of syntax
session_start();
if (isset($_COOKIE['username'])) {
$_SESSION['role'] = $_COOKIE['role'];
$_SESSION['username'] = $_COOKIE['username'];
$_SESSION['rid'] = $_COOKIE['rid'];
}
if (!isset($_SESSION['username'])) {
header('location: login.php');
}
$servername = "localhost";
$username = "johnalla_Mohsin";
$password = "Mohsin1982";
$database = "johnalla_m_billing";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
date_default_timezone_set('Asia/Karachi');
$currentdate = date("Y-m-d");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_COOKIE['username'])) {
$_SESSION['role'] = $_COOKIE['role'];
$_SESSION['username'] = $_COOKIE['username'];
$_SESSION['rid'] = $_COOKIE['rid'];
}
if (isset($_POST['invoice_no'])) {
$conn->autocommit(FALSE);
$result1 = $conn->query("select sum(cost * quantity) as total from temp_entries");
if ($result1->num_rows > 0) {
// output data of each row
while ($row1 = $result1->fetch_assoc()) {
$total = $row1["total"];
}
if ($conn->query("insert into bill (c_name, date, total) values ('$_POST[name]', '$_POST[date]', '$total')") === TRUE) {
$last_id = $conn->insert_id;
$result2 = $conn->query("select * from temp_entries");
if ($result2->num_rows > 0) {
// output data of each row
while ($row2 = $result2->fetch_assoc()) {
$entries[] = $row2;
$conn->query("insert into bill_entries (bill_id, item_name, description, cost, quantity) "
. "values ('$last_id', '$row2[item_name]', '$row2[description]', '$row2[cost]', '$row2[quantity])");
}
if ($conn->query("truncate table temp_entries") === TRUE) {
$conn->commit();
}
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
I m trying to get the existing "usercouponinhand" value from "userpaytoget" table and add it to received 'id' value as from "GET" tag. Then update it to the same "userpaytoget" table "usercouponinhand" column.
But unfortunately i see this "Unexpected =" error on the line result = $conn->query($sql);
The code follows:
<?php include('usercoupondelete.php'); ?>
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "";
$mobile = $_SESSION['mobile'];
$date = date('M-d,Y H:i:s');
$date2 = date('M-d,Y');
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM userpaytoget WHERE mobile = '$mobile' ";
result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$usercouponinhand = $row["usercouponinhand"];
$couponvalue = $_GET["id"];
$totalvalue = $couponvalue + $usercouponinhand ;
$sql2 = "UPDATE userpaytoget SET usercouponinhand = '$totalvalue', date = '$date', date2 = '$date2'
WHERE mobile = '$mobile'";
if ($conn->query($sql2) === TRUE) {
echo '';
}
else {
echo "ERROR" . $sql2 . "<br>" . $conn->error;
}
}
} else {
echo "None";
}
$conn->close();
?>
Any Help is greatly appreciated..
You are missing a $
It should be $result = $conn->query($sql);
I want to do a query to get the last id (int) in a table to create a new row with that last id + 1 but actually this just put all rows with the same id
my code:
<?php
$servername = "localhost";
$user = "root";
$pass = "dbpass";
$dbname = "site";
$mail = $_POST['mail'];
$password = $_POST['password'];
// Create connection
$conn = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sqlID = "SELECT MAX(id) FROM `login`;";
if ($result = mysqli_query($conn, $sqlID)) {
$id = mysqli_fetch_row($result);
}
settype($id, "int");
$id = $id + 1;
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
mysqli_fetch_row returns always an array, also if there is only 1 element. So the MAX(id) in in $row[0].
Fixing this, you also don't need to use settype.
If your id is autoincrement, change this:
$sql = "INSERT INTO login (`id`,`mail`,`password`)
VALUES ('".$id."','".$mail."','".$password."');";
to:
$sql = "INSERT INTO login (`mail`,`password`)
VALUES ('".$mail."','".$password."');";
Then get rid of all code from $sqlID to $id + 1; (for tidyness)
my code returns success, but it does not insert the record to the table "bekuldottkerdesek". What is causing the problem?
Even select command fails, when I start to echo some records from the table.
This is how the table looks: imgur
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
$conn = new mysqli($servername, $username, $password, $dbname);
date_default_timezone_set('Europe/Bucharest');
$current_date = date("Y-m-d H:i:s");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$check="SELECT * FROM bekuldottkerdesek WHERE kerdes = '$_POST[kerdes]'";
$res = mysqli_query($conn,$check);
if($res->num_rows){
header("Location: /bekuld.php?hiba=1");
}
else
{
$var1 = isset($_POST['at']) ? 1 : 0;
$var2 = isset($_POST['bt']) ? 1 : 0;
$var3 = isset($_POST['ct']) ? 1 : 0;
$sql = "INSERT INTO bekuldottkerdesek (datum, kerdes, a, b, c, at, bt, ct)
VALUES ('$current_date', '$_POST[kerdes]', '$_POST[a]', '$_POST[b]', '$_POST[c]', $at, $bt, $ct)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("Location: /bekuld.php?hiba=2");
}
$conn->close();
?>
change the insert statment to ,error passing data from $_POST
$sql = "INSERT INTO bekuldottkerdesek (datum, kerdes, a, b, c, at, bt, ct)
VALUES ('$current_date', '{$_POST['kerdes']}', '{$_POST['a']}', '{$_POST['b']}', '{$_POST['c']}', $at, $bt, $ct)";
and change this statment
$check="SELECT * FROM bekuldottkerdesek WHERE kerdes = '$_POST[kerdes]'";
to
$check="SELECT * FROM bekuldottkerdesek WHERE kerdes = '{$_POST['kerdes']}'";