I want to set an image as a cover for the album and i do it by choosing it from a radio input that is in a do-while loop. I have put in images table a field named is_cover that takes 1 if the image is set as cover ,or 0 if not.
<input type="radio" name="cover" value="<?php echo $row_images['image_id']; ?>" <?php if($row_images['is_cover'] == 1){ echo "checked=\"checked\""; } ?> />
My question is how can i perform an update query that sets all images is_cover field to 0 and only the image selected gets the value 1.
What i'm trying to say is how can i achieve this:
$is_cover = $_POST['cover'];
$query = "
UPDATE images
SET is_cover = 1
WHERE image_id = {$is_cover}
AND SET is_cover = 0
WHERE image_id <> {$is_cover}
";
This should do the trick for you:
UPDATE images SET is_cover = CASE WHEN image_id = {$is_cover} THEN 1 ELSE 0 END;
From my test:
mysql> select * from first;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
| 4 | NULL |
| 6 | ffff |
+------+-------+
5 rows in set (0.01 sec)
mysql> update first set title = case when id > 4 then 'gggg' else title end;
Query OK, 1 row affected (0.01 sec)
Rows matched: 5 Changed: 1 Warnings: 0
mysql> select * from first;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
| 4 | NULL |
| 6 | gggg |
+------+-------+
5 rows in set (0.00 sec)
You can run 2 Queries here one to set them all to 0 and then setting the one you selected to 1
Execute these 2 queries:
$query = "UPDATE images SET is_cover = 0 WHERE image_id <> {$is_cover}";
$query = "UPDATE images SET is_cover = 1 WHERE image_id = {$is_cover}";
The first query sets all is_cover to zero. The second query sets is_cover to 1 for the selected image.
Related
Consider I have array of IDs:
1
2
3
4
5
6
7
8
Let's say I can fetch an array starting with an ID of specific number, let's say 5.
mysql_query("SELECT * FROM farmlist WHERE id > 4 ORDER BY id")
it should give me array of form:
5
6
7
8
Question: Is there a way after reaching the last ID, it would add to array the IDs from the smallest until the ID of where we start, so that we have:
5
6
7
8
1 <~ Add
2 <~ Add
3 <~ Add
4 <~ Add
Try this query:
mysql_query("SELECT * FROM farmlist WHERE id > 4 UNION ALL SELECT * FROM farmlist WHERE id <= 4");
select id from farmlist
order by
(select if( id > 4, id - 4, id + (select max(id) + 1 from farmlist)))
pseudo-code:
res1 = mysql_query("SELECT * FROM farmlist WHERE id > 4 ORDER BY id");
res2 = mysql_query("SELECT * FROM farmlist WHERE id <= 4 ORDER BY id");
array_merge(res1, res2);
and the final res would be in res1
Consider this:
$ids = array(1,2,3,4,5,6,7,8);
$arr = array(5,6,7,8);
sort($ids);
sort($arr);
$min = $arr[0];
foreach($ids as $id){
if($id>=$min) break;
$arr[]=$i;
}
//array will now be (5,6,7,8,1,2,3,4)
That what you wanted?
With mysql this could be done as
mysql> create table test (id int);
Query OK, 0 rows affected (0.10 sec)
mysql> insert into test values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
Query OK, 10 rows affected (0.03 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql> select * from test order by case when id >=5 then 0 else 1 end , id ;
+------+
| id |
+------+
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
| 1 |
| 2 |
| 3 |
| 4 |
+------+
The above query could be even expanded in a range, lets say I want data from 5 till 7 on the top and rest all after that and this could be done as
mysql> select * from test order by case when id >=5 and id<8 then 0 else 1 end , id ;
+------+
| id |
+------+
| 5 |
| 6 |
| 7 |
| 1 |
| 2 |
| 3 |
| 4 |
| 8 |
| 9 |
| 10 |
+------+
I need to find the most common value (not 0) from arrays.
My code:
include ("db.php");
$query = "SELECT poll1 FROM names";
$res = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($res)) {
echo $row['poll1'];
}
And echo results (minimum value 0 (default) and maximum 3):
1
1
0
0
0
2
3
The most common value is "1". I cant use array_count_values, because there are 7 arrays of numbers.
This is a problem you should solve with SQL.
Firstly, you want to get the number of people selecting each option:
SELECT poll1, COUNT(*) AS count FROM names GROUP BY poll1;
+-------+-------+
| poll1 | count |
+-------+-------+
| 0 | 3 |
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
+-------+-------+
4 rows in set (0.00 sec)
Ok, but you're not interested in zeros, and you only care about the row with the largest value of count so you should sort by descending count, and limit it to 1 result:
SELECT poll1, count(*) AS count FROM names
WHERE poll1 != 0
GROUP BY poll1
ORDER BY count DESC
LIMIT 1;
+-------+-------+
| poll1 | count |
+-------+-------+
| 1 | 2 |
+-------+-------+
1 row in set (0.00 sec)
I have a table of 16K entries
I want to extract random 44 entries
but I don't want to repeat the same entries more then once (ever)
so i have a per-user list that keeps the already used 'IDs' as a comma-separated string in a table.
and I use that list to SELECT ... NOT IN (used_IDs)
The issue is that this list is getting too big and the sql call fails because of size i believe
Any idea on how to do that more usefully?
Questions table:
+------+-------+-------+
| id | Qtext | Tags |
+------+-------+-------+
Test table:
+------+-------+
| id | QIDs |
+------+-------+
Results table:
+------+-------+-------+
| id | tID | uID |
+------+-------+-------+
I need to select unique random values from Questions table based on the results table. (which associates test ID with Question IDs)
Currently trying to use:
SELECT DISTINCT `questions`.`ID`
FROM `questions`, `tests`, `results`
WHERE
`questions`.`ID` NOT IN (`tests`.`qIDs`)
AND `results`.`uID` = 1 AND `tests`.`ID` = `results`.`tID`
AND 4 IN ( `questions`.`tags`)
AND "http://www.usmlestep2qna.com" = `provider`
ORDER BY RAND() LIMIT 27;
Any ideas?
Instead of placing the used user Id values in a comma-separated string in one column, you could create a tall table to store them. This should yield better preformance
Rather than using a single row with a (potentially huge) CSV, why not use a nicely indexed table and an outer join to pick unmatched records. I have an example from my test database:
mysql> select * from first;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
| 4 | NULL |
| 6 | gggg |
+------+-------+
5 rows in set (0.00 sec)
mysql> select * from second;
+------+----------+------+------+-------+------+
| id | first_id | one | two | three | four |
+------+----------+------+------+-------+------+
| 1 | 1 | 3 | 0 | 4 | 6 |
| 1 | 2 | 4 | 4 | 1 | 2 |
| 3 | 3 | 1 | NULL | 3 | 4 |
+------+----------+------+------+-------+------+
3 rows in set (0.00 sec)
mysql> select a.id from first a join second b on a.id=b.first_id;
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
+------+
3 rows in set (0.00 sec)
mysql> select a.id from first a
left outer join second b on a.id=b.first_id where b.first_id is null;
+------+
| id |
+------+
| 4 |
| 6 |
+------+
2 rows in set (0.00 sec)
This should improve your performance rather nicely.
I'm doing a work for a client but since I haven't been using PHP/MySQL for a while I forgot some simple things, hope you can help me out.
I have the following SQL table:
ID (non-null, autoincrement) | credit (int)
My query should put the whole "credit" column to 0 except for the row that has the higher ID.
So I would do:
UPDATE $table SET credit = 0 WHERE... ?
Thanks in advance for any help :)
UPDATE $table SET credit = 0 WHERE ID > $ID
Will update any rows that have and ID greater than the variable $ID
If you only want to update the row with the maximum ID then use:
UPDATE $table SET credit = 0 WHERE ID = (select max(id) from $table)
Edit: As Eggyal correctly points out MySQL doesn't like a subquery on the same table as an update - but you can get around it nicely:
UPDATE $table
SET credit = 0
WHERE
credit='$credit'
AND statid='$statid'
AND userid='$userid'
AND ID = (select ID from (SELECT MAX(ID)as ID from $table) a)
And examples from my console:
mysql> select * from first;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
| 4 | NULL |
| 6 | eeee |
+------+-------+
5 rows in set (0.00 sec)
mysql> update first set title='ffff' where id=(select max(id) from first);
ERROR 1093 (HY000): You can't specify target table 'first' for update in FROM clause
mysql> update first set title='ffff' where id=(select ID from (select max(id) as ID from first) a);
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from first;
+------+-------+
| id | title |
+------+-------+
| 1 | aaaa |
| 2 | bbbb |
| 3 | cccc |
| 4 | NULL |
| 6 | ffff |
+------+-------+
5 rows in set (0.00 sec)
Note: As the subquery within a subquery trick unlocks the original table, it is a good idea to run this within a transaction - if the table is unlocked from a query, it might have changed by the time it is updated - so it will be a good idea to use this type of query within a transaction.
Hi I have a MySQL database table "points" the user can click a button and a point should be removed from their account, the button they pressed has an ID of another user, therefore their account must increase by one.
I have it working in jQuery and checked the varibles/posts in Firebug, and it does send the correct data, such as:
userid= 1
posterid = 4
I think the problem is with my PHP page:
<?php
include ('../functions.php');
$userid=mysql_real_escape_string($_POST['user_id']);
$posterid=mysql_real_escape_string($_POST['poster_id']);
if (loggedin())
{
include ('../connection.php');
$query1 = "UPDATE `points` SET `points` = `points` - 1 WHERE `userID` = '$userid'";
$result1=mysql_query($query1);
$query2 = "UPDATE `points` SET `points` = `points` + 1 WHERE `userID` = '$posterid'";
$result2=mysql_query($query2);
if ($result1 && result2)
{
echo "Successful";
return 1;
}
else
{
echo mysql_error();
return 0;
}
}
?>
Any ideas? Thanks :)
Two queries to increase/decrease field value are not necessary:
UPDATE table SET field = field + 1 WHERE id = 1
is a perfectly valid query as you can see next:
mysql> describe points;
+--------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+---------+------+-----+---------+-------+
| uid | int(11) | NO | PRI | NULL | |
| points | int(11) | YES | | 0 | |
+--------+---------+------+-----+---------+-------+
2 rows in set (0.05 sec)
mysql> insert into points VALUES (1,0),(2,0);
Query OK, 2 rows affected (0.14 sec)
mysql> select * from points;
+-----+--------+
| uid | points |
+-----+--------+
| 1 | 0 |
| 2 | 0 |
+-----+--------+
2 rows in set (0.05 sec)
mysql> update points set points = points+1 where uid = 1;
Query OK, 1 row affected (0.27 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from points;
+-----+--------+
| uid | points |
+-----+--------+
| 1 | 1 |
| 2 | 0 |
+-----+--------+
2 rows in set (0.00 sec)
Having that tested, are you sure you get into your if (loggedin()) clause?
I have to agree with KM, would be nice to see output of echo $query1; or echo $query2;
Here is the example query, tested by me and it is working 100%
$query="UPDATE table_name SET `hit_count`=(`hit_count`+1) WHERE `id` = '1'";
update table_name set col_name=col_name+1 where sqId = 12
But if your col_name by default value is null or empty it never works, so make sure that col_name default value is 0 or any integer value.
update 'tablename' set 'columnname1'='columnname1' + 1 where 'columnname2'='value';
eg: update students set englishmarks=englishmarks + 1 where name='Rahul';
Edit:(Explanation)
"UPDATE" keyword is used to update a vaule in the table. Here I am updating a value in the table "students". "SET" keyword updating the english marks by 1(just like in C language, how we increase the value of an integer, i=i+1) and condidtion is given where name is "Rahul".
So englishmarks of Rahul are incremented by 1
In laravel Migration do:
\DB::statement('SELECT #pos:=0;');
\DB::statement('UPDATE users SET company_id = ( SELECT #pos := #pos + 1 ) WHERE `id` = '1';');
If want to change all records, remove the WHERE id = '1'
It will insert number increment to your records like:
+-----+------------+
| id | company_id |
+-----+------------+
| 1 | 1 |
| 12 | 2 |
| 23 | 3 |
+-----+------------+