PHP MySQL Query with NOT LIKE specific id - php

I have 2 tables. The first one is messages and the second is room. msg_id from messages table is the same as id from room table. What I'm doing is selecting all msg_id and for each of them I wanna run a query that deletes all rooms that their ids dont match with msg_id:
My code:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
while($row = mysql_fetch_array( $result )) {
$me = $row[0]; //$me as a string
$int = (int)$me;//transform $me's value to int
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%" . $int . "%'");}
The $result2 query will delete all entries from room table, no matter the value of $int variable. That means that the check is not working. If I change the $result2 to this i.e.:
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%86%'");
all entries will be Deleted except the room entry with id = 86 (it works fine)
The basic plan is that I must keep all room entries that match their id with msg_id .

DELETE FROM `room` WHERE `id` NOT IN (SELECT `msg_id` FROM `messages`)
if you can't use subquery you can try:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
$ids = [];
while($row = mysql_fetch_array($result)) {
$ids[] = (int) $row[0];
}
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT IN (" . implode(',', $ids) . "));
and PLS don't USE mysql_query it is DEPRECATED

Could you use a subquery?
DELETE FROM ROOM WHERE id not in(SELECT msg_id FROM messages);

Try this query,
delete from 'room' where 'id' not in(select 'msg_id' from 'messages');
if it don't work for you, you can try NOT EQUAL TO query
delete from 'room' where 'id' <>(select 'msg_id' from 'messages');

Related

How select random column value from Mysql database using PHP

I'm trying to fetch random column from database using Rand() function.
It's returning random value but many time it is returning duplicate.
This is what my database table look like.
Column
Type
Null
Default
no
int(30)
No
postid
varchar(100)
Yes
NULL
byuser
varchar(32)
Yes
NULL
likeslimit
int(30)
No
createdon
date
No
And this is what my PHP code is.
$query = mysqli_query(
$mysql,
"SELECT postid FROM history ORDER BY Rand() LIMIT 1"
);
if (mysqli_num_rows($query) == 1) {
while ($row = mysqli_fetch_assoc($query)) {
echo $row['postid'];
}
}
I want it to always return random never the same till the end of data reached.
Don't use loop and condition you want only 1 limit try this
$query = mysqli_query(
$mysql,
"SELECT postid FROM history ORDER BY Rand() LIMIT 1"
);
$row = mysqli_fetch_assoc($query)
echo $row['postid'];
This is the way RAND in mysql works and will repeat the results from time to time. But you can achieve such functionality by using mysql with php.
$query = mysqli_query($mysql, "SELECT postid FROM cacheTable WHERE 1 ORDER BY RAND() LIMIT 1");
$row = mysqli_fetch_assoc($query);
$foundId = (int)$row['postid'];
if((int) $foundId === 0) { // NO records left in cacheTable then fill it up again
mysqli_query($mysql, "INSERT INTO cacheTable (postid) SELECT postid FROM history");
$query = mysqli_query($mysql, "SELECT postid FROM cacheTable WHERE 1 ORDER BY RAND() LIMIT 1");
$row = mysqli_fetch_assoc($query);
$foundId = (int) $row['postid'];
}
mysqli_query($mysql, "DELETE FROM cacheTable WHERE postid=".$foundId); // DELETE the record
$query = mysqli_query($mysql, "SELECT * FROM history WHERE postid=".$foundId);
$result = mysqli_fetch_assoc($query);
cacheTable will have only one column - ID (primary key) which will hold the corresponding ID (primary key) from history. cacheTable structure:
|------
|Column|Type|Null|Default
|------
|postid|varchar(100)|Yes|NULL
|-----
cacheTable will fill with all the ids from history table (it will be done once the cacheTable is empty). You will select rand result from the cacheTable and you will delete it then so it will not appear in the next selects. When we are out of records in cache table it will populate again.
NB: this approach has one major drawback - when you have new entries in history table they won't be available in cache table until it is empty and filled again.
This is the code Samir Nabil Suggested :
session_start();
$_SESSION['dupes'] = array();
$query = mysqli_query(
$mysql,
"SELECT postid FROM history ORDER BY Rand() LIMIT 1"
);
if (mysqli_num_rows($query) == 1) {
while ($row = mysqli_fetch_assoc($query)) {
if (!in_array($row['postid'], $_SESSION['dupes'])) {
echo $row['postid'];
$_SESSION['dupes'][] = $row['postid'];
}
}
}

Make an array from a select with multiple rows

