Is there anything wrong with mysqli update Query? - php

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'";

Related

unable to update City in only insert is performed

<?php
session_start();
include_once 'DBconfig.php';
extract($_GET);
$CityName = $_POST['CityName'];
if (isset($CityID))
{
$sql = "UPDATE city SET CityName = '$CityName', Modified = NOW() WHERE city.CityID = $CityID;";
}
else
{
$sql = "INSERT INTO city (CityID, CityName, Created, Modified) VALUES (NULL, '$CityName', NOW(), NOW());";
}
$result = mysqli_query($con, $sql);
if ($result)
{
header('location: ListCity.php');
}
else
{
header('location: AddEditCity.php');
}
?>
only insert block will be executed update not working $CityID variable is come from extract function so no naming convention issue can't resolve it please help
You are extracting from $_GET (which is always to be avoided) and then taking $CityName from $_POST. That is inconsistent as the request cannot be both a GET and a POST at the same time. It surely must be a POST request or the insert wouldn't be working at all. And as been commented, you should be using a prepared statement to avoid a SQL injection attack:
<?php
session_start();
include_once 'DBconfig.php';
$CityName = $_REQUEST['CityName'];
if (isset($_REQUEST['CityID']))
{
$CityID = $_REQUEST['CityID'];
$sql = "UPDATE city SET CityName = ?, Modified = NOW() WHERE city.CityID = ?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "si", $CityName, $CityID);
}
else
{
$sql = "INSERT INTO city (CityID, CityName, Created, Modified) VALUES (NULL, ?, NOW(), NOW())";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "s", $CityName);
}
$result = mysqli_stmt_execute($stmt);
if ($result)
{
header('location: ListCity.php');
}
else
{
header('location: AddEditCity.php');
}

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'";

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())";
...

Data is retrieved from DB but wont insert?

So when I want to retrieve data and check it i.e. if the email already exist echo already registered. That part works fine, however inserting the same data does not work. Are my conditionals ordered improperly?
(intentionally left out values for the dbhostname id pw variables)
$dbname = "hw2";
$link = mysqli_connect($dbhostname, $dbuserid, $dbpassword, $dbname);
$firstname = $_POST["signup-firstname"];
$lastname = $_POST["signup-lastname"];
$email = $_POST["signup-email"];
$password = $_POST["signup-password"];
$repassword = $_POST["signup-repassword"];
if ($password != $repassword){
echo "<br><h3>Passwords did not match. <br>Please try again.</h3>";
}
else {
$ret_email = "SELECT * FROM hw2 WHERE email = '$email'";
$result = mysqli_query($link, $ret_email);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0){
echo "This email is already registered.";
}
else{
$insert_query = "INSERT INTO hw2 (firstname, lastname, email, password, repassword) VALUES ('$firstname', '$lastname', '$email', '$password', '$repassword')";
echo "$insert_query";
}
}
?>
You should perform the query not only echoing it
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
if ($num_rows > 0){
echo "This email is already registered.";
}
else{
$insert_query = "INSERT INTO hw2 (firstname, lastname, email, password, repassword) VALUES ('$firstname', '$lastname', '$email', '$password', '$repassword')";
echo "$insert_query";
mysqli_query($link,$insert_query)
}

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