how to solve update query error - php

My error is
Error while updating: 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 '1' at line 1
Kindly note down no error in speeling no error in post I checked every bit.. updation query is causing that error. I tried many times but didn't resolved. Thanks in advance.
<?php
include('db.php');
session_start();
if(isset($_POST['update']))
{
$fname = mysql_real_escape_string($_POST['fname'], $con1);
$lname = mysql_real_escape_string($_POST['lname'], $con1);
$phone = mysql_real_escape_string($_POST['phone'], $con1);
$zip = mysql_real_escape_string($_POST['zip'], $con1);
$city = mysql_real_escape_string($_POST['city'], $con1);
$country = mysql_real_escape_string($_POST['country'], $con1);
$userId = $_SESSION['userID'];
$strSQL = mysql_query("SELECT * FROM sarah_cloudRecord.user_info WHERE userId = '$userId'" , $con1);
//$Results = mysql_fetch_array($strSQL);
$numrows = mysql_num_rows($strSQL);
if($numrows != 0)
{
while ($row = mysql_fetch_assoc($strSQL))
{
$dblname = $row['lastName'];
$dbfname = $row['firstName'];
$dbphone = $row['phone'];
$dbzip = $row['zipCode'];
$dbcity = $row['city'];
$dbcountry = $row['country'];
if ($fname != $dbfname || $fname == $dbfname)
{
$newfName = $fname;
}
if ($lname != $dblname || $lname == $dblname)
{
$newlName = $lname;
}
if ($phone != $dbphone || $phone == $dbphone)
{
$newPhone = $phone;
}
if ($zip != $dbzip || $zip == $dbzip)
{
$newZip = $zip;
}
if ($city != $dbcity || $city == $dbcity)
{
$newCity = $city;
}
if ($country != $dbcountry || $country == $dbcountry)
{
$newCountry = $country;
}
}
$updateSQL = mysql_query("UPDATE sarah_cloudRecord.user_info SET firstName = '$newfName', lastName = '$newlName', phone = '$newPhone', city = '$newCity', zipCode = '$newZip', country = '$newCountry' WHERE userId = '$userId'", $con1);
if (mysql_query($updateSQL, $con1))
{
echo "Update Successfully!";
}
else {
echo "Error while updating: " . mysql_error($con1);
}
}
else {
echo "no records found";
}
}
else
{
?>
<script type="text/javascript">
window.location = "http://dev.metawarez.com/cloud/login.php";
</script>
<?php
}
?>

Using mysql_query two time. You change your update query to
$updateSQL = "UPDATE sarah_cloudRecord.user_info SET firstName = '$newfName', lastName = '$newlName', phone = '$newPhone', city = '$newCity', zipCode = '$newZip', country = '$newCountry' WHERE userId = '$userId'";
if (mysql_query($updateSQL, $con1))
Note:- mysql is deprecated instead use mysqli or pdo

You are querying the reply from the UPDATE, thats where the 1 comes from.
http://php.net/manual/de/function.mysql-query.php
$updateSQL = mysql_query("UPDATE sarah_cloudRecord.user_info SET firstName = '$newfName', lastName = '$newlName', phone = '$newPhone', city = '$newCity', zipCode = '$newZip', country = '$newCountry' WHERE userId = '$userId'", $con1);
if ($updateSQL !== false)
{
echo "Update Successfully!";
} else {
echo "Error while updating: " . mysql_error($con1);
}

Related

PHP Update Confusion

