The best way to select rows from several tables? - php

I am creating a php app and am now creating the DB interface code. In my APP their are three tables, user, network, user_network. They have the following columsn:
user<-------------------->user_network<-------------------->network
user_ID un_ID network_ID
user_Name un_Member network_Name
un_Network network_Description
I have created the following query which querys the user_network table and returns the ID's of all networks which the user is a member of:
$STH = $DBH->query("SELECT * FROM user_network WHERE nm_Member ='$userID'");
I then pull the network_ID's from this array using the following code:
$DB_NetworkID = array();
foreach($STH as $row)
{
$DB_NetworkID[$counter] = $row['nm_networkID'];
$counter++;
}
print_r($DB_NetworkID);
The array now holds of all the network IDs that the user is a member of, like so
Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 ) //network IDs = 1, 3, 5, 7
I would now like to pull rows from the networks tables, how do i go about about SELECTing rows from the networks database WHERE the ID is contained in the array?
Thanks for any help.

You should use a JOIN instead and make it a single query:
SELECT
*
FROM
user
INNER JOIN
user_network
ON
user.user_ID = user_network.un_ID
INNER JOIN
network
ON
user_network.un_Network = network.network_ID
WHERE
user_ID = '$userID'
That query will give you all networks that a user is member of.

If your problem is the comparison against an array, then an easy workaround is using FIND_IN_SET() like this:
$list = implode(",", $DB_NetworkID); // turns it into "1,3,5,7"
... "SELECT * FROM foo WHERE FIND_IN_SET(network_ID, '$list')";
For better performance you should construct an .. IN (?,?,..) clause however.

Of course using JOIN as "halfdan" said, is the best way.
But I gonna answer your question:
If your array is like this:
$un = Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 7 ) //network IDs = 1, 3, 5, 7
You can use a Foreach like this:
Foreach($un as $key => $value) {
and your query will be like this:
SELECT * FROM network WHERE network_ID ='$value'

Related

PHP SQL - Search for match with same players

Good mornin'.
I've been tryin to make "something" that will compare matchup percentage but i'm stuck'd at searching for matches with 2 same players.
I've found something about AND OR parenthesis so here is my sql query
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' OR playerName01 ='".$player2."') AND (playerName02 = '".$player2."' OR playerName02='".$player1."')";
$result3 = $db->query($ccc);
$ids = array();
while ($row55 = $result3->fetch_assoc())
{
$ids[] = $row55['winner'];
}
But , the problem is whenever i try to get data , it gives me more indexes than actualy expected.
This is the result of printing array values after fetching.
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )
As expected is only 2 3 4 as u can see in the DB sample here.
db sample
Anyone suggestions on what i'm doing wrong?
A simple way to write this in MySQL uses tuples:
where (?, ?) in ( (playername01, playername02), (playername02, playername01) )
The ? are for parameters. That should be the way that you pass values into queries.
You are doing wrong while using AND OR in where clause
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' AND playerName02 ='".$player2."') OR (playerName01 = '".$player2."' AND playerName02='".$player1."')";
Try this #Patrik Dano

How do I convert a one to many relationship to a flat array using mysql and php

How can I format a one to many relationship to one 'row' using mysql or php?
Main Table
movie_id name
1 Portland
2 Blazers
Many Table
movie_id actor
1 Brandon
2 Greg
Below is the psudo code I have mapped out. Not sure if there is any thing native to PHP or MYSQl that would be more efficient before I continue. I'm thinking I have two queries. One with the movie information. One with the actor information. Once they are arrays I will loop through to get a single record for each movie with the actors.
movieInfo = = []
actorInfo = = []
Foreach(movieActorId)
If(actorId = movieActorId)
arrayPush(movieInfo[actorArray],actorInfo[name]);
The final array would look like this
movieInfo = array('movie_id' => '1',
'movie_name' => 'porland',
'actor' => array(Brandon,Greg)
);
Maybe this is what you need:
SELECT m.movie_id, m.name AS movie_name, GROUP_CONCAT(a.actor SEPARATOR ',') AS actor
FROM movies m
JOIN actors a ON m.movie_id = a.movie_id
GROUP BY m.movie_id;
// Run query
$movieInfo = array();
while ($array = mysqli_fetch_assoc($result)) {
$array['actor'] = explode(',', $array['actor']);
$movieInfo[] = $array;
}

MySql NOT IN many values from the mysql fetched result