I'm trying my best here to find a solution for my issue, but with no luck.
I have a SELECT in my PHP to retrieve some products information like their IDs.
mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
Every time I run this SELECT, I get 5 rows as result. After that I need to run a DELETE to kill those 5 rows using their id_item in my WHERE condition. When I run, manually, something like:
DELETE FROM mytable WHERE id_item IN (1,2,3,4,5);
It works! But my issue is that I don't know how to make an array in PHP to return (1,2,3,4,5) as this kind of array from my SELECT up there, because those 2 other conditions may vary and I have more "status = 0" in my db that can't be killed together. How am I suppose to do so? Please, I appreciate any help.
Unless there is more going on than what is shown, you should never have to select just to determine what to delete. Just form the DELETE query WHERE condition as you would in the SELECT:
DELETE FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'
But to answer how to get the IDs:
$result = mysqli_query($link, "SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
while($row = mysqli_fetch_assoc($result)) {
$ids[] = $row['id_item'];
}
$ids = implode(',', $ids);
Move to PDO or MySQLi now.
First of all you shouldn't be using mysql_query anymore as the function is deprecated - see php.net
If this is a legacy application and you MUST use mysql_query you'll need to loop through the resource that's returned by mysql_query, which should look something like this
$result = mysql_query("SELECT id_item FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$idArray = array();
while ($row = mysql_fetch_assoc($result)) {
$idArray[] = $row['id_item'];
}
if(count($idArray) > 0) {
mysql_query("DELETE FROM mytable WHERE id_item IN (" . implode(',' $idArray) . ")");
}
As said before, probably you don't even need a select. But you can do a select, grouping all ids together, and then put it in the delete IN.
$result = mysql_query("SELECT GROUP_CONCAT(DISTINCT id_item) AS ids FROM mytable WHERE status = '0' AND cond1 = '1' AND cond2 = '1'");
$ids = mysql_result( $result , 0, 'ids') ; // 1,2,3,4,5
if ($ids != ""){
mysql_query("DELETE FROM mytable WHERE id_item IN (" . $ids . ")");
}
GROUP_CONCAT

PHP - how to select from a table one query

I got a table that contains ID, Names, message, and time, I want to select from the table only one message query from each ID, Currently I select all the messages, this is my code
$query= mysql_query("SELECT * FROM `table` ORDER BY `time`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo '</br>';
echo $msg;
}
That Shows all messages ordered by time, Is there is a way to select only one message query from each ID?
Thanks,
Klaus
If you want only one message you can use LIMIT like this
SELECT * FROM table ORDER BY time LIMIT 1
Or if you want only one message from some id then you can use GROUP BY
SELECT * FROM table ORDER BY time GROUP BY id
Sure, pretty straightforward
This will fetch all messages given ID:
$id = 10 //Get your id in any way you need
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr['message'];
echo $msg;
}
and this will fetch only the first message given ID
$id = 10
$query= mysql_query("SELECT `message` FROM `table` WHERE `ID` = $id LIMIT 1")or die(mysql_error());
$row = mysql_fetch_array($query));
if($row){
$msg = $row['message'];
echo $msg;
}else{
echo 'no messages for id '.$id;
}

Fetching a random row from MySQL and displaying it with PHP

im trying to select the row quote and author from my table and echo it
my goal is to create a random quote generator and display the actual quote and author.
I have entered 25 quotes in my table with 3 rows (ID, quote, author)
my code is the following and i keep getting the resource id #9 error
<?php
mysql_select_db(name of database);
$quotes = "SELECT author AND quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1";
$result = mysql_query($quotes);
WHILE ($row = mysql_fetch_array($result)):
ENDWHILE;
echo "$result";
?>
please help
First of all, I think you want
<?php
mysql_select_db(name of database);
$quotes = "SELECT author,quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1";
$result = mysql_query($quotes);
WHILE ($row = mysql_fetch_array($result)):
ENDWHILE;
echo "$result";
?>
but I have an additional suggestion
Preload all the quote IDs
CREATE TABLE quoteID
(
ndx int not null auto_increment,
id int not null,
PRIMARY KEY (ndx)
);
INSERT INTO quoteID (id) SELECT id FROM inspirational_quotes;
Now choose based on the id from quoteID table
SELECT B.author,B.quote FROM quoteID A INNER JOIN inspirational_quotes B
USING (id) WHERE A.ndx = (SELECT CEILING(MAX(ndx) * RAND()) FROM quoteID);
This should scale just fine because the return value for #rnd_id comes from a list of ids with no gaps in the quoteID table.
<?php
mysql_select_db(name of database);
$quotes = "SELECT B.author,B.quote FROM quoteID A INNER JOIN "
. "inspirational_quotes B USING (id) "
. "WHERE A.ndx = (SELECT CEILING(MAX(ndx) * RAND()) FROM quoteID)";
$result = mysql_query($quotes);
$row = mysql_fetch_array($result);
echo "$result";
?>
Give it a Try !!!
You cant echo $result as a string
do
WHILE ($row = mysql_fetch_array($result)):
echo $row['author'] . " " . $row['quote'];
ENDWHILE;
?>
You are not echoing the right variable.
echo $row['author'] . ": " . $row['quote'];
Why AND just comma.
SELECT author, quote FROM inspirational_quotes ORDER BY RAND() LIMIT 1
MySQL Select syntax
I suggest you to randomize results by PHP to improve performance. eg.:
$r = mysql_query("SELECT count(*) FROM inspirational_quotes");
$d = mysql_fetch_row($r);
$rand = mt_rand(0,$d[0] - 1);
$r = mysql_query("SELECT author,quote FROM inspirational_quotes LIMIT $rand, 1");

MySQL output CSV and update from CSV

I have a query below where I select a single ID from my database, then update a field for that ID with a 1 to indicate that this record has been processed. I now need to perform the same process but select 50 ID's and output them in CSV format, and again update each record with a 1 to indicate that these records have been processed. Any help is appreciated, I'm not sure on the most efficient method to do this.
$result = mysql_query("SELECT `id` FROM `t_ids` WHERE `f_fetched` IS null LIMIT 1");
while($row = mysql_fetch_array($result))
$f_id = $row['id'];
mysql_query("UPDATE t_ids SET f_fetched = '1' WHERE id = '$f_id'");
You could use something like this
$result = mysql_query("SELECT `id` FROM `t_ids` WHERE `f_fetched` IS null LIMIT 50");
$processed_ids = array();
while($row = mysql_fetch_array($result))
{
//do whatever processing you need to with that id
//add the id to the $processed_ids array
$processed_ids[] = $row['id'];
}
$ids = implode(",", $processed_ids); //create a comma-delimited string of ids.
//update all rows in 1 query
mysql_query("UPDATE t_ids SET f_fetched = '1' WHERE id IN ($ids)");
why not just use:
mysql_query("UPDATE t_ids SET f_fetched = '1' WHERE `f_fetched` IS null");

Categories