HTTP Post to MySQL inserting Blank Rows - php

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!

Related

Store the data in mysql

i want to store a data to the mysql database but if i press the submit button it display the php page.
form:
<div id="test">
<form action="demo.php" method="post">
please enter the number(1 to 100) : <input type="text" name="value">
<input type="submit">
</form>
</div>
demo.php
<?php
$value=$_POST['value'];
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
if ($conn->query($input) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Replace $input with $sql in the if statement:
From
if ($conn->query($input) == TRUE) {
To
if ($conn->query($sql) == TRUE) {
Note: Since you are storing $_POST['value'] in $value, you don't need to use $_POST['value'] in the query, instead make use of $value.
There is one correction:
Change
if ($conn->query($input) == TRUE) {
To:
if ($conn->query($sql) == TRUE) {
Along with that, following are suggestions:
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
This query is OK, is value of $_POST['value'] is integer, but, for strings, it will create SQL Syntax Error.
Please correct this to:
$sql = "INSERT INTO input VALUES ('".$_POST['value']."')";
Observe, enclosed semi colon.
2) You are inserting only one field value and not specifying fields. This means you table has only field. Normally we do not have tables with only one field.
Please specify field names:
$sql = "INSERT INTO input (field_one) VALUES (".$_POST['value'].")";
Get values like this
$value=$_REQUEST['value'];
change the query to
$sql = "INSERT INTO input VALUES ('$value')";
1st : Add name attribute to submit button name="submit"
<input name="submit" type="submit">
2nd : use isset like this if(isset($_POST['submit'])){ //rest of code here }
3rd : Try to use prepared statement or pdo to avoid sql injection
demo.php
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$stmt = $conn->prepare("INSERT INTO input(value) VALUES (?)");
$stmt->bind_param('s',$_POST['value']);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
if ($stmt->execute() == TRUE && $stmt->affected_rows>0) {
echo "New record created successfully";
} else {
echo "Error: <br>" . $conn->error;
}
}
$conn->close();
?>

Inserting multiple rows into database through a link

I am quite new in php and mysql.
I was trying to insert multiple (unknown ) number of rows into mysql database. The data is posted into the table through a link -
http://localhost:81/logdata.php?CtrlID=3842&DateTime=2017-05-18+11%3A45%3A23&Bat=50.2&LVSD=1&Indt=29.4&Outdt=32.8&submit
The following code works perfect as long as a single row is posted. But I have no idea how to insert several rows together and how
the link should look like. Actually rows containing data are formed and stored in a Microcontroller.
I am sending the data with the help of GPRS. The controller successfully sending one row at a time, the data is correctly recorded in
mysql database. But I am struggling to send several rows together. I would highly appreciate any suggestion.
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your pwd
$dbname = "mirzu";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
if($conn){
echo 'Successfully Connected database.';
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//if(isset($_GET['submit'])){ //
$ID = $_GET['CtrlID'];
$DateTime = $_GET['DateTime'];
$battery = $_GET['Bat'];
$LVSD = $_GET['LVSD'];
$IndoorT = $_GET['Indt'];
$OutdoorT = $_GET['Outdt'];
$totalCtrlID = sizeof($ID);
for($i=0;$i<$totalCtrlID;$i++) {
$InsCtrlID = [$ID][$i];
$InsDateTime = [$DateTime][$i];
$Insbattery = [$battery][$i];
$InsLVSD = [$LVSD][$i];
$InsIndoorT = [$IndoorT][$i];
$InsOutdoorT = [$OutdoorT][$i];
$query = "INSERT INTO btsdata (CtrlID,DateTime,Batt,LVSD,IndT,OutdT)".
"VALUES ('$InsCtrlID','$InsDateTime','$Insbattery','$InsLVSD','$InsIndoorT','$InsOutdoorT');";
}
if (mysqli_query($conn, $query)) {
echo "New record created successfully into database";
} else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
//}
mysqli_close($conn);
?>
Two records the query will become:
INSERT INTO TABLE (column1, column2) VALUES ('data', 'data'), ('data', 'data')
Same as a more than two record.
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);

Cant insert specific row into the database PHP MySQL JSON

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

Php to MySQL database

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);
}

Simple insert into database doesn't work

I have a very simple bit of code to insert data into database.
It doesn't work. I do not get any error except cannot insert. I could connect to the database so that is not the issue.
The database has 3 fields, emailadd is the 2nd field. The other 2 are auto increment id and creation date, so also a field that on add, it will add current timestamp.
$inquiry = "INSERT INTO subscribe (emailadd) VALUES ('$myemail')";
$res = mysql_query($inquiry) or die("cannot insert");
$inquiry = "INSERT INTO `subscribe` (`emailadd`) VALUES ('$myemail')";
$res = mysql_query($inquiry,$con) or die('Not Inserted : ' . mysql_error());
Some time we need $con variable to identify the database connection, let see more check here
the mysql_query is deprecated, you need to use mysqli like so :
<?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 = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>

Categories