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!";
}
}
}
Related
Hello I am trying to insert new client data into my sql table based on if customers_id exists or not.
If the customer_id exists, it should just ignore the client data.
I tried with primary keys, INSERT IGNORE and even with replace. But somehow its not working or just duplicating the existing data.
Could you please help to insert this data from JSON array to SQL based on if customers_id already exists or not.
This is my Base Code, Of-course this duplicates data and just inserts new data.
$datas = json_decode($jsondata, true);
foreach ($datas as $data)
{
$customers_id = $data['customers_id'];
$last_name = $data['last_name'];
$first_name = $data['first_name'];
$email = $data['email'];
$phone = $data['phone'];
$vat = $data['vat'];
$country = $data['country'];
$date_of_birth = $data['date_of_birth'];
$customers_code = $data['customers_code'];
$customers_ref_ext = $data['customers_ref_ext'];
$sql = "INSERT INTO clients(customers_id, last_name, first_name, email, phone, vat, country, date_of_birth,customers_code,customers_ref_ext)
VALUES('$customers_id', '$last_name', '$first_name', '$email', '$phone', '$vat', '$country', '$date_of_birth', '$customers_code', '$customers_ref_ext')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
just execute a select query, if it returning record then it means that the record you trying to insert is already exist in table.
$datas = json_decode($jsondata, true);
foreach ($datas as $data)
{
$customers_id = $data['customers_id'];
$last_name = $data['last_name'];
$first_name = $data['first_name'];
$email = $data['email'];
$phone = $data['phone'];
$vat = $data['vat'];
$country = $data['country'];
$date_of_birth = $data['date_of_birth'];
$customers_code = $data['customers_code'];
$customers_ref_ext = $data['customers_ref_ext'];
$query = "SELECT * FROM clients where customers_id = ".$customers_id;
$result = $conn->query($query);
if (mysqli_num_rows($result) == 0)
{
$sql = "INSERT INTO clients(customers_id, last_name, first_name, email, phone, vat, country, date_of_birth,customers_code,customers_ref_ext) VALUES('$customers_id', '$last_name', '$first_name', '$email', '$phone', '$vat', '$country', '$date_of_birth', '$customers_code', '$customers_ref_ext')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
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
}
I had created a database which named student with ID, name, mat_number, specialty, age, and gender, in a PHP application.
I do not want the name or mat_number be taken in more than once.
I have done the connection to my database in a different page and called it in the add student page.
This following codes is for a faculty database collection
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender))
{
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}
else{
echo "Error: Complete all records";
}
}
?>
I want to get an error message demanding for a change if the 2 fields already exist in the database.
first name to check in database if already exist the record.
if no record run sql insert command.
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
$sql = "SELECT * FROM `student` WHERE name = "'.$name.'" and UB_number = '".$matNo."'";
$conn->query($sql);
$cnt = $conn->rowCount();
if($cnt == 0){
$sql = "INSERT INTO `student`
(`name`, `UB_number`, `age`,`sex`, `specialty`)
VALUES
('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
header("Location: index.php");
}else{
echo "Error: Complete all records";
}
}
If you would like to insert a new record to DB only if one doesn't exist which has the same name or mat_number then you first need to execute SELECT statement to see if it exists.
Using MySQLi:
<?php
include 'mysqli.php';
$conn = $mysqli;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->bind_param('ss', $name, $matNo);
$stmt->execute();
$stmt->bind_result($exists);
$stmt->fetch();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)');
$stmt->bind_param('sssss', $name, $matNo, $age, $gender, $specialty);
$stmt->execute();
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
Using PDO:
<?php
include 'lib.php';
$conn = $pdo;
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
if ($name && $matNo && $age && $specialty && !$gender) {
$stmt = $conn->prepare('SELECT 1 FROM student WHERE name=? OR UB_number=?');
$stmt->execute([$name, $matNo]);
$exists = $stmt->fetchColumn();
if (!$exists) {
$stmt = $conn->prepare('INSERT INTO `student`(`name`, `UB_number`, `age`, `sex`, `specialty`) VALUES(?,?,?,?,?)')
->execute([$name, $matNo, $age, $gender, $specialty]);
exit(header("Location: index.php"));
} else {
echo 'A record with this name or material number already exists!';
}
} else {
echo "Error: Complete all records";
}
}
hope this may be helpfull to you. In here I asume that you are not using any framework. But if you use a framework there are plenty of easy methods to do this.In here I have checked only name field. You should update code as you wants. Also it it better if you could validate your inputs before check. Like trim(). Thanks
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$matNo = $_POST['mat_number'];
$age = $_POST['age'];
$specialty = $_POST['specialty'];
$gender = $_POST['gender'];
//after user click the submit button
$sql_Select_Stundets = "SELECT * FROM student WHERE name = '$name' ";
// query the sql with db connection
$result_sql_Select_Stundets = mysqli_query($conn,$sql_Select_Stundets);
//Now check the row count to verify the output if there is any match
$rowcount=mysqli_num_rows($result);
//Now write insert inside if condition
if( $rowcount >0 ) {
if(!empty($name) && !empty($matNo) && !empty($age) &&
!empty($specialty) && !empty($gender)) {
$sql = "INSERT INTO `student`(`name`, `UB_number`, `age`,
`sex`, `specialty`)
VALUES ('$name', '$matNo', '$age', '$gender', '$specialty')";
$conn->query($sql);
bheader("Location: index.php");
}else{
echo "Error: Complete all records";
}
}else{
echo "<script>
alert('sorry this name is already available');
</script>";
}
}
?>
I am trying to insert some data into my database with this code:
$username = $_SESSION['user'];
$naslov = $_POST['naslov'];//name
$geslo = $_POST['geslo'];//password
$vsebina = $_POST['vsebina'];//description
if (trim($_POST['naslov'])=="" || $_POST['geslo']=="" || $_POST['vsebina']==""){
$status = "<div class='alert-danger'>Fields are empty</div>";
}
else{
$link = open_database_connection();
echo $username;
echo $naslov;
echo $geslo;
echo $vsebina;
$sql = "INSERT INTO projects (name, password, description, username) VALUES ('$naslov','$geslo','$vsebina','$username')";
mysqli_query($link, $sql);
close_database_connection($link);
$status = "<div class='alert-success'>Vic je bil dodan.</div>";
}
The echo show the values i am putting into the forms, the SQL does not show any errors it just doesn't insert the values into the table.
check if form method is POST if its not then change the code to
$username = $_SESSION['user'];
$naslov = $_GET['naslov'];//name
$geslo = $_GET['geslo'];//password
$vsebina = $_GET['vsebina'];//description
if (trim($_GET['naslov'])=="" || $_GET['geslo']=="" || $_GET['vsebina']==""){
$status = "<div class='alert-danger'>Fields are empty</div>";
}
else{
$link = open_database_connection();
echo $username;
echo $naslov;
echo $geslo;
echo $vsebina;
$sql = "INSERT INTO projects (name, password, description, username) VALUES ('$naslov','$geslo','$vsebina','$username')";
mysqli_query($link, $sql);
close_database_connection($link);
$status = "<div class='alert-success'>Vic je bil dodan.</div>";
}
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']);