Make an array from a select with multiple rows - php

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

Related

PHP MySQL Query with NOT LIKE specific id

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');

How do I use the results of a SQL query in a subsequent query?

I want to use the result set of a query in the where statement of a subsequent query.
Running into a problem because the first query returns multiple results and I don't know how to convert these to a comma-separated string for use in an 'IN' () statement.
$Result1 = mysql_query ("
select id from Table1
where
upper('$Input') = Employee_number
")
or die(mysql_error());
$Result2 = mysql_query ("
Select * from table2 where ID in ($Result1)")
You can combine this into a single MySQL statement like this:
SELECT * FROM Table2 WHERE id IN
(SELECT id FROM Table1 where upper('$Input') = Employee_number);
But if you really want to do it like in your question, you will probably have to lookup how to work with the results from mysql_query, just look that up in a function reference.
$query1 = mysql_query("
select id from Table1
where upper('$Input') = Employee_number
") or die(mysql_error());
$ids = array();
while($Result1 = mysql_fetch_array($query1))
{
$ids[] = $Result1['id'];
}
if(sizeof($ids))
{
$n_ids = implode(',', $ids);
$query2 = mysql_query("
select * from Table2
where ID IN (" . $n_ids . ")
") or die(mysql_error());
}

Output mysql result as an array of the form (column name => possible values for column name)

I have database such as
I want to create an associative array such that each att_name value is associated with its possible values from att_value:
array('att_name' => array('att_value_1', 'att_value_2', 'att_value_3'))
What is the best way to achieve this?
While it is easily possible to do this simply by selecting the results you want and iterating them in PHP to create the data structure you want, you could sub some of the work out to MySQL with GROUP_CONCAT():
$query = "
SELECT att_name, GROUP_CONCAT(att_value SEPARATOR ',') AS values
FROM table_name
GROUP BY att_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']] = explode(',', $values);
}
print_r($array);
Of course, this only works if your values will never contain the character (or sequence of characters) you use for the SEPARATOR in the MySQL query, so the safer pure-PHP way would be:
$query = "
SELECT att_name, att_value
FROM table_name
";
$result = mysql_query($query);
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[$row['att_name']][] = $row['att_value'];
}
print_r($array);
Try below:
$sql = "SELECT * from tablename";
$result = mysql_query($sql,$con);
$final_array=array();
while ($row = mysql_fetch_object($result))
{
$final_array[$row->att_name][0]=$row->att_value_1;
$final_array[$row->att_name][1]=$row->att_value_2;
....
....
}
This way :
SELECT
item,
att_name,
GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value
FROM
table
GROUP BY
att_name
Will give you something like that :
item att_name att_value
-----------------------------
books height 150 mm<!>250 mm
books price rs:20<!>Rs:20
books size 15 pg<!>30 pg<!>60 pg
books width 300 mm<!>400 mm
You have to explode the result from att_value by a <!>. I use this <!> so it highly impossible to have a value inside att_value with this. If you think you would someday use this, take another separator. Example : [{--}], _SEPARATOR_, [_-CUT-_], etc. Something you are sure at 100% you won't use a choice but always as a separator to split the text.
So example :
$SQL = 'SELECT item, att_name, GROUP_CONCAT(att_value SEPARATOR "<!>") AS att_value FROM table GROUP BY att_name';
$Query = mysql_query($SQL) or die('MySQL Error : '.mysql_error());
while($Assoc = mysql_fetch_assoc($Query)){
$Assoc['att_value'] = ($Assoc['att_value'] != '' ? explode('<!>', $Assoc['att_value']) : NULL);
print_r($Assoc);
}

MySQL MyISAM race condition

The function has next structure:
$q = 'LOCK TABLES table1 WRITE;';
mysql_query($q);
$q = 'select id from table1 where is_delete = 0 limit 1;';
$res = mysql_fetch_assoc(mysql_query($q));
if($res) {
$q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
mysql_query($q);
}
$q = 'UNLOCK TABLES;';
mysql_query($q);
I locking all tables, but queries run parallel.
How fix this?
Check whether you're getting any MySQL errors on the LOCK TABLES query:
$q = 'LOCK TABLES table1 WRITE';
$r = mysql_query($q) or die(mysql_error());
However, if this is all you are doing, you can also simply write:
UPDATE `table1 SET `is_delete` = 1 WHERE `is_delete` = 0 LIMIT 1
which does not require any locks at all. Of course, this will only work if the data from your first query is not being processed in any way, and if it doesn't really matter which row you are updating, as long as it's one in which is_delete is set to 0. This is what the code you posted does, too, but it's not immediately obvious to me what you would want to use this code for :)
More generally, if you are using the default InnoDB storage engine for your MySQL table, you may want to look into SELECT ... FOR UPDATE:
http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
You could write:
$q = 'select id from table1 where is_delete = 0 limit 1 for update';
$res = mysql_fetch_assoc(mysql_query($q));
if($res) {
$q = 'UPDATE table1 SET is_delete = 1 WHERE id = '".$res['id']."'';
mysql_query($q);
}
See also: http://www.mysqlperformanceblog.com/2006/08/06/select-lock-in-share-mode-and-for-update/

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