Cant insert specific row into the database PHP MySQL JSON - php

I pulled the json into the php object and started putting data from that object into the database. I have 20 users in json and everyone succeded to go into the database except one which surname is O'Carolan. I think that error is in that single quote, smth about that. I read everything about sql injection and tried everything i found here on stackoverflow with the similar errors and still doesnt work. I tried with the PDO also and prepared statements and still doesnt work. Here I always get an error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 'male')' at line 2. Also, when printing out the users from json it prints them properly and everything is ok there, just that 3rd user O'carolan wont go into to database.
My json is at http://dev.30hills.com/data.json and my code is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "30hills";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json_string = 'http://dev.30hills.com/data.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, false);
$elementCount = count($obj);
for ($x = 0; $x < $elementCount; $x++) {
$id = $obj[$x]->id;
$firstname = $obj[$x]->firstName;
$surname = $obj[$x]->surname;
//if (preg_match('/'.$special_chars.'/', $surname)){
// $surname = str_replace("'","",$surname);
//}
$age = $obj[$x]->age;
$gender = $obj[$x]->gender;
echo $id;
echo " ";
echo $firstname;
echo " ";
echo $surname;
echo "<br>";
mysqli_query($conn, "INSERT INTO user (`id`, `firstName`, `surname`, `age`, `gender`)
VALUES($id, '$firstname', '" . $surname . "', $age, '$gender')")
or die(mysqli_error($conn));
?>

The answer is that age = null in json wont insert into database, must make that nullable into the table

Related

INSERT TABLE using php variable

What is the correct syntax for the SQL INSERT INTO when using a php variable for table name. I have tried everything and it won't insert when I use php variable.
This is what I have so far. is this right?
$sql = "INSERT INTO ".$table." (`Name`) VALUES ('A')";
mysqli_query($conn, $sql);
if I switch $table to the actual table name, it works
$sql = "INSERT INTO 'myTable' ('Name') Values ('A')";
It works for me fine
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stack_over_flow";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
When Table Name is Variable
$DB_TBLName = "abc";
$sql_ac_valuee = "INSERT INTO $DB_TBLName (a, b ,c) VALUES "."('10','20','30')";
if ($con->query($sql_ac_valuee) === TRUE) {
}
else{
echo "Error: " . $sql_ac_valuee . "<br>" . $con->error;
}
When Use direct Table Name
$sql_ac_valuee = "INSERT INTO abc (a, b ,c) VALUES "."('10','20','30')";
if ($con->query($sql_ac_valuee) === TRUE) {
}
else{
echo "Error: " . $sql_ac_valuee . "<br>" . $con->error;
}
$query = "INSERT INTO $tname (place,dis,p_1,p_2,p_3,p_4,p_5,p_6) VALUES('$name','$discription','$bfile','$file1','$file2','$file3','$file4','$file5')";
$result =mysqli_query($link,$query);
if(!$result){echo mysqli_error($link);?>
This was my code and the output is:
Skardu.You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(place,dis,p_1,p_2,p_3,p_4,p_5,p_6) VALUES('Sundus','Few people can afford the T' at line 1
its work fine when i use skardu instead of varible

Insert into MySQL using JSON not working

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 (_).

HTTP Post to MySQL inserting Blank Rows

I'm trying to setup a post string to enter data directly into the database from a remote system.
Post string example: http://www.domainname.com/insert.php?Phone=07000888888
This returns my expected success message however when I check the database the phone field is blank.
My PHP insert script looks like:
<?php
$servername = "localhost";
$username = "XXXX";
$password = "XXXX";
$dbname = "Client1";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$_POST[Phone]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Can anyone figure out why it's inserting a blank row with this?
There are a few problems with the code that as a server admin make me slightly uncomfortable. Hopefully we can fix that and your problem at the same time.
This is what I picked up on.
(I have removed empty lines for brevity)
<?php
// ...
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$_POST[Phone]')";
// ...
The first thing is you are correctly escaping the string and then not using the escaped string
<?php
// ...
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$phone')";
// ...
However you never inspect the value to see if you have anything.
<?php
// ...
if(isset($_POST['phone'])){
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$phone')";
// ...
}else{
echo '<p><b>Error:</b> "Phone" not given.</p>';
exit(0); // stop and do no more
}
// ...
Finally (just in case): If you are sending the data this way http://example.com/example.php?phone=123456789 that is $_GET.
<?php
// ...
if(isset($_GET['phone'])){
$phone = mysql_real_escape_string($_GET['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('$phone')";
// ...
}
// ...
One way or another you should now have safe, clean and functional code that does not add empty rows and cannot so readily be abused.
You code should be like this
<?php
$servername = "localhost";
$username = "XXXX";
$password = "XXXX";
$dbname = "Client1";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$phone = mysqli_real_escape_string($conn, $_GET['phone']);
$sql = "INSERT INTO LiveFeed (phone)
VALUES ('".$phone."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Without seeing your form, which would help I am assuming you are using GET not POST.
So you need to get your values with GET not POST if the following is the result of the form submission:
http://www.domainname.com/insert.php?Phone=07000888888
change:
$phone = mysql_real_escape_string($_POST['phone']);
$sql = "INSERT INTO LiveFeed (phone) VALUES ('$_POST[Phone]')";
to
$phone = mysql_real_escape_string($_GET['Phone']);
$sql = "INSERT INTO LiveFeed (phone) VALUES ('$phone')";
Additionally for some extra input validation you could do something like:
$phone = mysql_real_escape_string($_GET['Phone']);
if(!ctype_digit($phone)){
echo "Incorrect Phone Number format";
}
$sql = "INSERT INTO LiveFeed (phone) VALUES ('$phone')";
That would make sure the phone number only has numbers in it (if that is indeed what you want and don't have +445498390 type numbers)
I finally figured it out.
The code itself was fine, it was the post string URL had an uppercase P in Phone.
once I changed it to phone it's now started working properly.
Thanks for all the help.
I was having this issue and it no matter what filtering I tried in PHP I could not stop the blank line from being inserted into my database records. What finally fixed the issue for me was adding .trim(); to my javascript variable. Hopefully, this will help someone else having similar issue!

Access denied for user 'unset_username'#'localhost' (using password: NO)

I have some PHP code that inserts data to MySQL database using MySQLi.
PHP code:
function insert_db($lat, $lng, $date, $user){
require('db_info_table.php');
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
return false;
}
$lat = mysql_real_escape_string($lat); // Sanitize data to prevent SQL injection
$lng = mysql_real_escape_string($lng);
$date = mysql_real_escape_string($date);
$user = mysql_real_escape_string($user); // << ERROR
$sql = "INSERT INTO table (lat, lng, date, user)
VALUES ('$lat', '$lng', '$date', '$user')";
if (mysqli_query($conn, $sql)) {
return true;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
return false;
}
mysqli_close($conn);
}
The connection details are located in a separate file in the same directory and it looks like this
$servername = "localhost";
$username = "user123";
$password = "pass123";
$dbname = "db123";
And I get these errors, I'm pretty sure one leads to another
mysql_real_escape_string(): Access denied for user 'unset_username'#'localhost' (using password: NO)
mysql_real_escape_string(): A link to the server could not be established in
And both errors appear on same line(look at the code).
It seems that you're connecting to server using mysqli library but then trying to use function from mysql library to secure you string. Use mysqli_real_escape_string() instead.
It basicaly doing the same thing as mysql_real_escape_string() but takes two params: first is connection link and second is variable that needs to be secured. So your code will look like this:
$lat = mysqli_real_escape_string($conn, $lat);
$lng = mysqli_real_escape_string($conn, $lng);
$date = mysqli_real_escape_string($conn, $date);
$user = mysqli_real_escape_string($conn, $user);

data not inserting I am using php mysql [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
<?php
error_reporting(0);
//connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "visionci";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//file properties
//if (isset($_POST['image']))
$file = $_FILES["image"]["tmp_name"];
if (!isset($file))
{//echo "Please Select an Image";
}
else
{ $name = $_POST["name"];
$rollno = $_POST["rollno"];
$address = $_POST["address"];
$duration = $_POST["duration"];
$course=$_POST["course"];
$fname = $_POST["fname"];
$mname = $_POST["mname"];
$image=addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$image_name= addslashes($_FILES["image"]["name"]);
$image_size= getimagesize($_FILES["image"]["tmp_name"]);
if($image_size==FALSE)
{echo "That's not an Image";}
else
{
$sql = "INSERT INTO insert (rollno,name,image,address,duration,fname,mname,course)VALUES('$rollno','$name','$image','$address','$duration','$fname','$mname','$course')";
if ($conn->query($sql) === TRUE)
{
//$lastid= mysqli_insert_id($conn);
echo "Record Inserted Successfully!";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
Above is my code. I am getting some garbage value followed by an error [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert (rollno,name,image,address,duration,fname,mname,course)VALUES('','','ÿØ' at line 1]
Let me know where I am getting problem I am Stuck.
Change your table name from insert. That can't be distinguished from the command insert, and you couldn't select from a table named insert without escaping
INSERT INTO something_else
or
INSERT INTO `insert`
$sql = "INSERT INTO insert (rollno,name,image,address,duration,fname,mname,course)VALUES('$rollno','$name','$image','$address','$duration','$fname','$mname','$course')";
Here you have used a "insert" as a table name. It is a Reserved key word in MySQL so change that name in to another value and try again.

Categories