MySQL Update 2 tables using 2 mysql_query() in single php script - php

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

Related

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 update a row in sql with loop?

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.

Update images in table keeping the old ones

I got 12 images and i want to update/edit them with a form. I choose to update one or more but not all of them, but keep the old image name in database.
I tried the following code but when i update one or two images, it's not keeping the old ones and the table field is null.
foreach($_FILES['more_images']['name'] as $key => $post_image) {
$getOld_ImageName = mysql_query("SELECT `image` FROM `more_images` WHERE `car_id` = '$id' AND `key` = '$key'") or die(mysql_error());
$getOld_Image = mysql_fetch_array($getOld_ImageName);
$more_imageOld = $getOld_Image['image'];
if (isset($post_image)) {
$file_name = $_FILES['more_images']['name'][$key];
$file_tmp = $_FILES['more_images']['tmp_name'][$key];
if($file_name == $more_imageOld) {
$updateMore_Images = mysql_query("UPDATE `more_images` SET `image` = '$more_imageOld' WHERE `car_id` = '$id' AND `key` = '$key'") or die(mysql_error());
} else {
move_uploaded_file($file_tmp, "$uploaddir/$file_name");
$updateMore_Images = mysql_query("UPDATE `more_images` SET `image` = '$file_name' WHERE `car_id` = '$id' AND `key` = '$key'") or die(mysql_error());
}
} else {
if ($key == $getOld_Image['key']) {
$post_image = $more_imageOld;
$updateMore_Images = mysql_query("UPDATE `more_images` SET `image` = '$post_image' WHERE `car_id` = '$id' AND `key` = '$key'") or die(mysql_error());
}
}
}
The $_FILE returns the new image names and blank on images that im keeping.
0 =
1 = 4061857_1_b.jpg
2 = 4061857_2_b.jpg
3 = 4061857_3_b.jpg
4 = 4061857_4_b.jpg
5 = 4061857_5_b.jpg
6 =
7 =
8 =
9 =
10 =
11 =
In other words im trying to update the table and where every $key is blank to keep the previous image name in the table as it was.
Any suggestions ?
I changed the if (isset($post_image)) to if (!empty($post_image)) and it worked.

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 get all affected rows for multiple statements in one query

MySQL/PHP:
For a query with multiple statements, which deletes rows in four different tables, I want to know the combined number of affected rows. The PHP manual says I'll only get the result from the last 'operation', which suggests it will only tell me how many rows were affected by the last of the DELETE statements.
How to get around this?
$deleteContactSQL = "DELETE FROM `persons` WHERE `persons`.`id` = '$person' AND `owner = '$user' AND `userOrContact` = 'contact';
DELETE FROM `tabs` WHERE `person` = '$person' AND `ownerIdentity` = '$user' AND `selfOrOther` = 'other';
DELETE FROM `tabAccess` WHERE `person`= '$person' AND `givenToIdentity` = '$user';
DELETE FROM `personAccess` WHERE `viewedPerson` = '$person' AND `viewerIdentity` = '$user';
;";
include $_SERVER['DOCUMENT_ROOT'].'/goalview/includes/db.inc.php';
$deleteContacts = mysqli_query($link, $deleteContactSQL);
$success = mysqli_affected_rows($link);
Something like this maybe?
include $_SERVER['DOCUMENT_ROOT'] . '/goalview/includes/db.inc.php';
$sql = array();
$sql[] = "DELETE FROM `persons` WHERE `persons`.`id` = '$person' AND `owner = '$user' AND `userOrContact` = 'contact';"
$sql[] = "DELETE FROM `tabs` WHERE `person` = '$person' AND `ownerIdentity` = '$user' AND `selfOrOther` = 'other';"
$sql[] = "DELETE FROM `tabAccess` WHERE `person`= '$person' AND `givenToIdentity` = '$user';"
$sql[] = "DELETE FROM `personAccess` WHERE `viewedPerson` = '$person' AND `viewerIdentity` = '$user';"
$aff_rows = 0;
foreach($sql as $current_sql)
{
$deleteContacts = mysqli_query($link, $current_sql);
$aff_rows = $aff_rows + mysqli_affected_rows($link);
}
Here is a compact, procedural-style mysqli_multi_query() solution for counting combined affected rows:
$deleteContactSQL="DELETE FROM `persons` WHERE `id`='$person' AND `owner='$user' AND `userOrContact`='contact';
DELETE FROM `tabs` WHERE `person`='$person' AND `ownerIdentity`='$user' AND `selfOrOther`='other';
DELETE FROM `tabAccess` WHERE `person`='$person' AND `givenToIdentity`='$user';
DELETE FROM `personAccess` WHERE `viewedPerson`='$person' AND `viewerIdentity`='$user';";
include $_SERVER['DOCUMENT_ROOT'].'/goalview/includes/db.inc.php';
if(mysqli_multi_query($link,$deleteContactSQL)){
do{
$success+=mysqli_affected_rows($link);
}while(mysqli_more_results($link) && mysqli_next_result($link));
}
Alternatively, this group of queries may be a good candidate for some TRIGGERs in the persons table.
I'd be doing it like this, but, I do like to keep things simple which not everyone can appreciate ;)
$deleteContactSQL = sprintf("call cascade_delete_persons(%d,%d)", $person, $user);
$deleteContacts = mysqli_query($link, $deleteContactSQL);
drop procedure if exists cascade_delete_persons;
delimiter #
create procedure cascade_delete_persons
(
in p_pid int unsigned,
in p_oid int unsigned
)
begin
declare v_persons_count int unsigned default 0;
declare v_tabs_count int unsigned default 0;
delete from persons where id = p_pid and owner = p_oid and userOrContact = 'contact';
set v_persons_count = row_count();
delete from tabs where person = p_pid and ownerIdentity = p_oid and selfOrOther = 'other';
set v_tabs_count = row_count();
-- etc...
select v_persons_count as person_count, v_tabs_count as tabs_count;
end #
delimiter ;
You can use this method too if you must : http://php.net/manual/en/mysqli.multi-query.php

Categories