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 (_).
Related
I got the tutorial from this link
https://icreateproject.info/2014/12/14/arduino-save-data-to-database/
The tutorial is about how to save data from Arduino to xampp database over the local network.
I follow everything until step 3. This is the PHP code:
<?php
// Prepare variables for database connection
$dbusername = "arduino"; // enter database username, I used "arduino" in step 2.2
$dbpassword = "arduinotest"; // enter database password, I used "arduinotest" in step 2.2
$server = "localhost"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"
// Connect to your database
$dbconnect = mysql_pconnect($server, $dbusername, $dbpassword);
$dbselect = mysql_select_db("test",$dbconnect);
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
mysql_query($sql);
?>
I tried to run this command in the link as mentioned in the tutorial
http://localhost/write_data.php?value=100
This is the error I get
Fatal error: Uncaught Error: Call to undefined function mysql_pconnect() in C:\xampp\htdocs\write_data.php:11 Stack trace: #0 {main} thrown in C:\xampp\htdocs\write_data.php on line 11
The mysql library that you are using is deprecated in php5.5
http://php.net/manual/en/function.mysql-connect.php
Here's an updated version with mysqli_connect
$dbusername = "arduino";
$dbpassword = "arduinotest";
$server = "localhost";
$database = 'test';
$mysqli = mysqli_connect($server, $dbusername, $dbpassword,$database);
// please validate the $_GET['value']
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
mysqli_query($mysqli, $sql);
new mysqli http://php.net/manual/en/function.mysqli-connect.php
Somehow i managed to connect and changed the value by typing and auto insert using this code
<?php
header("Refresh:5");
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else {
echo "hello";
}
$value = $_GET['value'];
$sql = "INSERT INTO test.sensor (value) VALUES ($value)";
$sql = "INSERT INTO test.sensor (value)
VALUES ('255')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
And without this code, which is on line 28, i will get error so i have to put this code as well
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Thank you everyone for helping really appreciate it.
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>";
}
}
I am trying to add 50 columns of data to mysql database with column names as l1, l2, l3 and so on..
if((strpos(strtolower($out), "error") === FALSE) && (strpos(strtolower($out), "not allocated") === FALSE)) {
$rows = explode("\n", $out);
$x=1;
foreach($rows as $row) {
$row = trim($row);
$rec[$x] = $row;
$x = $x + 1;
}
}
$senqu = "INSERT INTO simple (name,l1, l2, l3,l4,l5,l6,l7,l8,l9,l10,l11, l12, l13,l14,l15,l16,l17,l18,l19,l20,l21, l22, l23,l24,l25,l26,l27,l28,l29,l30,l31, l32, l33,l34,l35,l36,l37,3l8,3l9,l40,l41, l42, l43,l44,l45,l46,l47,l48,l49,l50) VALUES (".$abc;
for ($i =1;$i<=49;$i++) {
$senqu = $senqu.",'".$rec[$i]."'";
}
$senqu = $senqu.") WHERE name = ".$domain;
$db->query($senqu);
the code is giving me following errors:
PHP Notice: Undefined variable: db in /home/dataegud/public_html/zzuse.com/scrips/whois.php on line 346
[06-Apr-2017 15:57:37 Etc/GMT] PHP Fatal error: Call to a member function query() on a non-object in /home/dataegud/public_html/zzuse.com/scrips/whois.php on line 346
Can you help me. I am a novice in php and want to gain some knowledge.
the variable db is not defined due to which you are getting the error.The following link is causing the error
$db->query
==================================================
Following is the query for insert
<?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();
?>
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";
}
I have problem with MySQL database, I can't insert the information into the table. My php code seems to work, but when I run it nothing happens.
<?php
$servername = "localhost";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks";
$conn = new mysqli($servername, $fname, $lname,$klas,$file,$dbname);
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($servername, $fname, $lname,$klas,$file,)";
?>
You have three main problems in your code:
You're still not connected to the database
Only constructing and not executing
Having not matched parameters in the insert values
Solution :
1. Make a connection first
$conn = new mysqli($servername, $username, $password, $dbname);
The Parameter $servername, $username, $password, $dbname is obviously your hostname, Database Username, Password and the Database name
You should not have your table name or column names in the connection parameters
2. Construct the parameters which matches the coloumn name and variables correctly
$sql = "INSERT INTO student (fname, lname,klas,file)
VALUES ($fname, $lname,$klas,$file)";
3. Execute Your Query :
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Note :
Also it's good practice to close your connection once you are done
$conn->close();
So, you should be having something like this
<?php
$servername = "localhost";
$username = "YourDBUsername";
$password = "YourDBPassword";
$fname = "fname";
$lname = "lname";
$klas = "klas";
$nomer = "nomer";
$file = "dom";
$dbname = "homeworks"; //Hope you will have your db name here
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "
INSERT INTO student (fname, lname,klas,file) VALUES
('$fname'
,'$lname'
,'$klas'
,'$file');
";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Advice :
Always use prepared statements else clean your inputs before you insert.
Your connection should look something like this. link
<?php
//change the data into your connection data
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You made your query but didn't execute it.
if (mysqli_query($conn, $sql)) {
echo 'records created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($conn);
}