I am updating MySQL row using the following code. could any one tell me how i can error check the update query and only print Success if the update query was successful without any error? and print failed if update query was not successful!
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
// $get_contact = "SELECT * FROM `contacts` where contacts_id = '$contact_id'";
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '$contact_id'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='$fname',`last_name`='$lname',`cellphone_number`='$cphone',`city`='$city' WHERE contacts_id = ". $contact_id;
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>
My question is this: I'm doing my best to find whats the error and i couldn't what it is. It is for my elective project.
first of all please learn how to use procedure based query to be safe from SQL injection( I am not here to give tutorials on procedure and SQL injection, it is just warning against malicious code) and now your code solution. There was a problem in the way you were concatenating a variable with a string in your query. I have fixed that part for you.
if you still get any error then share what error you are getting and what is the error message.
<?php
//start the session
session_start();
// include db configuration
include('include/db_connect.php');
// user's information
$member_id = $_SESSION['id'];
$member_name = $_SESSION['name'];
$contact_id = $_GET['id'];
$get_contact = mysqli_query($conn, "SELECT * FROM `contacts` where contacts_id = '".$contact_id."'");
$row = mysqli_fetch_array($get_contact);
if(isset($_POST['submit'])){
$contact_id = $_POST['contact_id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$cphone = $_POST['cphone'];
$city = $_POST['city'];
$update = "UPDATE `contacts` SET `first_name`='".$fname."',`last_name`='".$lname."',`cellphone_number`='".$cphone."',`city`='".$city."' WHERE contacts_id = '".$contact_id."'";
if (mysqli_query($conn, $update)) {
echo "
<script>
var msg = confirm('Contact Updated');
if(msg == true || msg == false){
location.href='update_contact.php?id=$contact_id';
}
</script>
";
} else {
echo "Error: " . $update . "<br>" . mysqli_error($conn);
}
}
?>
use this function:
function alertBox($alert_msg, $redirect_link)
{
$alert = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
$alert .= '<script type="text/javascript">alert("'.$alert_msg.'");';
if(!empty($redirect_link)):
$alert .='window.location="'.$redirect_link.'";';
endif;
$alert .='</script>;';
return $alert;
}
// and for calling..
if((mysqli_query($con,$sql))
{
echo alertBox("sucessfull","example.php");
}

Show error message if that particular content is not in database

Here I have code where user is going to be created, they have to enter one accesscode given by admin. That accesscode is limited by some users like 10 or 20. After that it shows error like your accesscode is limited. So until now, it's working fine.
Now if user tries to enter accesscode that is not given by admin it has to show error message like your accesscode is wrong.
Here is my code:
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage'])) {
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage = 'Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username']))) {
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and `number` > `used` and status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret))) {
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if ($result = $DB->insert_record('user', $insert_record)) {
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
} else
$errorMessage = "error! can you please try again";
} else
$errorMessage = "your access code limit completed";
}
}
?>
Can you give us more information about your problem? What doesn't work?Try some "var_dump()" in your loop to know if you pass through or not so you can tell us where is the problem !
But first thing I see is here :
if(! $chk_username = $DB->get_record_sql($chk_sql, array($_POST['username'])) )
and here :
if($result = $DB->insert_record('user', $insert_record))
You should use "==" or "===" because using "=" means you assign a value to "$chk_username" and "result".
Then here is some librairie you can use if you want to display flash message, this is just for your information :
https://github.com/plasticbrain/PhpFlashMessages
And if you want to do it in JS you can use : https://github.com/CodeSeven/toastr
Hope it helps !
i changed the condition like this
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage']))
{
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage='Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username']))
)
{
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and
status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret)) )
{
if ( $chk_secret->used >= $chk_secret->number ) {
$errorMessage = "your access code limit completed..";
}else
{
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'],
PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if($result = $DB->insert_record('user', $insert_record))
{
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
}
else
$errorMessage = "error! can you please try again";
}
}
else
$errorMessage = "your access code is wrong..";
}
}
?>
it's working..

Login form validation always says WRONG USER DETAILS

