Insert Data into SQL if doesn't exist before using PHP - php

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

Related

MySQL database could not be updated with PHP program

addmember.php
<?php
require_once("dbtools.inc.php");
$account = $_POST["account"];
$password = $_POST["password"];
$name = $_POST["name"];
$sex = $_POST["sex"];
$year = $_POST["year"];
$month = $_POST["month"];
$day = $_POST["day"];
$telephone = $_POST["telephone"];
$address = $_POST["address"];
$email = $_POST["email"];
$comment = $_POST["comment"];
$link = create_connection();
$sql = "SELECT * FROM users Where account = '$account'";
$result = execute_sql($link, "member", $sql);
if (mysqli_num_rows($result) != 0)
{
mysqli_free_result($result);
echo "<script type='text/javascript'>";
echo "alert('Account already in use! Please choose another username');";
echo "history.back();";
echo "</script>";
}
else
{
mysqli_free_result($result);
$sql = "INSERT INTO users (account, password, name, sex,
year, month, day, telephone, address,
email, comment) VALUES ('$account', '$password',
'$name', '$sex', $year, $month, $day, '$telephone',
'$address', '$email', '$comment')";
$result = execute_sql($link, "member", $sql);
echo "User added successfully!";
}
mysqli_close($link);
?>
join.html
<form action="addmember.php" method="POST" name="myForm">
(Different types of input)
<input type="submit" value="Add">
My aim is to add a member data into the database after the user clicked the Add button on the form in join.html. However the page could run echo "User added successfully!"; this line but the problem is the database could not get updated even though I already called execute_sql command. May I ask what is missing in order to be connected with the database?

I keep getting this same error when i try to submit an appointment request to sql

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
}

Not able to insert data into a mysql database

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!";
}
}
}

Registration page with PHP & MySQL

I have a registration page, which is tied to this process.php code below. When I run this code, it returns "Error". Did I make a mistake somewhere?
<?php
require_once ('newmeowconnection.php');
if (isset($_POST['form_input']) && $_POST['form_input'] == 'registration') {
registerUser();
}
function registerUser() {
$query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at)
VALUES('{$_POST['first_name']}','{$_POST['last_name']}','{$_POST['email']}', '{$_POST['password']}', NOW(), NOW())";
$run = mysqli_query($query);
if ($run) {
$_SESSION['loggedin'] = TRUE;
$_SESSION['user'] = $_POST['email'];
header('Location: http://localhost/homepage.php');
} else {
echo 'Error';
}
}
?>
mysqli_query need run on connection object or pass connection to it:
$run = mysqli->query($connection, $query);
or
$run = $connection->query($query);
The problem is you are using single quotes-inside single-quotes. For instance '{$_POST['first_name']}' is read as {$_POST[ being one thing first_name as a SQL variable and ]} another string.
Try the following
...
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO users (first_name, last_name, email, password, created_at, updated_at) VALUES('{$first_name}','{$last_name}','{$email}', '{$password}', NOW(), NOW())";
...

Why is mysql inserting a new row instead of updating it?

My code should be checking the database to see if the custID exists, and if it does, to update the information. It it doesn't, it needs to add the customer information to the database.
Currently, when I use the code I have, each time an order is made on the website, a new custID is added to the database.
These errors are occurring:
When a new customer orders, a new row is inserted. None of the information
from the fields is put into the database, just an empty row.
When a returning customer orders, their information is drawn from the
database on a previous page, but on this page it inserts a new row and the new fields
are left blank.
If this isn't enough information or isn't clear, I will gladly offer more code and explanation.
//The information is passed through a session object from a previous page.
if (ISSET($_SESSION['fname'])) {
session_start();
$email = $_SESSION['email'];
$fname = $_SESSION['fname'];
$lname = $_SESSION['lname'];
$street = $_SESSION['street'];
$city = $_SESSION['city'];
$state = $_SESSION['state'];
$zip = $_SESSION['zip'];
$safeID = $_SESSION['safeID'];
$custID = $safeID / 507921;
}
include_once("Connection.php");
include_once("header.html");
//check if customer is already in database
$sql = "SELECT *
FROM bookcustomers
where custID = '$custID'";
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
if (mysqli_num_rows($result) > 0 ) {
$sql = "UPDATE bookcustomers
set fname = '$fname',
lname = '$lname',
email = '$email',
street = '$street',
city = '$city',
state = '$state',
zip = '$zip'
WHERE custID = '$custID'";
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
}
else {
$sql = "INSERT into bookcustomers (fname,
lname,
email,
street,
city,
state,
zip)
VALUES ('$fname',
'$lname',
'$email',
'$street',
'$city',
'$state',
'$zip')";
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$custID = mysqli_insert_id($link);
}
session_start should be called before your if clause.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
If you change the top if on your php file
session_start();
if (ISSET($_SESSION['fname'])) {
$email = $_SESSION['email'];
$fname = $_SESSION['fname'];
$lname = $_SESSION['lname'];
$street = $_SESSION['street'];
$city = $_SESSION['city'];
$state = $_SESSION['state'];
$zip = $_SESSION['zip'];
$safeID = $_SESSION['safeID'];
$custID = $safeID / 507921;
}
include_once("Connection.php");
include_once("header.html");
This will resume your session, as long as you created the session correctly and set the fname session variable on the previous page.
If you've set the values correctly and change the if clause to the one above, it should work.
Can you try this, moved session_start(); top of if (ISSET($_SESSION['fname'])) { .
<?php
session_start();
if (ISSET($_SESSION['fname'])) {
$email = $_SESSION['email'];
$fname = $_SESSION['fname'];
$lname = $_SESSION['lname'];
$street = $_SESSION['street'];
$city = $_SESSION['city'];
$state = $_SESSION['state'];
$zip = $_SESSION['zip'];
$safeID = $_SESSION['safeID'];
$custID = $safeID / 507921;
}
include_once("Connection.php");
include_once("header.html");
//check if customer is already in database
$sql = "SELECT *
FROM bookcustomers
where custID = '$custID'";
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
if (mysqli_num_rows($result) > 0 ) {
$sql = "UPDATE bookcustomers
set fname = '$fname',
lname = '$lname',
email = '$email',
street = '$street',
city = '$city',
state = '$state',
zip = '$zip'
WHERE custID = '$custID'";
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
}
else {
$sql = "INSERT into bookcustomers (fname,
lname,
email,
street,
city,
state,
zip)
VALUES ('$fname',
'$lname',
'$email',
'$street',
'$city',
'$state',
'$zip')";
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$custID = mysqli_insert_id($link);
}
?>

Categories