I have an array of ids that are unique in the context of the table for each row. What I would like to do is to query the database and obtain ordered by date of insertion (it is already a field in the table) but only those tables which id is in the array
$query = SELECT this,andthis,andthis,andthis FROM table WHERE id=(inside array of ids)? ORDER BY date_of_insertion;
The result is to be fetch_assoc() and therefore obtaining a associative array. What I would really want would be something like this in the final array:
[1] id, this, andthis,andthis,andthis
[2] id, this, andthis,andthis,andthis
[3] ...
even if the table has other ids and rows that just weren't queried because they weren't in the specified array. Those that were queried should be ordered by time. Any ideas on how to achieve the best performance on this?
You can try this one:
// this is the array of ids
$array_of_ids = array();
// joins the ids in the array into a string, separating each id with a comma
$ids = implode(',', $array_of_ids);
$query = "SELECT this, andthis, andthis, andthis FROM table WHERE id IN (" . $ids . ") ORDER BY date_of_insertion";
Related
I have a table called users(user_id, name, surname). In my php code a get an array with values like that:
<?php
$array = array();
while($e = mysql_fetch_array($favorites)){
$like_users = $e['user'];
$array[]=$like_users;
}
$arstring = implode(' ',$array);
?>
I want to select surname and name from table users, that their user_id is equal to those numbers exists as values in $array. Any idea how to do this?
Try this query
$sql='select name,surname from user where user_id in(?,?.....?)'
The number of ? is equal to the length of the array.
Then use
$query=$con->prepare($sql);
$query->execute($array);
Then fetch the returned rows.
PS:Creating prepared statements with variable number of arguments have been asked before on SO and the method is same as I have described.
collect all user_ids from SQL Query in one Array, then compare this array with your existing array
<?php
$array = array();
while($e = mysql_fetch_array($favorites)){
// $e['user'] equal user_id
$array[$user_id]= $e['user'];
}
?>
we use $array[$user_id] to save each user_id to corresponding array index, then compare two array as you want
It seems that I have to edit my question again - these down votes are getting frustrating...
I have an array of ids and a table to check it with. This is the query I use:
SELECT COUNT(*) FROM orders WHERE order_id IN (...
When this number isn't equal to the number of ids in the array, I need to get those values from the array that I have, that do not exist in the table. Is there a more optimal way to do this than making some temporary table, and selecting from it?
EDIT: For all those suggesting inserting NOT in the first query - I do not need all the rows from my table that do not match the values in the array - I need the values from the ARRAY itself...
For example, I have an array of three ids - "1","2","3". In the table I have ids "2" and "3". I check the array with my query:
SELECT COUNT(*) FROM orders WHERE order_id IN (1,2,3)
I get the number 2 as a result of this query, and that doesn't match the number of ids I have in the array, which is 3. I need a query that will get the missing id from the array I submitted, in this case the id I need is "1"
I don't think there's a clean SQL-only solution, because there's no way to SELECT from an array. However, instead of using a temporary table, you could return all the IDs that are found in the table, and do the NOT on the PHP side.
So select the result of this into an array, $existing_orders:
SELECT order_id FROM orders WHERE order_id IN (...);
Then you have:
$all_orders = array(1, 2, 3); // IDs you're looking for
$existing_orders = array(2, 3); // IDs that were found in the table
$not_existing_orders = array_diff($all_orders, $existing_orders);
print_r($not_existing_orders); // Array( [0] => 1 )
OK THAT´S clear now:
Then you will have to make something like this:
select id from order where id IN ( your list )
create a second array with the found values
and then use php array function array_diff
select * from orders where order_id NOT in (...
My query is
SELECT *
FROM `wp_patient_bill`
WHERE `bill_code` !=''
AND `is_billed` = 'Y'
AND `charged` = 'N'
AND `id` IN (97,419,631,632,633,422,635,421,35,799,60,423)
And I want the record array will be sort according to my list i.e. ID
'97,419,631,632,633,422,635,421,35,799,60,423'
. I am using php. Please suggest me the optimize way to do it.
Here is another solution:
SELECT *
FROM `wp_patient_bill`
WHERE `bill_code` !=''
AND `is_billed` = 'Y'
AND `charged` = 'N'
AND `id` IN (97,419,631,632,633,422,635,421,35,799,60,423)
ORDER BY FIELD(`id`,97,419,631,632,633,422,635,421,35,799,60,423)
Reference: SQL order by sequence of IN values in query
Assuming your list of IDs is in an array
Run the query
Loop through the results, storing each row of results in an associative array keyed on the ID $data["{$row['id']}"] = $row;
Loop through your list of IDs, and use the ID to key into the associative array to get the data. This will be in the order of the IDs you want.
Add an "ORDER BY ID" statement at the end of the query.
I need to update an array into mysql table.
this is my array
[cat2] => Array
(
[0] => 34
[1] => 48
[2] => 49
[3] => 46
)
and I want my output as 34,48,49,46 to move into a table called shops and column called category. This is code I written, $shop['cat2'] contains the array i posted above. Please help me. This code is keep only 34 in all fields of column category
foreach ($shop['cat2'] as $k => $v) {
$query = "UPDATE shops SET categories2=$v";
mysql_query($query);
}
In order to apply each of these array elements to one row of your category column, you will need to first fetch the a unique id from the shops table, and loop over it, using that unique identifier value in the update query's WHERE clause:
We'll call mysql_fetch_assoc() inside the foreach() loop to pull one row per one array element. This assumes you have a column shops.id which is the unique identifier per shop.
// If `id` is not the unique id per shop, substitute the correct column
$rowids = mysql_query("SELECT id FROM shops ORDER BY id");
if ($rowids) {
// Loop over your array, and do one update per array elem
foreach ($cat2 as $cat) {
$row = mysql_fetch_assoc($rowids);
$id = row['id'];
// Your values are ints, so no need to quote and escape.
// If you do use other string values, be sure to mysql_real_escape_string() them and single-quote
$upd = mysql_query("UPDATE shops SET category = $cat WHERE id = $id");
// Report error on this iteration
if (!$upd) {
echo "error updating $id" . mysql_error();
}
}
}
else {
echo "Couldn't get row ids. " . mysql_error();
}
Look into the implode function: implode(",", $shop['cat2'])
You might also want to look into Foreign Keys. When using a foreign key you can use a join SQL statement to retrieve data from multiple columns. When storing the categories as one field, like in your example, this is not possible.
You would need a new table for that: ShopCategory with columns: ShopID and CategoryID, these columns would have a foreign key relation to your Shop and Category tables respectively.
As Michael Berkowski already pointed out in the comments, if you do not use a where clause, this SQL statement will update the Category for ALL your shops!
$query = "UPDATE shops SET categories2='".implode(",", $shop['cat2'])."' WHERE id=".$shop;
I currently have the following array,
Array (1)
0 => Array (5)
productid => 1
qty => 1
materialid => 12
and I have the following two queries which are
select name as productname, price from products where productid=1
and
select name from materials where materialid=12
I need to link these queries such that the array output is like this or similar:
Array (1)
0 => Array (5)
productid => 1
qty => 1
materialid => 12
productname => Toothbrush
price => £3.00
This is basically to output the content on to a basket page. Note that the queries can not be joined as there isn't any joins on the two tables.
Thanks
Run the first query, get the data as a keyed array. Run the second query, get the data as a keyed array as well. Then make a union of both arrays:
$data1 = query_data($sql1);
$data2 = query_data($sql2);
$result = array($data1 + $data2);
Will give you a result that is one array containing a single array with all values from $data1 and $data2. Duplicate keys in $data2 will not overwrite those from $data1. See Array Operators in the PHP Manual.
A similar function is array_merge() which does create one array out of two as well.
You could also query both tables at the same time:
select p.name as productname, m.name as materialname, p.price
from products p, materials m
where p.productid=1 and materialid=12
Where did you get the data to populate the initial array? Does it always have a single value (if so you could use a cartesian join on a single query to avoid making 2 trips to the database). Why are the relations between the tables of data not described in the database?
Splicing the values from the array into the query, either as literals or as bound parameters is trivial. What is the question here?
You can run query separately:
$res1 = mysql_query(Qry1);
$res2 = mysql_query(Qry2);
$data1 = mysql_fetch_array($res1);
$data2 = mysql_fetch_array($res2);
$res = array_merge_recursive($data1, $data2);