Updating one table if another table id matches - php

Okay, I am trying to update a table depending if it belongs to the user, So In one table for example I have pictures, like so:
+----------------------------------------------------+
| picture_id | picture_user | picture_title |
+----------------------------------------------------+
and in another table I have:
+--------------------------------------------------------------+
| delete_pic_id | delete_pic_user | delete_pic_status |
+--------------------------------------------------------------+
now I want to update delete_pic_status only if the delete_pic_user matches the picture_user
Here's what I am thinking but need a little help:
$manage_application = $database->prepare(
"UPDATE deleted_pic
SET delete_pic_status=1
WHERE delete_pic_user(the other table)=the id");
How would I go about accomplishing this

Use Exists
UPDATE deleted_pic
SET delete_pic_status = 1
WHERE EXISTS (SELECT 1
FROM other_table ot
WHERE ot.picture_user = deleted_pic.delete_pic_user)

UPDATE deleted_pic SET delete_pic_status=1 WHERE
delete_pic_user in (select picture_user from myOthertable)

I assume you are using PDO and as you have the id of the user in a session variable you can use a parameterised query like this
$sth = $database->prepare( "UPDATE deleted_pic
SET delete_pic_status = 1
WHERE delete_pic_user = :id");
$result = $sth->execute(array(':id' => $_SESSION['userId']) );
if ( $result ) {
// the delete worked
} else {
// the delete failed
}

Below query will fulfill your need-
update all rows based on checking existence in another table
UPDATE deleted_pic dp
JOIN other_table ot ON ot.picture_user = dp.delete_pic_user
SET delete_pic_status = 1;
update one table's data in another table for all rows-
UPDATE deleted_pic dp
JOIN other_table ot ON ot.picture_user = dp.delete_pic_user
SET dp.column1 = ot.column5;
update one table's data in another table for specific rows-
UPDATE deleted_pic dp
JOIN other_table ot ON ot.picture_user = dp.delete_pic_user
SET dp.column1 = ot.column5
where dp.status=1;

UPDATE deleted_pic
SET delete_pic_status=1
WHERE deleted_pic.delete_pic_user in(SELECT picture_user from tab2)

Related

Update value from one database to another database - fastest method

I have two tables.
first datatable structure has nine columns but the important three are:
code | name | value
2D3 | name test | 0.12
the second table has the same three columns.
Now I want to update all rows of the first table with the values of table two where code AND name are the same as in table two.
So my current idea is to do a select of all rows of table 1 with the code and name columns, than check if a row with the same code and name exists in table 2, if yes get that value and do a UPDATE query in table 1 with value of table 2.
The problem is that the two tables are hugh and I am sure that I am not using the fastest method.
anyone an idea for the fastest method to do this? Thank you very much!
EDIT: the query:
$getall = "SELECT code, name, value FROM table2";
$query = mysqli_query($conn, $getall );
while($result = mysqli_fetch_array($query))
{
$UpdateAll = "UPDATE table1 SET value = '".mysqli_real_escape_string($conn,$result["value"])."' WHERE name = '".mysqli_real_escape_string($conn,$result["name"])."' AND code = '".mysqli_real_escape_string($conn,$result["code"])."'";
$result2 = mysqli_query($conn, $UpdateAll); }
You speak of two databases but really mean two tables, don't you? In this case, you can do it with one update using a join, like this:
update table1 t1
inner join table2 t2 on t2.code = t1.code and t2.name = t1.name
set t1.value = t2.value;

MySQL Query to update multiple tables

I have a Quiz module in which I have two tables quiz_question and quiz_options. quiz_question is saving Questions
and quiz_option saving options for particular questions.
table structure for quiz_option:
id | question_id | text | is_correct
table structure for quiz_question
id | title | desctiption |
Where question_id is foreign key to id of quiz_question
I want to write a query to update quiz_question and all its corresponding quiz_options is a single query.
Multiple table update you can use foreign key connect two and more table with foreign key concept update parent table primary key to child table foreign key see link
http://www.hostingadvice.com/how-to/mysql-foreign-key-example/.
table quiz_question PK (question_id)
table quiz_option FK (question_id)
Get the id of the question and Update them one by one as you cannot update two tables using a single query.
$ID_VALUE = mysqli_real_escape_string($conn, $_GET['id']);
UPDATE quiz_option SET fields_name = 'value' WHERE question_id = $ID_VALUE;
UPDATE quiz_question SET fields_name = 'value' WHERE id = $ID_VALUE;
Here is the query:
INSERT INTO quiz_question(title,description) VALUES ('test','test question');
INSERT INTO quiz_option(question_id,text,is_correct) VALUES (LAST_INSERT_ID(),'test','0'),(LAST_INSERT_ID(),'test2','0'),(LAST_INSERT_ID(),'test3','0'),(LAST_INSERT_ID(),'test4','1')
try this
UPDATE table1 a
INNER JOIN table2 b
ON a.ID = b.ID
SET a.value = b.value

UPDATE, JOIN and WHERE MySQL

I'm currently working on my query. So I have two tables, tbl_room and tbl_reservation. I wanted to do an update query with the following conditions:
Decrement room counter by 1 in tbl_room if:
The first and last name of the customer matches the first and last name in the tbl_reservation
The tbl_reservation room ID matches with the tbl_room room ID
I'm currently stuck with this:
$result = mysql_query("UPDATE
tbl_room
JOIN tbl_reservation
ON tbl_room.roomID = tbl_reservation.roomID
AND tbl_reservation.cus_fname = '$cusFN'
AND tbl_reservation.cus_lname = '$cusLN' SET tbl_room.reserve = reserve - 1 ");
These are my tables:
----------
tbl_room
----------
roomID,
room_type,
capacity,
reserve <--- reservation counter
----------
tbl_reservation
----------
reserveID,
cus_fname,
cus_lname,
I already came up with the right query. Yehey! So I moved my query just after the while statement and used this syntax:
$result6 = mysql_query("UPDATE tbl_room
JOIN tbl_reservation ON tbl_room.roomID=tbl_reservation.roomID
AND tbl_reservation.cus_fname='$cusFN'
AND tbl_reservation.cus_lname='$cusLN'
SET tbl_room.reserve=tbl_room.reserve-1");
Try this...
$sql = "UPDATE `tbl_room`
SET `tbl_room`.`reserve` = `tbl_room`.`reserve` - 1
WHERE `tbl_room`.`roomID` = `tbl_reservation`.`roomID`
AND `tbl_reservation`.`cus_fname` = '$cusFN'
AND `tbl_reservation`.`cus_lname` = '$cusLN'";

A complicated mysql join

Ok, I have this first table which has, among other things:
table 1: id | depID (every id has one depID)
Then, I have a second table where I have table 2: userID | depID (where an userID is associated with multiple depIDs in separate rows. Also, I have table 3 with userID | rankID (where an userID is associated with one rankID).
I need to get all id and depID from table 1, and then to check, which userIDs of table 2 shares the same depID (table1.depID = table2.depID), and then, to check which of those userIDs from table 2 has rankID = $rID
Thanks guys.
I think this SQL should get you what you want, but I'm not 100% clear from the wording of the question:
SELECT table2.userID
FROM table1
JOIN table2
ON table1.depID = table2.depID
JOIN table3
ON table2.userID = table3.userID
AND table3.rankID = $rID;

Removing duplicate field entries in SQL

Is there anyway I can erase all the duplicate entries from a certain table (users)? Here is a sample of the type of entries I have. I must say the table users consists of 3 fields, ID, user, and pass.
mysql_query("DELETE FROM users WHERE ???") or die(mysql_error());
randomtest
randomtest
randomtest
nextfile
baby
randomtest
dog
anothertest
randomtest
baby
nextfile
dog
anothertest
randomtest
randomtest
I want to be able to find the duplicate entries, and then delete all of the duplicates, and leave one.
You can solve it with only one query.
If your table has the following structure:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`username` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;
you could do something like that (this will delete all duplicate users based on username with and ID greater than the smaller ID for that username):
DELETE users
FROM users INNER JOIN
(SELECT MIN(id) as id, username FROM users GROUP BY username) AS t
ON users.username = t.username AND users.id > t.id
It works and I've already use something similar to delete duplicates.
You can do it with three sqls:
create table tmp as select distinct name from users;
drop table users;
alter table tmp rename users;
This delete script (SQL Server syntax) should work:
DELETE FROM Users
WHERE ID NOT IN (
SELECT MIN(ID)
FROM Users
GROUP BY User
)
I assume that you have a structure like the following:
users
-----------------
| id | username |
-----------------
| 1 | joe |
| 2 | bob |
| 3 | jane |
| 4 | bob |
| 5 | bob |
| 6 | jane |
-----------------
Doing the magic with temporary is required since MySQL cannot use a sub-select in delete query that uses the delete's target table.
CREATE TEMPORARY TABLE IF NOT EXISTS users_to_delete (id INTEGER);
INSERT INTO users_to_delete (id)
SELECT MIN(u1.id) as id
FROM users u1
INNER JOIN users u2 ON u1.username = u2.username
GROUP BY u1.username;
DELETE FROM users WHERE id NOT IN (SELECT id FROM users_to_delete);
I know the query is a bit hairy but it does the work, even if the users table has more than 2 columns.
You need to be a bit careful of how the data in your table is used. If this really is a users table, there is likely other tables with FKs pointing to the ID column. In which case you need to update those tables to use ID you have selected to keep.
If it's just a standalone table (no table reference it)
CREATE TEMPORARY TABLE Tmp (ID int);
INSERT INTO Tmp SELECT ID FROM USERS GROUP BY User;
DELETE FROM Users WHERE ID NOT IN (SELECT ID FROM Tmp);
Users table linked from other tables
Create the temporary tables including a link table that holds all the old id's and the respective new ids which other tables should reference instead.
CREATE TEMPORARY TABLE Keep (ID int, User varchar(45));
CREATE TEMPORARY TABLE Remove (OldID int, NewID int);
INSERT INTO Keep SELECT ID, User FROM USERS GROUP BY User;
INSERT INTO Remove SELECT u1.ID, u2.ID FROM Users u1 INNER JOIN Keep u2 ON u2.User = u1.User WHERE u1.ID NOT IN (SELECT ID FROM Users GROUP BY User);
Go through any tables which reference your users table and update their FK column (likely called UserID) to point to the New unique ID which you have selected, like so...
UPDATE MYTABLE t INNER JOIN Remove r ON t.UserID = r.OldID
SET t.UserID = r.NewID;
Finally go back to your users table and remove the no longer referenced duplicates:
DELETE FROM Users WHERE ID NOT IN (SELECT ID FROM Keep);
Clean up those Tmp tables:
DROP TABLE KEEP;
DROP TABLE REMOVE;
A very simple solution would be to set an UNIQUE index on the table's column you wish to have unique values. Note that you subsequently cannot insert the same key twice.
Edit: My mistake, I hadn't read that last line: "I want to be able to find the duplicate entries".
I would get all the results, put them in an array of IDs and VALUES. Use a PHP function to work out the dupes, log all the IDs in an array, and use those values to delete the records.
I don't know your db schema, but the simplest solution seems to be to do SELECT DISTINCT on that table, keep the result in a variable (i.e. array), delete all records from the table and then reinsert the list returne by SELECT DISTINCT previously.
The temporary table is an excellent solution, but I'd like to provide a SELECT query that grabs duplicate rows from the table as an alternative:
SELECT * FROM `users` LEFT JOIN (
SELECT `name`, COUNT(`name`) AS `count`
FROM `users` GROUP BY `name`
) AS `grouped`
WHERE `grouped`.`name` = `users`.`name`
AND `grouped`.`count`>1
Select your 3 columns as per your table structure and apply condition as per your requirements.
SELECT user.userId,user.username user.password FROM user As user
GROUP BY user.userId, user.username
HAVING (COUNT(user.username) > 1));
Every answer above and/or below didn't work for me, therefore I decided to write my own little script. It's not the best, but it gets the job done.
Comments are included throughout, but this script is customized for my needs, and I hope the idea helps you.
I basically wrote the database contents to a temp file, called the temp file, applied the function to the called file to remove the duplicates, truncated the table, and then input the data right back into the SQL. Sounds like a lot, I know.
If you're confused as to what $setprofile is, it's a session that's created upon logging into my script (to establish a profile), and is cleared upon logging out.
<?php
// session and includes, you know the drill.
session_start();
include_once('connect/config.php');
// create a temp file with session id and current date
$datefile = date("m-j-Y");
$file = "temp/$setprofile-$datefile.txt";
$f = fopen($file, 'w'); // Open in write mode
// call the user and pass via SQL and write them to $file
$sql = mysql_query("SELECT * FROM _$setprofile ORDER BY user DESC");
while($row = mysql_fetch_array($sql))
{
$user = $row['user'];
$pass = $row['pass'];
$accounts = "$user:$pass "; // the white space right here is important, it defines the separator for the dupe check function
fwrite($f, $accounts);
}
fclose($f);
// **** Dupe Function **** //
// removes duplicate substrings between the seperator
function uniqueStrs($seperator, $str) {
// convert string to an array using ' ' as the seperator
$str_arr = explode($seperator, $str);
// remove duplicate array values
$result = array_unique($str_arr);
// convert array back to string, using ' ' to glue it back
$unique_str = implode(' ', $result);
// return the unique string
return $unique_str;
}
// **** END Dupe Function **** //
// call the list we made earlier, so we can use the function above to remove dupes
$str = file_get_contents($file);
// seperator
$seperator = ' ';
// use the function to save a unique string
$new_str = uniqueStrs($seperator, $str);
// empty the table
mysql_query("TRUNCATE TABLE _$setprofile") or die(mysql_error());
// prep for SQL by replacing test:test with ('test','test'), etc.
// this isn't a sufficient way of converting, as i said, it works for me.
$patterns = array("/([^\s:]+):([^\s:]+)/", "/\s++\(/");
$replacements = array("('$1', '$2')", ", (");
// insert the values into your table, and presto! no more dupes.
$sql = 'INSERT INTO `_'.$setprofile.'` (`user`, `pass`) VALUES ' . preg_replace($patterns, $replacements, $new_str) . ';';
$product = mysql_query($sql) or die(mysql_error()); // put $new_str here so it will replace new list with SQL formatting
// if all goes well.... OR wrong? :)
if($product){ echo "Completed!";
} else {
echo "Failed!";
}
unlink($file); // delete the temp file/list we made earlier
?>
This will work:
create table tmp like users;
insert into tmp select distinct name from users;
drop table users;
alter table tmp rename users;
If you have a Unique ID / Primary key on the table then:
DELETE FROM MyTable AS T1
WHERE MyID <
(
SELECT MAX(MyID)
FROM MyTable AS T2
WHERE T2.Col1 = T1.Col1
AND T2.Col2 = T1.Col2
... repeat for all columns to consider duplicates ...
)
if you don't have a Unique Key select all distinct values into a temporary table, delete all original rows, and copy back from temporary table - but this will be problematic if you have Foreign Keys referring to this table

Categories