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.
Related
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>";
}
I'm trying to figure how to call a query once.
I have 6 different variables for images, title and desc.
In this code, I need to know how to loop for id from 0 to 6.
$date = new DateTime("NOW");
$image1 = 'SSSS';
$title1 = 'AAAA';
$desc1 = 'BBBB';
$image2 = 'RRRR';
$title2 = 'GGGG';
$desc2 = 'VVVV';
/// 4 vars later....
$id = 6;
$get = $this->db->queryRow("UPDATE `featured` SET `image` = '{$image.$id}', `title` = '{$title.$id}', `desc` = '{$desc.$id}', `date` = '{$date->format('Y-m-d H:i:s')}' WHERE id = '{$id}'");
return(object) $get;
To build a collection of Querys use the multi_query function.
Loop to build your Query string to pass to the db and concatenated by a semicolon.
<?php
for($i=0;$i <= $maxquerys;$i++){
$query = "UPDATE `featured` SET `image` = '".$image.$id."', `title` = ".$title.$id."', `desc` = '".$desc.$id."', `date` = '".$date->format('Y-m-d H:i:s')."' WHERE id = '".$id."';"
}
/* execute multi query */
if ($mysqli->multi_query($query)) {
while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
you may check also the result by
echo $mysqli->affected_rows;
?>
I have tried to use a simple $query model and it works fine.
Create a valid Query string to pass to the db
<?php
$query = "UPDATE `featured` SET `image` = '".$image.$id."', `title` = ".$title.$id."', `desc` = '".$desc.$id}."', `date` = '".$date->format('Y-m-d H:i:s')."' WHERE id = '".$id."';"
$result=$mysqli->query($query);
// Verify results
if(!$result) {
$ErrMessage = "ErrSqlQuery:" . $mysqli->error . "\n";
$mysqli->close();
die($ErrMessage);
}
you can check also the result by
echo $mysqli->affected_rows;
?>
$query_build = "";
foreach($arr as $$image){
$query_build .= "UPDATE `featured` SET `image` = '{$image.$id}', `title` = '{$title.$id}', `desc` = '{$desc.$id}', `date` = '{$date->format('Y-m-d H:i:s')}' WHERE id = '{$id}';";
}
$get = $this->db->queryRow($query_build);
Accumulate all the queries and execute all at once.
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.
for(some loop condition):
mysql_query("UPDATE `details` SET
`url_battlelog` = '".$stats[$out]['url_battlelog']."',
`url_bf3stats` = '".$stats[$out]['url_bf3stats']."',
`rank_img_medium` = '".$stats[$out]['rank_img_medium']."',
`country_name` = '".$stats[$out]['country_name']."',
`country` = '".$stats[$out]['country']."',
`country_flag` = '".$stats[$out]['country_flag']."',
`rank_number` = '".$stats[$out]['rank_number']."',
`score_total` = '".$stats[$out]['score_total']."',
`time_total` = '".$stats[$out]['time_total']."',
`dogtag_basic_img` = '".$stats[$out]['dogtag_basic_img']."',
`dogtag_basic` = '".$stats[$out]['dogtag_basic']."',
`dogtag_advance_img` = '".$stats[$out]['dogtag_advance_img']."',
`dogtag_advance` = '".$stats[$out]['dogtag_advance']."'
WHERE `name_player` = '".$stats[$out]['name_player']."'
")
or die(mysql_error());
for(2nd loop condition):
mysql_query("UPDATE `weapons` SET
`img` = '".$gun_img."',
`name` = '".$gun_name."',
`kit` = '".$gun_kit."',
`time` = '".$gun_time."',
`kills` = '".$gun_kills."',
`headshots` = '".$gun_hs."',
`shots` = '".$gun_shots."',
`hits` = '".$gun_hits."',
`star_total` = '".$gun_star_c."',
`star_img` = '".$gun_star_i."',
`star_need` = '".$gun_star_n."',
`rank_curr` = '".$gun_rank_c."',
`rank_all` = '".$gun_rank_w."',
`desc` = '".$gun_desc."',
`category` = '".$gun_cat."',
`range` = '".$gun_range."',
`fire_rate` = '".$gun_fire_rate."',
`ammo` = '".$gun_ammo."',
`auto_fire` = '".$gun_fire_auto."',
`burst_fire` = '".$gun_fire_burst."',
`single_fire` = '".$gun_fire_single."',
`unlock_total` = '".$unlock_total."',
`unlock_done` = '".$unlock_done."',
`unlock_p` = '".round($unlock_p)."'
WHERE `name_player` = '".$stats[$out]['name_player']."'
")
or die(mysql_error());
the problem is that only 2nd table (weapons) is updating, 1st table (details) is not showing any changes. Doesn't show any error.
I have same type of script for inserting data into both tables and its working fine.
I'm new to MySQL and PHP. sorry for bad English....
did you test by writing your SQL ? I think your [WHERE] condition is not fully filled
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'";