SQL Update ceasing to work? - php

I want to update a mysql database. That has become a common practice for me, but for some reason with no error, it just doesn't work. The only thing I have never done is compare against 2 variables(in this case, ID && Name)
$name = $_POST['name'];
$duty = $_POST['duty'];
$number = $_POST['number'];
$url = $_POST['url'];
$insert = "UPDATE vendors SET name = '$_POST[name]', duty = '$_POST[duty]', number = '$_POST[number]', url = '$_POST[url]' WHERE id = '$id' && name = '$name'";
$result=mysql_query($insert) or die(mysql_error());
if ($result) {
header("location:**HIDDEN**");
Any help would be appreciated.

Instead of &&, you should use AND to add another where-condition.

Write this instead:
$name = $_POST['name'];
$duty = $_POST['duty'];
$number = $_POST['number'];
$url = $_POST['url'];
$insert = "UPDATE `vendors` SET `name` = '{$_POST['name']}', `duty` = '{$_POST['duty']}', `number` = '{$_POST['number']}', `url` = '{$_POST['url']}' WHERE (`id` = '$id' AND `name` = '$name')";
$result = #mysql_query($insert) or die(mysql_error());
header("location:**HIDDEN**");
It should now work. Notify me if there still is a problem.

replace && with AND and you should be good

Your Query is wrong. Following is the correct one.
The way you have used the variables is wrong.
You had not written any code for $id. What is that?
$insert = "UPDATE vendors SET name = '".$_POST['name']."', duty = '".$_POST['duty']."', number = '".$_POST['number']."', url = '".$_POST['url']."' WHERE id = '$id' AND name = '$name'";

Related

PHP Update query no errors but not proceeding with the next page

I need help with the query, no errors or such but it is not proceeding to the next page, see query below:
<?php
$connect=mysqli_connect('localhost','root','','lawadmission');
session_start();
$reference_number = $_SESSION['reference_number'];
$citizenship = $_POST['citizenship'];
$region = $_POST['region'];
$spouse_name = $_POST['spouse_name'];
$place_of_birth = $_POST['place_of_birth'];
$civil_status = $_POST['civil_status'];
$no_of_children = $_POST['no_of_children'];
$weight = $_POST['weight'];
$height = $_POST['height'];
$degree = $_POST['degree'];
$school = $_POST['school'];
$yearGraduated = $_POST['yearGraduated'];
$elementary = $_POST['elementary'];
$elementaryDegreeObtained = $_POST['elementaryDegreeObtained'];
$elementaryPeriodOfAttendance = $_POST['elementaryPeriodOfAttendance'];
$highschool = $_POST['highschool'];
$highschoolDegreeObtained = $_POST['highschoolDegreeObtained'];
$highschoolPeriodOfAttendance = $_POST['highschoolPeriodOfAttendance'];
$college = $_POST['college'];
$collegeDegreeObtained = $_POST['collegeDegreeObtained'];
$collegePeriodOfAttendance = $_POST['collegePeriodOfAttendance'];
$postCollege = $_POST['postCollege'];
$postcollegeDegreeObtained = $_POST['postcollegeDegreeObtained'];
$postcollegePeriodOfAttendance = $_POST['postcollegePeriodOfAttendance'];
$other = $_POST['other'];
$otherDegreeObtained = $_POST['otherDegreeObtained'];
$otherPeriodOfAttendance = $_POST['otherPeriodOfAttendance'];
$query = "UPDATE applicants SET
citizenship = '$citizenship',
region = '$region',
spouseName = '$spouse_name',
placeOfBirth = '$place_of_birth',
civilStatus = '$civil_status',
childNo = '$no_of_children',
weight = '$weight',
height = '$height',
degree = '$degree',
school = '$school',
yearGraduated = '$yearGraduated',
elementary = '$elementary',
elementaryDegreeObtained = '$elementaryDegreeObtained',
elementaryPeriodOfAttendance = '$elementaryPeriodOfAttendance',
highschool = '$highschool',
highschoolDegreeObtained = '$highschoolDegreeObtained',
highschoolPeriodOfAttendance = '$highschoolPeriodOfAttendance',
college = '$college',
collegeDegreeObtained = '$collegeDegreeObtained',
collegePeriodOfAttendance = '$collegePeriodOfAttendance',
postCollege = '$postCollege',
postcollegeDegreeObtained = '$postcollegeDegreeObtained',
postcollegePeriodOfAttendance = '$postcollegePeriodOfAttendance',
other = '$other',
otherDegreeObtained = '$otherDegreeObtained' and
otherPeriodOfAttendance = '$otherPeriodOfAttendance'
WHERE referenceNo = '$reference_number'";
if(mysqli_query($connect, $query)){
header( "Location: registered.php" ); die;
echo "<script>window.open('registered.php','_self')</script>";
}
if(mysqli_connect_errno($connect))
{
echo 'Failed to connect';
}
?>
Your error is right here:
UPDATE applicants SET
...
other = '".$other."',
otherDegreeObtained = '".$otherDegreeObtained."' and <--- and
otherPeriodOfAttendance = '$otherPeriodOfAttendance'
This and should be a ,.
SQLInjection
Besides that you are open to SQL injection. As I said in the comments a single ' in any one of your inputs will wreck your query -via- SQLInjection.
Will take this small example
//$citizenship = $_POST['citizenship'];
UPDATE applicants SET citizenship = '{$_POST['citizenship']}'
Now if $_POST['citizenship'] is like it's or anything with a ' in it, this is what your query becomes:
UPDATE applicants SET citizenship = 'it's'
Now that s' will be unmatched and as such it will be a syntax error in your SQL, and you will be right back where you were. That's the best case. One thing that could be done is this (do not try this)
//don't do this
$_POST['otherPeriodOfAttendance'] = "' WHERE 1 --";
UPDATE applicants SET ... , otherPeriodOfAttendance='' WHERE 1 --WHERE referenceNo = ''
//OR
UPDATE applicants SET ... , otherPeriodOfAttendance='' WHERE 1
The -- is a comment in SQL, so the rest of the query is ignored after that. So what this will do is update every row in your DB, not just 1 as 1 is always true. In fact you could probably omit the WHERE all together. So just by putting in:
//don't do this either
$_POST['otherPeriodOfAttendance'] = "'--";
UPDATE applicants SET ... , otherPeriodOfAttendance=''--WHERE referenceNo = ''
//OR
UPDATE applicants SET ... , otherPeriodOfAttendance=''
I can basically wipe out that whole table, which is obviously not something we want to do.
I suggest looking up how to Prepare Queries in PHP. There are plenty of resources on this topic so I won't go into great detail here except to say beside the obvious security reasons, it also takes care of quotes.
If you can use array on your query else you edit your query that would clearly read the the values on your parameters. Also, please consider using var_dump or print_r for checking.
$query = "UPDATE applicants SET
citizenship = '".$citizenship."',
region = '".$region."',
spouseName = '".$spouse_name."',
placeOfBirth = '".$place_of_birth."',
civilStatus = '".$civil_status."',
childNo = '".$no_of_children."',
weight = '".$weight."',
height = '".$height."',
degree = '".$degree."',
school = '".$school."',
yearGraduated = '".$yearGraduated."',
elementary = '".$elementary."',
elementaryDegreeObtained = '".$elementaryDegreeObtained."',
elementaryPeriodOfAttendance = '".$elementaryPeriodOfAttendance."',
highschool = '".$highschool."',
highschoolDegreeObtained = '".$highschoolDegreeObtained."',
highschoolPeriodOfAttendance = '".$highschoolPeriodOfAttendance."',
college = '".$college."',
collegeDegreeObtained = '".$collegeDegreeObtained."',
collegePeriodOfAttendance = '".$collegePeriodOfAttendance."',
postCollege = '".$postCollege."',
postcollegeDegreeObtained = '".$postcollegeDegreeObtained."',
postcollegePeriodOfAttendance = '".$postcollegePeriodOfAttendance."',
other = '".$other."',
otherDegreeObtained = '".$otherDegreeObtained."',
otherPeriodOfAttendance = '".$otherPeriodOfAttendance."'
WHERE referenceNo = '".$reference_number."'";
my be problem is die function. remove Die function
if(mysqli_query($connect, $query))
{
header( "Location: registered.php" );
echo "<script>window.open('registered.php','_self')</script>";
}

SQL: Edit only if input is not null

I currently working on simple Christmas gifts database :) and I have a problem with my Edit function. When user select existing gift for edit (by ID) and enter new values (for example for price) I want only that the price is changed and everything else is kept as it was. I try to use function IFNULL but my code is not working as I expected. Everytime i get new value for price, the other fields are erased.
My code (Iam using MySQL):
else if($_REQUEST['btn_submit']=="Edit")
{
$gifts_id = $_POST["gifts_id"];
$year = $_POST["year"];
$whom = $_POST["whom"];
$category = $_POST["category"];
$what = $_POST["what"];
$shop = $_POST["shop"];
$url = $_POST["url"];
$price = $_POST["price"];
$note = $_POST["note"];
$status = $_POST["status"];
Db::query("
UPDATE `gifts`
SET
`year` = ifnull('$year',`year`),
`whom` = ifnull('$whom',`whom`),
`category` = ifnull('$category',`category`),
`what` = ifnull('$what',`what`),
`shop` = ifnull('$shop',`shop`),
`url` = ifnull('$url',`url`),
`price` = ifnull('$price',`price`),
`note` = ifnull('$note',`note`),
`status` = ifnull('$status',`status`)
WHERE
`gifts_id` = '$gifts_id';
");
echo("<p>Gift with ID:'$gifts_id' successfully updated</p>");
}
Thanks for answers!
PS: I code just for fun so please be mercyful :)
If your want to properly edit your values, first you should fill all your inputs with your old values so the user can edit them or leave them as it was. Then you can check that all the values are not null before calling the sql as shown below:
else if($_REQUEST['btn_submit']=="Edit")
{
$gifts_id = $_POST["gifts_id"];
$year = $_POST["year"];
$whom = $_POST["whom"];
$category = $_POST["category"];
$what = $_POST["what"];
$shop = $_POST["shop"];
$url = $_POST["url"];
$price = $_POST["price"];
$note = $_POST["note"];
$status = $_POST["status"];
if(!empty($gifts_id)&&!empty($year)&&!empty($whom)&&!empty($category)&&!empty( $what)&&!empty($shop)&&!empty($url )&&!empty($price)&&!empty($note)&&!empty($status))
{
Db::query("
UPDATE `gifts`
SET
`year` = ifnull('$year',`year`),
`whom` = ifnull('$whom',`whom`),
`category` = ifnull('$category',`category`),
`what` = ifnull('$what',`what`),
`shop` = ifnull('$shop',`shop`),
`url` = ifnull('$url',`url`),
`price` = ifnull('$price',`price`),
`note` = ifnull('$note',`note`),
`status` = ifnull('$status',`status`)
WHERE
`gifts_id` = '$gifts_id';
");
echo("<p>Gift with ID:'$gifts_id' successfully updated</p>");
}
else
{
echo("<p>Gift with ID:'$gifts_id' was not updated, please check your data</p>");
}
IFNULL tests only for the special NULL value, and quoted strings are never null. You should compare the strings with ''.
Db::query("
UPDATE `gifts`
SET
`year` = if('$year' = '',`year`, '$year'),
`whom` = if('$whom' = '',`whom`, '$whom'),
...
WHERE
`gifts_id` = '$gifts_id';
");
Another option is to build the query dynamically.
$assign_array = array();
foreach (array('year', 'whom', 'category', ...) AS $field) {
if ($_POST[$field] !== '') {
$assign_array[] = "`$field` = '{$_POST[$field]}'";
}
}
$assign_string = implode(',', $assign_array);
Db::query("
UPDATE `gifts`
SET $assign_string
WHERE `gifts_id` = '$gifts_id';");
Note, however, that this is vulnerable to SQL injection. If your DB API allows you to create prepared queries and provide an array of values, you should do that. You can build up the parametrized query and array of values in a similar manner to this.

how to use PDO rowCount() function in foreach?

i need some help , i have simple code like count rows in php, i use PDO ,
so i check if rowCount > 0 i do job if no other job but i have it in foreach function, in first step i get true result but in other i get invalid
so i think it is function like a closeCursor() in PDO but i try and no matter . maybe i do it wrong ?
it is part of my code
public function saveClinicCalendar($post){
$daysItm = '';
$Uid = $post['Uid'];
$ClinicId = $post['ClinicId'];
$type = $post['type'];
$resChck = '';
foreach($post['objArray'] as $arr){
foreach($arr['days'] as $days){
$daysItm = $days.",".$daysItm;
}
$daysItm = substr($daysItm, 0, -1);
$dateTime = $arr['dateTime'];
$sqlChck = 'SELECT * FROM clinic_weeks WHERE dates = :dates AND Uid = :Uid AND category = :category AND Cid = :Cid AND type = :type';
$resChck = $this->db->prepare($sqlChck);
$resChck->bindValue(":dates",$dateTime);
$resChck->bindValue(":Cid",$ClinicId);
$resChck->bindValue(":type",$type);
$resChck->bindValue(":Uid",$Uid);
$resChck->bindValue(":category",$Uid);
$resChck->execute();
$co = $resChck->rowCount();
if($co > 0){
/*UPDATE*/
$sql = 'UPDATE clinic_weeks SET dates = :dates ,time = :time, Cid = :Cid, type = :type, Uid = :Uid, category = :category ';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}else{
/*INSERT*/
$sql = 'INSERT INTO clinic_weeks (dates,time, Cid,type,Uid,category) VALUES (:dates,:time, :Cid,:type,:Uid,:category)';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}
$res->execute();
$resChck->closeCursor();
$resChck = null;
$daysItm = '';
}
}
what i am doing wrong?
many thanks to Barmar, he suggest me a true answer.
here is a code
$sql = "INSERT INTO clinic_weeks
(`timestam`,`time`,dates,Cid,type,Uid,category)
VALUES
('$timestamp','$daysItm','$dateTime','$ClinicId','$type','$Uid','$Uid')
ON DUPLICATE KEY UPDATE `time` = '$daysItm' ";
I use there "ON DUPLICATE KEY UPDATE" and it`s work perfectly!
instead a big code top of page i make a two line of code.

MYSQL Query not working as it should

$sql = "UPDATE `shows` SET `title` = '$title', `tagline` = '$tagline', `desc` = '$desc' , `img_src = '$imgsrc' WHERE id = $showid";
The query above does not want to work, I simply get a mysql_error saying error at '' on line 1;
Any idea where I am going wrong?
You're missing a tick:
`img_src = '$imgsrc' WHERE id = $showid";
should be:
`img_src` = '$imgsrc' WHERE id = $showid";

MySQL UPDATE doesn't change anything

I'm trying to update a database entry but it won't change anything. I'm getting no errors which confuses me...
Code:
if(isset($_GET['edit']))
{
$idn = $_GET['id'];
$namn = $_POST['namn'];
$adress = $_POST['adress'];
$postnummer = $_POST['postnummer'];
$postort = $_POST['postort'];
$email = $_POST['email'];
$status = 0;
echo $namn;
$sql="UPDATE ordrar SET namn = '$namn' AND adress = '$adress' AND postnummer = '$postnummer'
AND postort = '$postort' AND email = '$email' AND status = '$status' WHERE id = '$idn'";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
//$referer = $_SERVER['HTTP_REFERER'];
//header('Location:'. $referer);
}
Thanks for answers
/Victor
Your immediate problem is SQL syntax. Read the documentation on UPDATES and replace the ANDs with commas.
Your secondary, but possibly larger problem is that you're building a query out of untrusted user input. That's a recipe for a SQL injection attack. Use bind variables instead.
Ref this
Syntax for Update
UPDATE table_name SET field1=new-value1, field2=new-value2 [WHERE Clause]
Your query should
$sql="UPDATE ordrar SET namn = '$namn' , adress = '$adress' ,
postnummer = '$postnummer' , postort = '$postort' , email = '$email' ,
status = '$status' WHERE id = '$idn'";
if you get no errors it does mean that no records matched WHERE condition
or you're probably don't have $_GET['edit'] varibale set

Categories