I am trying to write from form to my SQL database. This is all local through WAMP, if that makes a difference.
The error I am receiving is as follows:
Error: INSERT INTO customers (yard, full_address, business_name, business_status, first_name, last_name, landline_number, mobile_number, email_address) VALUES ('Dominic', '123 Fake Street', 'Dom's Business Name', '', 'Dominic', 'Fichera', 0123456789', '0123456789', '')
Erreur de syntaxe pr�s de 's Business Name', '', 'Dominic', 'Fichera', 0123456789', '0123456789', '')' � la ligne 2
I've also uploaded an image here: http://s7.postimg.org/ecqci36nv/error_snippet.png
I am unsure if this error refers to an issue within my code, an issue with the way I've setup my SQL table or something completely different.
Here is the main chunk of my code where all of the action happens:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "login";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["yard"])) {
$yard_error = "Yard is required";
} else {
$yard = test_input($_POST["yard"]);
}
if (empty($_POST["full_address"])) {
$full_address_error = "Address is required";
} else {
$full_address = test_input($_POST["full_address"]);
}
if (empty($_POST["first_name"])) {
$first_name_error = "First name is required";
} else {
$first_name = test_input($_POST["first_name"]);
}
if (empty($_POST["last_name"])) {
$last_name_error = "Last name is required";
} else {
$last_name = test_input($_POST["last_name"]);
}
if ($_POST["business_status"] = "") {
$business_status_error = "Business status is required";
} else {
$business_status = test_input($_POST["business_status"]);
}
$business_name = $_POST["business_name"];
$landline_number = $_POST["landline_number"];
$mobile_number = $_POST["mobile_number"];
$email_address = $_POST["email_address"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customers (yard, full_address, business_name, business_status, first_name, last_name, landline_number, mobile_number, email_address)
VALUES ('$yard', '$full_address', '$business_name', '$business_status', '$first_name', '$last_name', $landline_number', '$mobile_number', '$business_status')";
if ($conn->query($sql) === TRUE) {
$yard_confirmation = $yard . "successfully saved.";
} else {
$yard_confirmation = "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I would recommend something like this:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
And:
$errors = array();
($_POST["business_name"]) ? $business_name = test_input($_POST["business_name"]) : $errors[] = "Business name is required!";
(Doing the same line for each $_POST variable)
Basically it's an if/else statement in one line (reduces clutter). If there is data in $_POST["business_name"], then $business_name will have the value parsed through test_input - if it has no value, then the errors array gets a new value!
After checking all the values and parsing them, you can do:
if(empty($errors)) {
//If there are no errors, continue inserting
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customers (yard, full_address, business_name, business_status, first_name, last_name, landline_number, mobile_number, email_address) VALUES ('$yard', '$full_address', '$business_name', '$business_status', '$first_name', '$last_name', $landline_number', '$mobile_number', '$business_status')";
if ($conn->query($sql) === TRUE) {
$yard_confirmation = $yard . "successfully saved.";
} else {
$yard_confirmation = "Error: " . $sql . "<br>" . $conn->error;
}
} else {
foreach($errors as $error) {
echo $error."<br />";
}
}
I would definitely recommend using PDO though, it allows you to bind values to queries.
'Dom's Business Name' is invalid, you'll need to escape it:
'Dom\'s Business Name'
Please consider using prepared statements.
You SQL-injected your own database lol. Though you do have a function for adding slashes called test_input() you forgot to use it in some places. Change these:
$business_name = $_POST["business_name"];
$landline_number = $_POST["landline_number"];
$mobile_number = $_POST["mobile_number"];
$email_address = $_POST["email_address"];
To these:
$business_name = test_input($_POST["business_name"]);
$landline_number = test_input($_POST["landline_number"]);
$mobile_number = test_input($_POST["mobile_number"]);
$email_address = test_input($_POST["email_address"]);
I'd encourage reading this.
Consider this php function http://php.net/manual/en/mysqli.real-escape-string.php and prepare your string before saving into database.
As others said, the problem is with apostrophe in the business name, but it could be with other characters that need to be escaped. And worst, your code is a candidate to be a victim of SQL injection.
For a solution, line:
$business_name = $_POST["business_name"];
should be changed by :
if ($_POST["business_name"] = "") {
$business_name_error = "Business name is required";
} else {
$business_name = test_input($_POST["business_name"]);
}
And the following three lines should be change in the same way.
In your query, your listed values, you're missing a single quote before "$landline_number".
Also, since you're not using prepared statements, I HIGHLY recommend you use mysqli_real_escape_string() for all user submitted variables to prevent injection. For example:
$variable = mysqli_real_escape_string($conn, $_POST['variable']);
Related
I'm pretty new to sql and php.
I'm trying to submit this form into mysql server but I keep getting this error...i'm not sure where the mistake is...
Error: INSERT INTO grooming (Address, Breed, City, Email, Firstname,
Lastname, NeuteredOrSpayed, PetName, PetType, PhoneNumber, State, Zip)
VALUES ('123 Main St','Chihuahua','Los
Angeles','blankemail#gmail.com','John','Doe','Yes','Iris','Dog','(555)123-4568','CA','90001')
Incorrect integer value: 'Yes' for column 'NeuteredOrSpayed' at row 1
This is the code:
<?php
$servername = "localhost";
$username = "root";
$password = "pwdpwd";
$dbname = "pet_shop";
$db = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
echo 'Could not connect: ' . mysql_error();
} else {
function clean_data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$firstname = clean_data($_POST['aptfirstname']);
$lastname = clean_data($_POST['aptlastname']);
$address = clean_data($_POST['aptaddress']);
$city = clean_data($_POST['aptcity']);
$state = clean_data($_POST['aptstate']);
$zip = clean_data($_POST['aptzip']);
$phonenumber = clean_data($_POST['aptphonenumber']);
$email = clean_data($_POST['aptemail']);
$petname = clean_data($_POST['aptpetname']);
$neutered = clean_data($_POST['aptneutered']);
$pettype = clean_data($_POST['aptpettype']);
$breed = clean_data($_POST['aptbreed']);
if ($neutered == "true") {
$neutered = "Yes";
} else {
$neutered = "No";
}
if ($pettype == "Cat") {
$breed = "";
}
$sql = "INSERT INTO grooming (Address, Breed, City, Email, FirstName, LastName, NeuteredOrSpayed, PetName, PetType, PhoneNumber, State, Zip) VALUES ('$address', '$breed', '$city', '$email', '$firstname', '$lastname', '$neutered', '$petname', '$pettype', '$phonenumber', '$state', '$zip')";
if ($db->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
?>
If you need more context to the form code I can post that as well, it was just a lot to post up on here
Its a simple datatype error the column you have in database called neutered has a datatype of Integer and the value you trying to insert is 'Yes' which is absolutely not an integer.
Try putting integer 1 and 0 for yes and no respectively.
it's very clear.. as #Berto99 and #Pete and others mentioned..
column 'NeuturedOrSpayed' datatype is INT, so in your code it should be like this
if ($neutered == "true") {
$neutered = 1; # it was 'Yes' --> string, need to be int, so 1
} else {
$neutered = 0; # it was 'No' --> string, need to be int, so 0
}
The code I have below is suppose to insert some information into a mysql database. For some reason every time I test it I get the error statement that it was not able to execute. Everything looks like it should work to me. Is there something I am missing here?
<?php
include("phpconnect.php");
$name = $_GET["name"];
$date = $_GET["date"];
echo $name;
echo $date;
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES ('$name', '1', '$date', '$date')";
if (mysqli_query($conn, $sql))
{
echo "Records added successfully.";
}
else
{
echo "ERROR: Could not execute $sql. "
.mysqli_error($conn);
}
mysqli_close($conn);
?>
Maybe, you should build your SQL statement slightly different. You can always throw an error message, better for the overview -
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES (?, 1, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param('sss', $name, $date, $date);
if (!$stmt->execute()) {
return false;
// or print error message
} else {
return true;
} else {
return false;
}
Or check this out - MySQL INSERT INTO with PHP $variable !
First Check your datbase connection
Second check your form method GET or POST then apply
Check your table column name
include("phpconnect.php");
if(isset($_POST['submit'])){
$name = $_POST["name"];
$date = $_POST["date"];
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit) VALUES ('$name', '1', '$date', '$date')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
Try something like this. This function accurately inserts into my database and also scrapes for SQL injection.
function addRestaurant() {
if(isset($_POST['submit'])) {
global $connection;
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$googlemapslink = $_POST['googlemapslink'];
$restauranttype = $_POST['restauranttype'];
$website = $_POST['website'];
$logo = $_POST['logo'];
$sitelink = $_POST['sitelink'];
if ($googlemapslink == "") {
$googlemapslink = "https://youtu.be/dQw4w9WgXcQ";
}
if ($website == "") {
$website = "https://youtu.be/dQw4w9WgXcQ";
}
if ($logo == "") {
$logo = "https://youtu.be/dQw4w9WgXcQ";
}
$name = mysqli_real_escape_string($connection, $name);
$address = mysqli_real_escape_string($connection, $address);
$city = mysqli_real_escape_string($connection, $city);
$state = mysqli_real_escape_string($connection, $state);
$zipcode = mysqli_real_escape_string($connection, $zipcode);
$googlemapslink = mysqli_real_escape_string($connection, $googlemapslink);
$restauranttype = mysqli_real_escape_string($connection, $restauranttype);
$website = mysqli_real_escape_string($connection, $website);
$logo = mysqli_real_escape_string($connection, $logo);
$sitelink = mysqli_real_escape_string($connection, $sitelink);
$query = "INSERT INTO `restaurants` (Name, Address, City, State, ZipCode, GoogleMapsLink, Website, RestaurantType, RestaurantLogo, SiteLink) ";
$query .= "VALUES (";
$query .= "'$name', ";
$query .= "'$address', ";
$query .= "'$city', ";
$query .= "'$state', ";
$query .= "'$zipcode', ";
$query .= "'$googlemapslink', ";
$query .= "'$website', ";
$query .= "'$restauranttype', ";
$query .= "'$logo', ";
$query .= "'$sitelink'); ";
$filesite = "restaurants/" . $sitelink;
$file = "restaurants/menu.php";
$contents = file_get_contents($file);
file_put_contents($filesite, $contents);
$result = mysqli_query($connection, $query);
if(!$result) {
die("Query failed." . mysqli_error($connection));
} else {
echo "Record updated!";
}
}
}
I have form that subscribers enter their email address and this gets posted to mysql database. The problem is that if you visit the page, even without subscribing, a record is added to the database even without the required email address. Even worse, it seems to be adding records every three seconds. How can i stop this? Is there something wrong in my code.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
header('location: index.php');
mysqli_close($conn);
Just check with the if statement if there is an email you can save and put saving to database into that if statement as below:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// create connection
$conn = mysqli_connect($servername, $username, $password);
// check connection
if (!$conn) {
die("connection error: " . mysqli_connect_error());
}
echo "connected";
$emailErr = ''; //it is a good practice to initialize variable before its use.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['email'])) {
$emailErr = "Email required";
} else {
$email = post_input($_POST['email']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!isset($emailErr)) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email address";
}
}
}
}
// function to clean email
function post_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// select correct database
mysqli_select_db($conn, "mailinglist");
//if you have an email in $email and there is no
//error in $emailErr
if(!empty($email) && empty($emailErr)) {
//insert it to the db.
//THIS IS INSECURE WAY - Check links in comments!
// query to insert email
$sql = "INSERT INTO subscribers (email) VALUES ('" . $_POST['email'] ."')";
if (mysqli_query($conn, $sql)) {
echo "Thank you for subscribing";
} else {
echo "Error creating record: " . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
header('location: index.php');
exit();
PHP code didn't insert.
<?php
$message = " ";
require "database.php";
if (isset($_POST["submit"])) {
if (empty($_POST["email"]) || empty($_POST["password"])) {
$message = "Email or Password is Incorrect";
} else {
$email = '$_POST[email]';
$pass = '$_POST[password]';
if ($email && $pass) {
$db = mysqli_select_db($conn, "auth");
$sqli = "INSERT INTO users (email, password) VALUES($email, $pass)";
if (mysqli_query($conn, $sqli)) {
$message = "New record created successfully";
} else {
$message = "Cannot create user!";
}
}
}
}
?>
$conn = mysqli_conncect("localhost","root","","auth");
I tried everything but not found the mistake to insert the query into the table.
Remove the single quotation in your else statement. PHP will interpret it as a string instead of a POST variable.
That is:
$email = $_POST['email'];
$pass = $_POST['password'];
I have the following code. I try to use my Submit button to insert the code into the database, but every time I use it and refresh the browser, empty fields get inserted into the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!". $cn->connect_error;
}
// once the button is clicked
if (isset($_POST['submitForm'])) {
//the values in the boxes
$name = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
$interest = $_POST['interest'];
$info = $_POST['info'];
//echo "connection successfully";
//Insert into table
$sql = "INSERT INTO miltb(name, email, password, interest, info, productorder) VALUES('$name', '$email', '$password', '$interest', '$info', 'none' )";
}
if ($cn->query($sql) == true) {
?><script>alert ("INSERTED SUCCESSFULLY!");</script><?php
} else {
echo "error: " . $sql . "\n" . $cn->error;
}
$cn->close();
?>
How would I fix it?
The reason empty fields get inserted in the database it's because you are not checking for empty fields, you need to check those empty fields first then if empty fields exists do not insert.
Well man there's a lot that you need to learn, you need to learn about
1.SQL Injections
2.mysqli prepared or pdo prepared statements.
3.Password hashing
Filter ,sanitize and validate user inputs
Never trust an input from the user, you must always treat a user input as if it comes from a dangerous hacker.
Then you code with prepared statements should look like this :
<?php
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!" . $cn->connect_error;
}
$error = "";
// once the button is clicked
if (isset($_POST['submitForm'])) {
// check for empty fiels
if (empty($_POST['fname'])) {
echo "Enter your name";
$error++;
} else {
$name = userInput($_POST['fname']);
}
if (isset($_POST['email'])) {
echo "enter email";
$error++;
} else {
$email = userInput($_POST['email']);
// validate email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
echo "enter a valid email";
$error++;
}
}
if (empty($_POST['password'])) {
echo "enter password";
$error++;
} else {
$password = userInput($_POST['password']);
$hash = password_hash($password, PASSWORS_DEFAULT); //hash the password
}
if (!empty($_POST['confpass']) && $_POST['confpass'] !== $_POST['password']) { //password confirmation
echo "passwords does not match";
$error++;
}
if (empty($_POST['interest'])) {
echo "enter interests";
$error++;
} else {
$interest = userInput($_POST['interest']);
}
if (empty($_POST['info'])) {
echo "enter info";
$error++;
} else {
$info = userInput($_POST['info']);
}
if ($error > 0) { // if we have errors don't insert to db
echo "you have " . $error . " error(s) on your form plz fix them";
} else { // no errors lets insert
// prepare and bind
$sql = $cn->prepare("INSERT INTO miltb(name, email, password, interest, info) VALUES (?, ?, ?,?,?)");
$sql->bind_param("sssss", $name, $email, $hash, $interest, $info);
if ($sql->execute()) {
echo "INSERTED SUCCESSFULLY!";
} else {
echo "could not insert ";
}
}
$sql->close();
$cn->close();
}
function userInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help and you will learn a thing or two, I stand to be corrected where I'm wrong
Use something like this to be sure values are inserted:
$name = isset($_POST['fname']) ? strval($_POST['fname']) : null;
if (empty($name)){
echo "Name can't be empty!";
exit();
}
Note: beware of SQL Injection. Using php function strval() is the least possible secutiry, but atleast use that, if nothing more.