SQL partially works but needs a few WHERE clauses - I think - mysql

How can I change this SQL to do the following:
If user is not in table, add them. [THIS PART WORKS]
If user IS in table AND favourite_active = 0 change it to favourite_active = 1.
If user is in table AND favourite_active = 1 change it to favourite_active = 0.
I need to add in WHERE clauses I think.
$result = mysql_query("SELECT * FROM tbl_favourites WHERE (user_id = '$who' AND favourite_id = '$usernum' AND favourite_active = '1')");
// if user does not exist in favourites, add them
if(mysql_num_rows($result) == 0)
{
mysql_query("INSERT INTO tbl_favourites (user_id, favourite_id, favourite_active) VALUES ('$who', '$usernum', '1')");
echo"You have added this user as a favourite";
}
// if user does exist and favourite_active = 1 change to 0
else {
mysql_query("UPDATE tbl_favourites SET favourite_active='0' WHERE user_id='$who' AND favourite_id='$usernum'");
echo"You have removed this user as a favourite";
}
// if user does NOT exist and favourite_active = 0 change to 1
else {
mysql_query("UPDATE tbl_favourites SET favourite_active='1' WHERE user_id='$who' AND favourite_id='$usernum'");
echo"You have removed this user as a favourite";
}

You can't have two else clauses in an IF. And you can't do the UPDATE in two separate queries, because the second one will simply undo the first one. Use the following query:
UPDATE tbl_favourites SET favourite_active = NOT favourite_active WHERE user_id = '$who' and `favourite_id = '$usernum'
I'm also not sure that the first part, which you say works, really works. Your SELECT query looks specifically for favourite_active = 1. If the user already exists with favourite_active = 0, you'll try to INSERT them. Is that really what you want? Maybe you should remove AND favourite_active = '1'.
If user_id and favourite_id form a unique index on the table, you can do the entire thing in a single query:
INSERT INTO tbl_favourites (user_id, favourite_id, favourite_active)
VALUES ('$who', '$usernum', '1')
ON DUPLICATE KEY UPDATE favourite_active = NOT favourite_active

Related

Can't update two tables in one Query

I've got two Queries to Update two tables:
First Table
UPDATE user_info SET `location` = ".$locationid.", `looking_for` = ".$lookingfor." WHERE `user_info`.`user_id` = ".$infoid.";
Second Table
UPDATE user_personality SET `personality` = '".$changedescription."' WHERE `user_personality`.`user_info_id` = ".$infoid.";
And I'm trying to merge those two Queries, using the same statement.
UPDATE user_info, user_personality
SET user_info.location = ".$locationid.", user_info.`looking_for` = ".$lookingfor.", user_personality.personality = '".$changedescription."'
WHERE `user_info`.`user_id` = ".$infoid."
AND `user_personality`.`user_info_id` = ".$infoid."
I'm not receiving any error message, but is not updating.
What am I doing wrong?
Thanks.
Just a guess...
"
UPDATE user_info i
JOIN user_personality p
ON p.user_info_id = i.user_id
SET i.location = $locationid
, i.looking_for = '$lookingfor'
, p.personality = '$changedescription'
WHERE i.user_id = $infoid;
";
If you set the 2 table fields equal to each other in the where clause it should work, so I believe you'd change your where clause to:
WHERE `user_info`.`user_id` = `user_personality`.`user_info_id`
AND `user_info`.`user_id` = ".$infoid."
MySQL definitely supports updating multiple tables, so the where clause that works for a multi table select statement should also work for an update.

Deleting my data in my table but not in database

I have a query here. I wanted to delete my data in my browser table but I dont want it to be deleted permanently, I just want it to be hidden. My problem is I don't know what kind of query will I be needing. Here is my delete query.
My table feilds are Id Name and Flag. I want to do is when the flag is 1 it shows up the table and if it is 0 it will be hidden when the delete button is pressed.
function delete()
{
$id = $this->input->get('id');
$sSQL = "DELETE FROM tableq where id = ?";
$this->db->query($sSQL, array($id));
}
You can just update the flag, and in your select query select only flag=1 Try this,
$sSQL = "update tableq set `flag` =0 where id = ?";
$this->db->query($sSQL, array($id));

Updating Multiple Rows and Columns of database in Joomla

I have a database similar to this:
table name = jos_school ... id = Primary key, name = Unique key
id name no_of_students no_of_staffs fees
1 schoolA 0 0 0
2 schoolB 0 0 0
...
...
In phpMyAdmin I did something like this, and it worked (successfully updated multiple rows and columns),
UPDATE jos_school
SET no_of_students = CASE name
WHEN 'schoolA' THEN '1523'
WHEN 'schoolB' THEN '546'
....
END,
no_of_staffs = CASE name
WHEN 'schoolA' THEN '1234'
WHEN 'schoolB' THEN '346'
....
END
WHERE name IN ('schoolA', 'schoolB')
However, I was not able to update the table USING JOOMLA's Update methods. I don't want to use foreach and update the table over 1000 times. I want to execute a single query.
I've also read: http://docs.joomla.org/Inserting,_Updating_and_Removing_data_using_JDatabase#Updating_a_Record
and dint found it helpful in this case.
So, can someone point me to the right direction.
You can query as below,
// Create a new query object.
$db = &JFactory::getDBO();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query="UPDATE jos_school SET no_of_students = CASE name";
foreach($data as $d)
{
$query.=".....";
}
$query.=".....";
$db->setQuery((string)$query);
Hope that helps ...

How do I update a table with fields selected from another table?

Although there are many questions similar to this, such as
"Updating a record from another table", but i could not get this working.
I have a query that selects and updates table sem_stdexamfinresmark. The select subquery returns multiple rows of data whose size may not be equal to the table being updated, but the update is now working.
The query looks like :
update sem_stdexamfinresmark sr,
(select
se.currsession,
str.studentid,
str.classid,
str.subjectid,
str.aggScore*(select gbtp.percentage from gb_termpercentage gbtp where gbtp.termname = se.examtype)/100 as aggPer,
str.aggGrade
from
sem_stdexamtermresr str,
sem_exam se
where
str.examid=se.examid and
se.examtype = 'Second Term' and
se.currsession =1 and classid='8'
) s
set
sr.SecondTermMark = s.aggPer and
sr.SecondTermGrade = s.aggGrade
where
sr.studentid=s.studentid and
sr.subjectid=s.subjectid and
s.currsession = s.currsession and
sr.classid='8';
EDIT:
update sem_stdexamfinresmark
set
sr.SecondTermMark = s.aggPer and
sr.SecondTermGrade = s.aggGrade
from
(select
se.currsession,
str.studentid,
str.classid,
str.subjectid,
str.aggScore*(select gbtp.percentage from gb_termpercentage gbtp where gbtp.termname = se.examtype)/100 as aggPer,
str.aggGrade
from
sem_stdexamtermresr str,
sem_exam se
where
str.examid=se.examid and
se.examtype = 'Second Term' and
se.currsession = 1 and classid='8'
) s
where
sr.studentid=s.studentid and
sr.subjectid=s.subjectid and
s.currsession =1 and
sr.classid='8';
select * from sem_exam;
update sem_exam set currsession =1;
try something that looks more like:
update foo
set col = bar.col
from bar
where ...
This is what happens when one loses sleep :( I just did a silly mistake here and added "and"

How do I change the case on every field in a mysql table in one call?

I have a table with 27 varchar fields. I want to make all fields lowercase, but i want to do it in one short mysql call.
This does a single field:
UPDATE table
SET field = LOWER(field)
How do I do the equivalent of this (which doesn't work):
UPDATE table
SET * = LOWER(*)
You can't do it with your creative attempt SET * = LOWER(*) etc.
You can however do it like this:
UPDATE table SET
column1 = LOWER(column1),
column2 = LOWER(column2),
-- etc, listing all text type columns
columnN = LOWER(columnN);
The reason there's no "shortcut" is probably because this pattern is so infrequently needed.
The consensus is that this cannot be done in a single mysql query.
Here is a super quick PHP script that does this for N fields (thanks for the idea #alex):
$sql = "SHOW COLUMNS
FROM table";
$results = mysqli_query($dbcon,$sql);
while($column = mysqli_fetch_assoc($results))
{
$column = $column["Field"];
$sql = "UPDATE table
SET $column = LOWER($column)";
$success = mysqli_query($dbcon,$sql);
}