This php code for login form validation. Why it always returns 'Wrong user data' (Грешни данни!). $name & $pass1 come from the login form which is in other file.
$activated has values 0 || 1 and it is to see if user confirmed registration from email.
<?php
//connection with database
require "db_connect.php";
require "password_compat-master/lib/password.php";
$name = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'name'))));
$pass1 = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'pass1'))));
$errorName = '';
$errorPass1 = '';
$feedback = '';
$mainError = false;
//get hash
$retHash = "SELECT password FROM users WHERE user_name='$name'";
$query_retHash = mysqli_query($conn, $retHash);
$row = mysqli_fetch_array($query_retHash);
$hash = $row['password'];
//get name
$retName = "SELECT user_name FROM users WHERE user_name='$name'";
$query_retName = mysqli_query($conn, $retName);
$row = mysqli_fetch_array($query_retName);
$uname = $row['user_name'];
//get 'activated'
$retAct = "SELECT user_name FROM users WHERE user_name='$name'";
$query_retAct = mysqli_query($conn, $retAct);
$row = mysqli_fetch_array($query_retAct);
$activated = $row['activated'];
if (filter_input_array(INPUT_POST)) {
if ($name !== $uname) {
$mainError = true;
}
if (!password_verify($pass1, $hash)) {
$mainError = true;
}
if ($activated != 1) {
$mainError = true;
}
if (!$mainError) {
$feedback = 'Здравей,' . $name . '!';
} else {
$feedback = 'Грешни данни!';
}
}
?>
As #Rajdeep Answered,
$retAct = "SELECT user_name FROM users WHERE user_name='$name'";
^ it should be activated
Better use one query. Fetch all details.
<?php
//connection with database
require "db_connect.php";
require "password_compat-master/lib/password.php";
$name = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'name'))));
$pass1 = mysqli_real_escape_string($conn, stripslashes(trim(filter_input(INPUT_POST, 'pass1'))));
$errorName = '';
$errorPass1 = '';
$feedback = '';
$mainError = false;
//get hash
$retHash = "SELECT * FROM users WHERE user_name='$name'";
$query_retHash = mysqli_query($conn, $retHash);
$row = mysqli_fetch_array($query_retHash);
$hash = $row['password'];
$uname = $row['user_name'];
$activated = $row['activated'];
if (filter_input_array(INPUT_POST)) {
if ($name !== $uname) {
$mainError = true;
}
if (!password_verify($pass1, $hash)) {
$mainError = true;
}
if ($activated != 1) {
$mainError = true;
}
if (!$mainError) {
$feedback = 'Здравей,' . $name . '!';
} else {
$feedback = 'Грешни данни!';
}
}
?>
Look at this statement here,
//get 'activated'
$retAct = "SELECT user_name FROM users WHERE user_name='$name'";
^ it should be activated
And there's no point running three separate queries. You can achieve the same thing using only one query, like this:
// your code
$query = "SELECT user_name, password, activated FROM users WHERE user_name='$name' LIMIT 1";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result);
$uname = $row['user_name'];
$hash = $row['password'];
$activated = $row['activated'];
if (filter_input_array(INPUT_POST)) {
// your code
}

Can't get session variable to work in sql UPDATE statement