I have 2 MySql queries which are interdependent.
My 'table1'
----------
id
----------
1
2
3
4
5
6
7
My First query
$sql1 = "SELECT * FROM table1 WHERE";// some condition which gives me id's 1,2,3
$res1=$obj->_executeQuery($sql1);
$res1=$obj->getAll($res1);
The result of this is giving me array
Array
(
[0] => Array
(
[id] => 1
..
..
)
[1] => Array
(
[id] => 2
..
..
)
[2] => Array
(
[id] => 3
..
..
)
)
I want to run another query on same 'table1', where not equal to list of ID's which i am getting from the first query.
My Second Query
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (" . implode(',', $res1) . ")";
This is not showing me only one id i,e first. In above case i should get id's 4,5,6,7
Since implode will not give the desired value on multidimensional array so first you need to get the array of all id's to form one-dimensional array then use implode on the array of id's:
$id=array();
foreach ($res1 as $key=>$inner_array){
$id[]= $inner_array['id'];
}
you can use array_walk also here like this:
array_walk($res1,function($c) use (&$id) {$id[] = $c['id'];});
but i think the best one is array_map :
$id = array_map(function($i) {
return $i['id'];
}, $res1);
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (" . implode(',', $id) . ")";
Note: when ever you are doing select please specify your column if you need few to select,unnecessarily selecting all will slow your sql processing.
suppose here:SELECT * FROM table1 WHERE, if you need only id then please select id only.
You have to change $res1, which is a two-dimensional array, into a one-dimensional array of IDs to be able to use implode:
$ids_from_first_query = array();
foreach($res1 as $result_row) {
$ids_from_first_query[] = $result_row['id'];
}
$ids_as_string = implode(',', $ids_from_first_query);
$sql2 = 'SELECT * FROM table1 WHERE id NOT IN(' . $ids_as_string . ')';
In the above code, $ids_as_string will look like this:
1,2,3
Thus it can be used in your MySQL query
Here you are getting two dimensional array so that's reason it is not working
while($each=mysql_fetch_array($res1))
{
$array[]=$each[id];
}
$imp=implode(",",$array);
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (".$imp.")";
Try this it will works

SQL: can I JOIN 2 tables according the first table "array" value?

Im trying to find a better way to return 2 tables at once.
My first table is:
[ID] [area]
1 13,12,15
6 18,17,13
and the second table is:
[areaname] [singlearea]
textOf12 12
textOf18 18
textOf15 15
Now, I need to return for each [ID] hits area names, for example:
For the ID: 1, I need the following array: (textOf12,textOf15)
and for the ID 6 I need: (textOf18) only.
This is what i have for now (I don't think its a nice code):
$getall = "SELECT * FROM table1";
$resultfull = mysql_query($getall);
while ($res = mysql_fetch_assoc($resultfull))
{
$uarray = array();
$sqlarea = explode(",", $res['area']);
foreach($sqlarea as $userarea)
{
$areaarray = runquery("SELECT areaname From table2 WHERE singlearea = '".$userarea."'");
$value = mysql_fetch_object($areaarray);
array_push($uarray,$value->areaname);
}
var_dump($uarray);
any suggestions?
Thank you very much!
Comma separated ID list and ID value pretty good matching using like:
select t1.id, t2.areaname
from table1 t1, table2 t2
where concat(',', t1.area, ',') like concat('%,', t2.singlearea, ',%')
However It's recommended to use additional link table!

Is using PHP to loop a mySQL query efficient?

I have a HTML table full of check-boxes on page 1 with the name attribute set like this:
input type="checkbox" name="A_1"
input type="checkbox" name="B_2"
On the following page, I loop through my $_POST array in PHP with explode to make an array like this:
Array ( [A_1] => on [A_2] => on [B_2] => on [B_5] => on [C_5] => on [submit] => Submit )
Into two arrays:
row_Array = Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 5 [4] => 5 )
column_Array = Array ( [0] => A [1] => A [2] => B [3] => B [4] => C )
This is my SQL query:
for($i=0; $i < count($column_array); $i++) {
$sql = "SELECT {$column_array[$i]} FROM table WHERE num IN ({$row_array[$i]})";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_assoc($result)) {
$result_array[] = $data[$column_array[$i]];
}
}
Here is an example of my SQL table:
A B C
1 cat cot cet
2 rat rot ret
3 hat hot het
4 lat lot let
5 bat bot bet
The individual SQL queries from my loop look like this and return the correct values:
SELECT A FROM table WHERE num IN (1) returns cat
SELECT A FROM table WHERE num IN (2) returns rat
SELECT B FROM table WHERE num IN (2) returns rot
SELECT B FROM table WHERE num IN (5) returns bot
SELECT C FROM table WHERE num IN (5) returns bet
I am quite new to sql and php. This works but it seems like a terrible way to do this. Any advice or help would be greatly appreciated.
I believe it's a better practice to run a single query and loop through the data returned rather than looping and then running multiple queries.
However, depending on your data structure and application layout, UI, etc, that may not be possible.
I would aim for something like SELECT A,B,C,num FROM table WHERE num IN (1,2,5)
then maybe
foreach($result as $r){
$data[$r['num']] = $r;
}
Let's try just running one query and loop trough it. It's pretty much #Andy Gee 's answer expressed in code.
$cols = implode(',', array_unique($column_array));
$rows = implode(',', array_unique($row_array));
$sql = "SELECT {$cols} FROM table WHERE num IN ({$rows})";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_assoc($result)) {
//Do your stuff here
}
Something like, it's realy bad idea but..:
$columns = implode(', ', $column_array);
$num_values = implode(', ', $row_array);
$sql = "SELECT {$columns}, num FROM table WHERE num IN ({$num_values})";
$result = mysqli_query($connection, $sql);
while ($data = mysqli_fetch_assoc($result)) {
$result_array[] = $data[$column_array[$i]];
}
Other way is to build one long Query with UNION
SELECT A as value, num FROM table WHERE num = 1
UNION
SELECT A as value, num FROM table WHERE num = 2
UNION
SELECT B as value, num FROM table WHERE num = 2
UNION
SELECT B as value, num FROM table WHERE num = 5
UNION
SELECT C as value, num FROM table WHERE num = 5
returns:
array(
array("num" => 1, "value" => 'cat'),
array("num" => 1, "value" => 'rat'),
...
);

Categories