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

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

Related

Insert Data into SQL if doesn't exist before using 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;
}
}
}

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?

Trying to save user information, error

I am trying to save the information stored in the SQL but this error keeps coming out: "Error Saving Data. 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 'company = 'GlobalTop Inc.' where regid = 1' at line 6" What seems to be the error?
Here is the full code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<?php
include "db.php";
$gresult = ''; //declare global variable
//Start of edit contact read
if(isset($_POST["action"]) and $_POST["action"]=="edit"){
$id = (isset($_POST["ci"])? $_POST["ci"] : '');
$sql = "select regid, regname,
address, phone,
email,company from tblregistrants
where regid = $id";
$result = mysqli_query($link, $sql);
if(!$result)
{
echo mysqli_error($link);
exit();
}
$gresult = mysqli_fetch_array($result);
include 'update.php';
exit();
}
//Insert or Update contact information
if(isset($_POST['action_type']))
{
if ($_POST['action_type'] == 'add' or $_POST['action_type'] == 'edit')
{
//Sanitize the data and assign to variables
$regid = mysqli_real_escape_string($link, strip_tags($_POST['regid']));
$regname = mysqli_real_escape_string($link, strip_tags($_POST['regname']));
$phone = mysqli_real_escape_string($link, strip_tags($_POST['phone']));
$address = mysqli_real_escape_string($link, strip_tags($_POST['address']));
$email = mysqli_real_escape_string($link, strip_tags($_POST['email']));
$company = mysqli_real_escape_string($link, strip_tags($_POST['company']));
if ($_POST['action_type'] == 'add')
{
$sql = "insert into tblregistrants set
name = '$regname',
phone = '$phone',
address = '$address',
email = '$email'
company = '$company'";
}else{
$sql = "update tblregistrants set
name = '$regname',
phone = '$phone',
address = '$address',
email = '$email'
company = '$company'
where regid = $regid";
}
if (!mysqli_query($link, $sql))
{
echo 'Error Saving Data. ' . mysqli_error($link);
exit();
}
}
header('Location: view.php');
exit();
}
//Read registrants information from database : Stage 1
$sql = "select * from tblregistrants";
$result = mysqli_query($link, $sql);
if(!$result)
{
echo mysqli_error($link);
exit();
}
//Loop through each row on array and store the data to $reg_list[] : Stage 2
while($rows = mysqli_fetch_array($result))
{
$reg_list[] = array('regid' => $rows['regid'],
'regname' => $rows['regname'],
'address' => $rows['address'],
'phone' => $rows['phone'],
'email' => $rows['email'],
'company' => $rows['company']);
}
include 'view.php';
exit();
?>
You have missed , in both if and else statement after email = '$email'
if ($_POST['action_type'] == 'add')
{
$sql = "insert into tblregistrants set
name = '$regname',
phone = '$phone',
address = '$address',
email = '$email',
company = '$company'";
}else{
$sql = "update tblregistrants set
name = '$regname',
phone = '$phone',
address = '$address',
email = '$email',
company = '$company'
where regid = $regid";
}
Also use Prepared statement to prevent from SQL injection
as Lawrence suggested you are missing , on your query
try this:
$sql = "insert into tblregistrants set
name = '$regname',
phone = '$phone',
address = '$address',
email = '$email',
company = '$company'";
Change this,
$sql = "update tblregistrants set
name = '$regname',
phone = '$phone',
address = '$address',
email = '$email',
company = '$company'
where regid = $regid";
To this
$sql = "update tblregistrants set
name = '$regname',
phone = '$phone',
address = '$address',
email = '$email',
company = '$company'
where regid = '$regid'";

Is there anything wrong with mysqli update Query?