First page:
<?php
session_start();
//db info
$conn = new mysqli("$server","$user_name","$password","$database");
$sql = "SELECT id FROM Client_Information order by id desc limit 1";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
$id=$row['id'] + 1;
}
}
$_SESSION['id'] = $id;
$sitename = $_POST['sitename'];
$sitetype = $_POST['sitetype'];
$color1 = $_POST['color1'];
$color2 = $_POST['color2'];
$color3 = $_POST['color3'];
$color4 = $_POST['color4'];
$sitedescription = $_POST['sitedescription'];
$aboutme = $_POST['aboutme'];
$contactname = $_POST['contactname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address = $_POST['address'];
if (isset($sitename) && isset($sitetype) && isset($color1)
&& isset($color2) && isset($contactname) && isset($phone)
&& isset($email) && isset($address) && isset($sitedescription)
&& isset($aboutme)) {
$sql = "INSERT INTO Client_Information (id, sitename, sitetype, color1, color2,
color3, color4, sitedescription, aboutme,
contactname, phone, email, address, timestamp)
VALUES ('$id', '$sitename', '$sitetype', '$color1', '$color2',
'$color3', '$color4', '$sitedescription', '$aboutme',
'$contactname', '$phone', '$email', '$address',
CURRENT_TIMESTAMP)";
$conn->query($sql);
header('Location: images.php');
}
mysqli_close($conn);
?>
Second page:
<?php
session_start();
echo $_SESSION['id'];
//db info
$conn = new mysqli("$server","$user_name","$password","$database");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$wherevar = $_SESSION['id'];
$exsitename1 = $_POST['exsitename1'];
$exsitename2 = $_POST['exsitename2'];
$exsitename3 = $_POST['exsitename3'];
$exsitename4 = $_POST['exsitename4'];
$exsiteurl1 = $_POST['exsiteurl1'];
$exsiteurl2 = $_POST['exsiteurl2'];
$exsiteurl3 = $_POST['exsiteurl3'];
$exsiteurl4 = $_POST['exsiteurl4'];
$exsitedescr1 = $_POST['exsitedescr1'];
$exsitedescr2 = $_POST['exsitedescr2'];
$exsitedescr3 = $_POST['exsitedescr3'];
$exsitedescr4 = $_POST['exsitedescr4'];
if (isset($exsitename1) && isset($exsitename2) && isset($exsitename3) && isset($exsitename4)
&& isset($exsiteurl1) && isset($exsiteurl2) && isset($exsiteurl3) && isset($exsiteurl4)
&& isset($exsitedescr1) && isset($exsitedescr2) && isset($exsitedescr3) && isset($exsitedescr4)) {
$sql = "UPDATE Client_Information
SET exsitename1='$exsitename1', exsitename2='$exsitename2', exsitename3='$exsitename3',
exsitename4='$exsitename4', exsiteurl1='$exsiteurl1', exsiteurl2='$exsiteurl2',
exsiteurl3='$exsiteurl3', exsiteurl4='$exsiteurl4', exsitedescr1='$exsitedescr1',
exsitedescr2='$exsitedescr2', exsitedescr3='$exsitedescr3', exsitedescr4='$exsitedescr4'
WHERE id = '$wherevar'";
$conn->query($sql);
header('Location: index.php');
}
session_destroy();
mysqli_close($conn);
?>
So the first page works fine and inserts all the data into the db, but when the second page is ran, it doesn't update the same row that was inserted on the first page. It just leaves all those variable.
On the second page, I'm trying to have it edit the row that was just created.

register form + insert query do not work how to fix it [duplicate]

