sql update query in php - php

I am trying to do an update query in php to update my database but the query is not working. It is probably something simple.
$query = "UPDATE Events
SET charity_name = '$charity_name' ,
charity_reg = $charity_reg ,
Event_Name = '$event_tit',
Event_Status_Code = '$event_stat',
Start_Date = $event_dat,
Hours = $event_hour,
location = '$event_loc',
Other_Details = $event_content,
event_image = $imageData,
image_name = '$imageName',
max_available_spaces = $event_spaces,
Event_type = '$eve_category',
event_cost = $event_cost,
event_organiser = '$event_organiser'
WHERE Event_ID = $the_event_id";

You are not putting quotes ('') around some values, that might be a problem unless all thoses values are boolean/ints. Make sure to put quotes around all values, like '$imageData' instead of $imageData Also watch out for sql injections when you are directly inputting the values in your query. Better to use prepared statements
$query = "UPDATE Events
SET charity_name = '$charity_name' ,
charity_reg = '$charity_reg' ,
Event_Name = '$event_tit',
Event_Status_Code = '$event_stat',
Start_Date = '$event_dat',
Hours = '$event_hour',
location = '$event_loc',
Other_Details = '$event_content',
event_image = '$imageData',
image_name = '$imageName',
max_available_spaces = '$event_spaces',
Event_type = '$eve_category',
event_cost = '$event_cost',
event_organiser = '$event_organiser'
WHERE Event_ID = $the_event_id;";
EDIT: as #dWinder mentioned: if $the_event_id is not an integer, make sure to also put quotes around that value.

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.

Not able to input string number into sql database using php

I have the following code:
if(isset($_POST['regKitsForm'])){
$kitsiteID = $_POST['kitsiteID'];
$sql = "SELECT patientID FROM patient WHERE patientNum=".$_POST['kitpatientID'];
$connect->execute($sql);
$get = $connect->fetch();
$kitpatientID = $get[0];
if(is_numeric($_POST['kitNum1'])) {
$kitNum1 = str_pad($_POST['kitNum1'], 5, '0', STR_PAD_LEFT);
$kitForm = $_POST['kitForm'];
$sql = "UPDATE form$kitForm SET v0".$kitForm."_dd_kitNum1=$kitNum1 WHERE patientID = $kitpatientID AND siteID = $kitsiteID";
This should be inputing e.g.: 00001 from $kitNum1, but it isn't... it's just inputing 1.
Please help
M
Make sure, that your database column is of a string type like varchar(5) and not of an integer type. In addition, put quotes around the value in your query so that it isn't interpreted as a number, but as a string instead:
$sql = "UPDATE form$kitForm SET v0".$kitForm."_dd_kitNum1='$kitNum1' WHERE patientID = $kitpatientID AND siteID = $kitsiteID";

SQL Update ceasing to work?

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

Categories