I cannot update my existing data in the tabular form of my CRUD web application. Is there anything wrong with the query ? This is my source of reference and I have follow the UPDATE query exactly as in here INSERT, UPDATE and DELETE with mysqli. This is my code.
<?php
//error_reporting(E_ALL^E_NOTICE);
function chgDate($date){
$temp=explode("-",$date);
return $temp[2]."-".$temp[1]."-".$temp[0];
}
$json=array();
$ic = $_POST['IC'];
$Fic = $_POST['fromIC'];
$name = $_POST['formName'];
$tel = $_POST['formTelephone'];
$gender = $_POST['formGender'];
$email = $_POST['formEmail'];
if(isset($_POST['formUni'])){
$uni = $_POST['formUni'];
}
$age = $_POST['formAge'];
$address = $_POST['formAddress'];
$dob = $_POST['formDOB'];
$process= $_POST['process'];
//include ("connect_db.php");
//include_once('connect_db.php');
$db = mysqli_connect("localhost","root","admin","li") or die("Connection Error: " . mysqli_error());
if($process == 'save'){
$SQL="Insert into biodata (IC, Name, Telephone, Gender, Email, University, Age, Address, DOB) values ('$Fic', '$name', '$tel', '$gender', '$email', '$uni', '$age', '$address', '".chgDate ($dob)."')";
$json['newrow']=$Fic;
} else if ($process == 'edit') {
$SQL="UPDATE biodata SET IC='$Fic', Name='$name', Telephone='$tel', Gender='$gender', Email='$email', University='$uni', Age='$age', Address='$address, DOB ='".chgDate ($dob)."' WHERE IC= '$ic'";
} else if ($process == 'delete') {
$SQL = "DELETE FROM biodata WHERE IC='$ic'";
}
$data = mysqli_query($db, $SQL);
if($data){
$json['msg']='success';
}else{
$json['msg']='fail';
}
echo json_encode($json);
?>
It seems you forgot to end the quotes
Address='$address'
Check it
$SQL="UPDATE biodata SET IC='$Fic', Name='$name',
Telephone='$tel', Gender='$gender', Email='$email', University='$uni',
Age='$age', Address='$address', DOB ='".chgDate ($dob)."' WHERE IC= '$ic'";

SQL first entry not adding to database

Could someone please help with the code below. I am trying to create a registration query, however when it is submitted, I get an error for the following line:
$insert_query = "insert into members (First_name, last_name, Address_1, Address_2, Postcode, Email, Membership_Number, Password) values('$fname','$lname','$address1','$address2','$postcode','$email','$member','$password')";
This is only affecting the first_name, as the other field names are successfully submitted.
Your help would be much appreciated!!
<?php
$con = mysql_connect("localhost","root","") or die(mysql_error());
$select_db = mysql_select_db("thistlehc",$con);
if(isset($_POST['register']))
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$address1 = mysql_real_escape_string($_POST['address1']);
$address2 = mysql_real_escape_string($_POST['address2']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$email = mysql_real_escape_string($_POST['email']);
$member = mysql_real_escape_string($_POST['member']);
$password = mysql_real_escape_string($_POST['password']);
$query = "select membership_number from members where membership_number='$member'";
$link = mysql_query($query)or die(mysql_error());
$num = mysql_num_rows($link);
if ($num>0){
echo 'Membership Number already exists'; //Membership number already taken
}
else {
$insert_query = "insert into members (First_name, last_name, Address_1, Address_2, Postcode, Email, Membership_Number, Password) values('$fname','$lname','$address1','$address2','$postcode','$email','$member','$password')";
$result = mysql_query($insert_query)or die(mysql_error());
echo "Registered Successfully!";
}
?>
Look's to me like you forgot to encapsulate the contents of your if statement.
if(isset($_POST['register']))
Because it doesn't have curly brackets around the code to be executed, only the first line immediately after is executed. In your case, the if statement seemingly returned false, and the line defining $fname was not executed, hence an undefined variable.
You want to use something similar to this -
if(isset($_POST['register'])){
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$address1 = mysql_real_escape_string($_POST['address1']);
...
}

Categories