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";
}
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 have a little problem
I want to create a script, that creates a new line in the table, if there is a new user and in the line, change the "points" columme to zero(0)
This is my current code:
<?php
header('Content-Type: text/html; charset=Windows-1250');
$firstName = $_POST['firstname'];
$servername = "db.mysql-01.gsp-europe.net";
$username = "xxxxxxxxxx";
$password = "xxxxxxxxxxx";
$dbname = "xxxxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "UPDATE `member_profile` SET points = points + 1 WHERE user_id = '$firstName'";
if ($conn->query($sql) === TRUE) {
echo "Thingz created successfully";
} else {
echo "Error doing sum thingz: " . $conn->error;
}
$conn->close();
?>
What i need in the cube: When there new user_id ($firstName) appear, create new line with this user name, and change the "points" columme from "null" into Zero(0)
Thanks for yout time, I appreciate it
If I understand well you want to check if the user exists or not. If user is new create new line with the user with 0 points and if exist increse points with 1.
<?php
header('Content-Type: text/html; charset=Windows-1250');
if(isset($_POST['firstname'])){
$firstName = $_POST['firstname'];
$servername = "db.mysql-01.gsp-europe.net";
$username = "xxxxxxxxxx";
$password = "xxxxxxxxxxx";
$dbname = "xxxxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// check if the user exist
$check = "SELECT * FROM `member_profile` WHERE user_id = '$firstName'";
$result = mysqli_query($conn,$check) or die(mysqli_error($conn));
$rows = mysqli_num_rows($result);
//if exist increse points with 1
if($rows>=1){
$sql = "UPDATE `member_profile` SET points = points + 1 WHERE user_id = '$firstName'";
if ($conn->query($sql) === TRUE) {
echo "Thingz created successfully";
} else {
echo "Error doing sum thingz: " . $conn->error;
}
}
//if don't exist create user with points 0
if($rows==0)
{
$query = "INSERT into `member_profile` (user_id, points) VALUES ( '$firstName' ,'0')";
$result = mysqli_query($conn,$query)or die(mysqli_error($conn));
$conn->close();
}
}
?>
Remember, I gave you an idea, the code is prone to sql inject
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>";
}
}
every thing is getting inputted correctly but date is being submitted into database like 0000-00-00. please help!! i tried to echo my date before posting it into dob and it coming out to be correct as inserted into the form. but when i check my database the dob columnsgets updates with a 0000-00-00.
here is the code:
<?php
if (isset($_POST['submit'])) {
echo "<pre>";
var_dump($_POST);
echo "</pre>";}
$username = $_POST['username'];
$password = $_POST['password'];
//$salary = $_POST['salary'];
$birthdate = $_POST['year'] . '-' . $_POST['month']. '-' .$_POST['day'];
echo $birthdate."<br>";
if(!empty($username)){
if(!empty($password)){
if(!empty($birthdate)){
$servername = "localhost";
$usernamei = "root";
$passwordi = "password";
$databasei = "regis";
// Create connection
$conn = new mysqli($servername, $usernamei, $passwordi, $databasei);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else {
echo $birthdate;
$sql = "INSERT INTO iocl (user_name, password,dob)
values ('$username','$password','$birthdate')";
if($conn->query($sql)){
echo "new record is inserted sucess";
}
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 (_).