This question already has an answer here:
Register form with php, mysql
(1 answer)
Closed 9 years ago.
I have a register form that required some input from user. The form was working fine but now it doesn't insert any value to the database. Can anyone help me?
I will display all the code but what I need is help about the insert query:
register.php
<?php require_once('for members/scripts/connect.php'); ?>
<?php
function specializationQuery(){
$specData = mysql_query("SELECT * FROM specialization");
while($recordJob = mysql_fetch_array($specData)){
echo'<option value="' . $recordJob['specialization_id'] . '">' . $recordJob['specialization_name'] . '</option>';
}
}
//default value
$message = "Fields Marcked with an [*] are Required";
$username = "";
$fname = "";
$lname = "";
$specialization = "";
$email = "";
$pass1 = "";
$pass2 = "";
$governorate="";
$district = "";
$village = "";
if(isset($_POST['username'])){
$username = mysql_real_escape_string($_POST['username']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$email = mysql_real_escape_string($_POST['email']);
$pass1 = mysql_real_escape_string($_POST['pass1']);
$pass2 = mysql_real_escape_string($_POST['pass2']);
$bdate = mysql_real_escape_string($_POST['birthdate']);
$specialization = mysql_real_escape_string($_POST['specialization']);
$governorate = mysql_real_escape_string($_POST['governorate']);
#$district = mysql_real_escape_string($_POST['district']);
#$village = mysql_real_escape_string($_POST['village']);
var_dump($fname);
var_dump($username);
var_dump($governorate);
var_dump($email);
//error handeling
if((!$username)||(!$fname)||(!$lname)||(!$email)||(!$pass1)||(!$pass2)||(!$specialization)||(!$governorate)||(!$district)||(!$village)){
$message = "**** Please insert the Required Fields below ****<br />";
if($fname == "")
{
$message = $message . "Enter First name<br/>";
}
if($lname == "")
{
$message = $message . "Enter Last name<br/>";
}
if( $specialization == 0)
{
$message = $message . "Select Your Job<br />";
}
if($governorate == 0)
{
$message = $message . "Select Your Governorate<br />";
}
if($district == '0')
{
$message = $message . "Select Your District<br />";
}
if($village == '0')
{
$message = $message . "Select Your Village<br />";
}
if($email == "")
{
$message = $message . "Enter Email Adress<br/>";
}
if ($username == "") {
$message = $message . "Enter User Name<br/>";
}
if($pass1 == "")
{
$message = $message . "Enter password<br/>";
}
if($pass2 == "")
{
$message = $message . "rechek the password <br/>";
}
}
elseif(strlen($pass1) <= 8)
{
$message = $message . "Your Password must be at least 8 charachters<br />";
}
else if($pass1!=$pass2){
$message = "your password do not match!";
}
else
{
//securing the data
$username = preg_replace("#[^0-9a-z]#i","",$username);
$fname = preg_replace("#[^0-9a-z]#i","",$fname);
$lname = preg_replace("#[^0-9a-z]#i","",$lname);
//$pass1 = sha1($pass1);
$email = mysql_real_escape_string($email);
// checking for duplicate
$user_query = mysql_query("SELECT user_name FROM user WHERE user_name = '$username'LIMIT 1") or die("could not check the username");
$count_username = mysql_num_rows($user_query);
$email_query = mysql_query("SELECT email_address FROM user WHERE email_address = '$email'LIMIT 1") or die("could not check the email");
$count_email = mysql_num_rows($email_query);
if($count_username > 0){
$message = " your username is alredy in use";
}elseif($count_email > 0){
$message = "your email is alredy in use";
}
else{
$query = mysql_query("INSERT INTO user(user_name, first_name, last_name, governorate, district, village, birth_date, email_address, specialization, password, registered_date)VALUES('$username', '$fname', '$lname', '$governorate', '$district', '$village', '$bdate', '$email', '$specialization', '$pass1', now())")or die("could not insert data");
$message = "you have now been registered";
//from the social website
if ($query)
{
$_SESSION['user_id'] = mysql_insert_id();
$_SESSION['login'] = 'true';
$_SESSION['login_user'] = $username;
}
?>
You need to separate code in files. You have wrote long like story.
$username = mysql_real_escape_string($_POST['username']); //such type of code so many times. Mine code is not good but better than yours. Try to divide code in functions and separate each logic in functions. So that it is easily understandable and changeable (change in 1 place should change in all places). Try to separate JS, HTML, PHP, error handling, etc. I haven't wrote whole working code but show you way, how you can improve.
function getPostedField($var){
if(!empty($_POST[$var]) and ($_POST[$var]!=0) ){
$var = mysql_real_escape_string($_POST[$var]);
return ($var);
}
return false;
}
if(isset($_POST['username'])){
$fields = array('username','fname','lname'.....);
$errors = 0;
$posted_arr = array();
foreach($fields as $field){
$value = getPostedField($field);
if($value){
$posted_arr[$field] = $value;
}else{
$errors++;
$error_msg .= "<p>$field should not be empty.</p>";
}
}
if($posted_arr['pass1']==$posted_arr['pass2'] and (strlen($posted_arr['pass2']<=8) ) ){
$errors++;
}
//do more checking here
if($error==0){
$query = "insert into `table`";
foreach($fields as $field){
$query .= "`$field`='".$posted_arr[$field]."',";
}
$len = strlen($query) - 1;
$query = substr($query,0,$len); //removing last ,
$sql_query = mysql_query($query);
}
}

Categories