Say, I have a mysql table with columns like:
f_name, l_name, score1, score2, score 3
Then I want to create a PHP Associatiove Array from a query to get something like:
$array = ('name1'=>65, 'name2'=>45, 'anothername'=>23);
the scores e.g 65 is obtained by adding score1, score2 and score3 and name is obtained from f_name and l_name.
First of all what format of array you have specified is single dimension associative array.
You can use the following query:
SELECT CONCAT(FNAME,' ',LNAME) AS NAMES,
SCORE1+SCORE2+SCORE3 AS SUMS FROM EXAMPLE WHERE UID=1;
This query will produce result with two columns - NAMES and SUMS which can then be used to create an associative array through php.
Related
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";
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 (...
I have the following query in PHP:
$titlematch = mysql_query("SELECT `item_id` FROM `items` WHERE `item_id` IN ($matches_s) AND MATCH (`eng_name`) AGAINST ('$query') IN NATURAL LANGUAGE MODE AS score;");
$titlematch2 = mysql_fetch_assoc($titlematch);
In plain words, I want to select the item_id from the table items where
the item_id value can be found within the array $matches_s, and
the string stored in eng_name can be found within the string $query
and then output a 2-dimensional array, where the second-level array contains the item_id and score (relevance) elements.
I have tried switching the order of which criteria comes first, or using brackets. Here are the results I get:
var_dump($titlematch); // returns bool(false)
var_dump($titlematch2); // returns NULL
Question is 'What am I doing wrong? Do I have to write this differently to other AND statements?
Let's say I have three values in PHP: "a", "b", "c". Doesn't matter whether in an array or comma separated string.
There is a table in database:
id | value
1 | a
2 | b
3 | d
My purpose is to find the values that are in php array but not in database table.
The given example will give "c".
Can I do it with only one query?
UPDATE
Received several good suggestions in answers about array_diff(), though in my case the DB table is really large and the array has not more than 5-6 items. So it would be better to perform 5-6 queries, I think.
If the PHP array is short, you can build a UNION ALL query to build your small table, then use NOT IN or LEFT JOIN query (whichever is faster) against the large table:
SELECT value
FROM (
SELECT 'a' AS value
UNION ALL
SELECT 'b'
UNION ALL
SELECT 'c'
) AS php_array_values
WHERE value NOT IN (
SELECT value
FROM that_large_table
);
Alternately, you can insert the php array values in a temporary table and use the IN or JOIN queries. Of course, this means you end up writing three extra queries:
CREATE TEMPORARY TABLE IF NOT EXISTS php_array_values (value VARCHAR(100));
DELETE FROM php_array_values;
INSERT INTO php_array_values VALUES ('a'), ('b'), ('c');
SELECT php_array_values.value
FROM php_array_values
LEFT JOIN that_large_table ON php_array_values.value = that_large_table.value
WHERE that_large_table.value IS NULL
how about this?
<?php
$a = array('a', 'b', 'c');
$values = implode("','", $a);
$sql = "SELECT DISTINCT `value` FROM `mytable` WHERE `value` IN ('$values')";
echo $sql;
perform the sql query. the result will be those 0 to 3 elements you already have. next, do an array_diff (which will not be heavy at all, since you'll have your initial small array, and the array of those in the db, which is even smaller).
$not_in_db = array_diff($a, $array_from_sql_result);
if what you have is a string with comma separated values, then you'll need to "explode" it first:
$s = "a,b,c";
$a = explode(",", $s);
You could select all the entries in the table and then perform an array_diff().
But this isn't one query, is one query and some post processing.
For this I would pull values from the table into an array and use array_diff
REF: http://www.php.net/manual/en/function.array-diff.php
Instead of pulling all the elements from the DB you can try using 'LIKE' statement, this will reduce the number of entries pulled from DB.
something like this :
PHP array values : a,b,c
DB values : a,b,d
select value from your_table_name where (value LIKE '%a%') OR (value LIKE '%b%') OR (value LIKE '%c%');
o/p of this will be : {a,b}
now use array_diff of php.
select max(*) as count from tablename
where field1 != $arr[0] && field2 != $arr[1] && field3 != $arr[2];
You can use and or or operators if you want. if the return count for this query is 0 then the array values are not exist in the database already.
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);