Updating more than one row with a single query - php

I have a table called posts in my database with a column called has_read. I then have an array of post IDs like so:
$posts = array(1, 5, 29, 38, 50, 51, 52, 65, 79);
What I want to do is for all of those posts in the array, update their row to add the user ID to has_read. I can't use a foreach loop because it'll execute 9 queries, which I think is too much.

$updatestring = implode(",",$posts = array(1, 5, 29, 38, 50, 51, 52, 65, 79))
$sql = "UPDATE post SET has_read=1 WHERE userID IN($updatestring)";
Concat your array of id's to a comma separated string and just use the IN() function for a bulk update
Although actually thinking about it this is the completely wrong way of doing this. Since its a one thread to many users relationship you're better off having a normalised database for this and using a separate table to track reads based off userid and thread id.

You can use WHERE IN statment like this :
$result = mysql_query('UPDATE table SET field = value WHERE id IN ('.implode(',',$posts).')');

You can use IN.
$sql = "UPDATE posts
SET has_read = has_read + " . $user_id . "
WHERE id IN (" . implode(",", $posts) . ")";
Of course, you should not literally do it this way, but prepare a statement and pass the $user_id as a parameter, depending on the database library you are using.

use Where with IN
$result = mysql_query('UPDATE posts SET has_read= user_id
WHERE id IN ('.implode(',',$posts).')');

What about something like:
UPDATE posts_table SET has_read = 1 WHERE id IN (1, 5, 29, 38, 50, 51, 52, 65, 79);

Try this:
$query = 'UPDATE posts SET has_head = 1 WHERE id IN (' . implode(',', array_map('intval', $array)) . ');';

Related

Laravel joining tables in a database query with bind values question

I have a earnings column on my site, I need to display the entire amount of earnings using a query in the database, but there is a small problem.
The table bets_double has columns: game_id, sum, color, and userid. And in the table game_double I have a column number it means winning number and id. In controller i bind numbers to colors this way:
$red = [1, 2, 3, 4, 5, 6, 7];
$black = [8, 9, 10, 11, 12, 13, 14];
$zero = [0];
How can I make a request in Laravel so that from the table bets_double take value color and checked the value from the table game_double and the total amount of victories was displayed?
For example, if in bets_double write color red, and in game_double number from 1 to 7 as write in $red variable, then to display the total winning. How to do it?
An example request code, but I don’t know how to send the values of variables in this code:
$double_games_money = DB::table('bets_double')
->where('user_id', $this->user->id)
->whereExists(function ($query) {
$query
->selectRaw(1)
->from('game_double')
->whereRaw('game_double.id = bets_double.game_id')
->whereRaw('game_double.number = bets_double.color');
})

Record query results for use in further queries

I can't explain it properly but I have several different loop queries on a page (news website homepage) to select articles and want to "record" the ID of each article to exclude such ID's from further query results.
Select rand from database ... result = ID's 3, 99, 6
$selected = 3, 99, 6
Select rand from database WHERE ID != $selected ... result = ID 51
$selected = 3, 99, 6, 51
Select rand from database WHERE ID != $selected ... result = ID 4
I can't wrap my head around on how to "record" the already selected ID's incremential and then use it further down to prevent the same article to appear twice.
make an array where you add all result ids into, then explode that array for the next sql. something like this:
$selectedIds = array();
// make first query, get results in loop. im not writing the query execution here, just the loop after
while($row = mysqli_fetch_assoc($res)){
$selectedIds[] = $row['id'];
// do your other stuff here (single article generation)
}
// for further queries you can make the WHERE clause like this
$query = "SELECT rand FROM table WHERE ID not in (".explode(', ', $selectedIds).")";
// this will make the actual query look like this:
// SELECT rand FROM table WHERE ID not in (3, 99, 6)

How do I translate this raw SQL query in PHP ActiveRecord?

I'm trying to run this sql query as a php activerecord query:
delete from article_categories where
article_id = 10
and
category_id in (1,4,5,6,7)
This statement works fine when I run it from the mysql console.
I tried doing this from php activerecord:
$query["conditions"] = array('article_id = ? and category_id in (?)', 10, "1,4,5,6,7");
ArticleCategory::delete_all($query);
The problem is it is only deleting one record at a time.
I expect all the records that match
article_id == 3
and
category_id == 1 || category_id == 2 || ... || category_id == 5
to be deleted.
However only the first record with fields
article_id = 3, category_id = 1
gets deleted.
What am I typing wrong?
If you want to use "IN (?)" in your where clause, be sure to pass an array as the condition value. Otherwise it would just read IN ("1,2,3,4") in stead of IN (1,2,3,4) (note the double quotes in the former version!).
So, it would look something like this:
$article_id = 1;
$categories = array(1, 2, 3, 4);
ModelName::delete_all(array(
'conditions' => array('article_id = ? and category_id IN (?)', $article_id, $categories)
));
And if you just want to delete the current record, do:
$record->delete();
Be careful not to invoke ->save() afterward, because the record will be saved again.
I'm not really sure if the ID you're sending it to delete can be empty? The documentation shows this for "Massive Update or Delete".
Post::table()->delete(array('id' => array(5, 9, 26, 30));
So, translated in your situation that would be something like
ArticleCategory::delete(array(array('id' => array(1, 4, 5, 6, 7)),
'conditions'=> array('article_id = ?', 10),
));

PHP variable variables with mysql resultset

So I have a mysql table which has a id column (sid) that can be dynamically added to. Now I am doing a query to get count of all entries grouped into each of these sid's like so:
SELECT SUM(IF(sid = 71, 1, 0)) as count71,
SUM(IF(sid = 72, 1, 0)) as count72,
SUM(IF(sid = 75, 1, 0)) as count75,
SUM(IF(sid = 81, 1, 0)) as count85
FROM `table`
WHERE userid=44;
Note that all the SUM fields are created dynamically and I don't know what the actual sid's are. Now question is how do I loop through the resultset for each of the counts using PHP's variable variables? I've tried this but doesn't work.
$count_var = "rs['count71']"
$$count_var // holds number of entries where sid is 71;
Thanks!
May I suggest this instead:
select sid, count(*) from `table` where userid = 44 group by sid ;
You could do:
$count_var = "rs['count71']";
echo eval('return $'. $count_var . ';');
but of course #troelskn's answer is probably the best solution for what you want

Find an ID number in an SQL table that isn't listed in an array of numbers

I have a table that looks like the following;
id header
1 fruit
4 header_example
9 test
13 money
I then have an array that used to contain each of the id's, but I remove one. I now for example, have an array that looks like this:
array = [1, 9, 13]
How would I look at that array, and determine that the row with id=4 should be deleted?
Thanks!
On the MySQL side, you could just run this, using php to output the array contents into the IN clause:
DELETE FROM table WHERE id NOT IN ( <array contents> )
On the PHP side, you could generate the appropriate contents:
' . implode(', ', $arr) . '
$arr = array(1, 9, 11);
$query = 'DELETE FROM tbl WHERE id NOT IN (' . implode(', ', $arr) . ')';
mysql_query($query);
$sql = 'DELETE FROM table WHERE id not in ('.implode(',', $array).')';

Categories