mysql fastest 2 table query - php

Situation: 2 tables, the first (Persons) storing person names and some other data, and the second (Phones) storing their phone numbers. There can be multiple phone numbers per person (thats why I am using separate tables in the first place).
Goal: Select everything so that in the end I'd have a php array like this:
array
(
'0' => array
(
'name' => 'John Smith'
// other values from table Persons...
'Phones' => array('0' => '12345', '1' => '324343') // from Phones table
),
'1' => array
(
'name' => 'Adam Smith'
// other values from table Persons...
'Phones' => array('0' => '645646', '1' => '304957389', '2' => '9435798') // from Phones table
)
);
ETC.
Phones.person_id = Persons.id
What would be the fastest way to do this? Fastest in a sense of program execution time, not the coding time. I could do simple JOIN but in this case I'd get many duplicate rows, i.e. for each phone I get all the data of the same person again and again in each row if you see what I mean. So I need to work on the array in PHP side. Maybe there's a better way?

One query. Check for typos:
$return = array();
$query = "SELECT pe.id, pe.name, ph.phone FROM Persons pe INNER JOIN phones ph ON pe.id = ph.person_id ";
$results = mysql_query($query);
if($results && mysql_num_rows($results)) {
while($row = mysql_fetch_assoc($results)) {
if(!$return[$row['id']]) {
$return[$row['id']] = array('name' => $row['name'], 'Phones' => array());
}
array_push($return[$row['id']]['Phones'], $row['phone']);
}
}
return $return;

Get the person first, and then query for each of the phone numbers.
$return = array();
$query = "SELECT `id`, `name` FROM `Persons`";
$person_results = mysql_query($query);
if($person_results && mysql_num_rows($person_results)) {
while($person_row = mysql_fetch_assoc($person_results)) {
$person = array();
$person['name'] = $person_row['name'];
$person['phone'] = array();
$query = "SELECT `number` FROM `Phones` WHERE `person_id` = '{$person_row['id']}'";
$phone_results = mysql_query($query);
if($phone_results && mysql_num_rows($phone_results)) {
while($phone_row = mysql_fetch_assoc($phone_results)) {
array_push($person['phone'], $phone_row['number']);
}
}
}
}
return $return;

Related

PHP & sqlsrv - create array from results, without knowing column names?

Using the below, I echo a JSON array of the results. But this requires that I identify the column names which I'd like to return from the SQL query:
$new_sql = "SELECT TOP 200 * FROM STracker ORDER BY [ID] DESC";
$check_statement = sqlsrv_query($conn, $new_sql);
$data = array();
while($row = sqlsrv_fetch_array($check_statement, SQLSRV_FETCH_ASSOC)) {
$data['data'][] = array(
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
);
}
Is there any way to create that array information, but return all of the columns returned by the query dynamically? So by using SELECT * FROM, all of the column data is returned in the array but without me needing to write out all of these individually? (the below)
'id' => $row['ID'],
's_reference' => $row['s_reference'],
'reference' => $row['reference'],
'customer_name' => $row['customer_name']
Ok I forgot to add that I'd tried this:
$data['data'][] = array($row);
Which is clearly wrong, and after using the following, it works perfectly!
$data['data'][] = $row;

PHP. How to take data from 2 mysql tables instead of 1

Learning php and I am losing my mind trying to solve this for days now. Please help.
This is a code which goes thought a table COUPON, take data with a condition met, and download it afterwards. In this table COUPON I have USER_ID as number but I want to have a user name also, which is kept in another table USER.
How can I go to another table (USER) and take names (REALNAME) by this USER_ID which is the same in both tables?
if ( $_POST ) {
$team_id = abs(intval($_POST['team_id']));
$consume = $_POST['consume'];
if (!$team_id || !$consume) die('-ERR ERR_NO_DATA');
$condition = array(
'team_id' => $team_id,
'consume' => $consume,
);
$coupons = DB::LimitQuery('coupon', array(
'condition' => $condition,
));
if (!$coupons) die('-ERR ERR_NO_DATA');
$team = Table::Fetch('team', $team_id);
$name = 'coupon_'.date('Ymd');
$kn = array(
'id' => 'ID',
'secret' => 'Password',
'date' => 'Valid',
'consume' => 'Status',
);
$consume = array(
'Y' => 'Used',
'N' => 'Unused',
);
$ecoupons = array();
foreach( $coupons AS $one ) {
$one['id'] = "#{$one['id']}";
$one['consume'] = $consume[$one['consume']];
$one['date'] = date('Y-m-d', $one['expire_time']);
$ecoupons[] = $one;
}
down_xls($ecoupons, $kn, $name);
After this, I want to try to do the same thing using only SQL queries.
You would need to JOIN the tables in the SQL query
SELECT something FROM coupons as coupons JOIN user as user ON coupons.id=user.id
You should use join when you want to retrieve details from two tables.
Join table COUPON and table USER based on user_id . This should yield results you want.

Codeigniter Active Record: is it possible to remove the brakets around the table name

I am using codeigniter to produce a left join of two tables, but need to remove the brackets that active record applies to the table name. you know SELECT blah FROM ('some table') I really need these brackets to disappear.
here is my input array:
$retrieve_arr = array(
'table' => 'entries',
'select' => array('entries.entry_id', 'entries.score', 'sc_users.name', 'clients.name'),
'joins' => array(
'clients' => 'entries.client_id = clients.client_id',
'sc_users' => 'entries.sc_user_id = sc_users.sc_user_id'
),
'joinType' => 'left',
'where' => 'null'
);
here is my model:
$retrieve = new Data();
if($get_arr['select'] != 'null')
{
$query = $retrieve->db->select($get_arr['select']);
}
foreach($get_arr['joins'] as $additional => $value)
{
$retrieve->db->join($additional, $value, $get_arr['joinType']);
}
if($get_arr['where'] != 'null')
{
foreach ($get_arr['where'] as $name => $value)
{
$retrieve->db->where($name, $value);
}
}
$query = $retrieve->db->get($get_arr['table']);
$queryData = $query->result_array();
return $queryData;
and here is what my query string:
SELECT `entries`.`entry_id`, `entries`.`score`, `sc_users`.`name`, `clients`.`name` FROM (`entries`) LEFT JOIN `sc_users` ON `entries`.`sc_user_id` = `sc_users`.`sc_user_id` LEFT JOIN `clients` ON `sc_users`.`client_id` = `clients`.`client_id`Array
I have been looking for this for a while so your help is very much appreciated.
If you are referring to the ` backticks, in the Select() portion, use a FALSE as the second parameter (refer to the Users Guide for more info)

MySQL Select FROM 3 tables AND put that in PHP array

Sorry for bad english and bad title!
I have the table "post"
id title
1 test Thread
2 hello
3 just
so have "tags"
tagid tagname
1 test
2 russia
3 new site
so have a post_tags
tagid postid
1 1
2 1
3 1
I need an array from var_dump next below:
$posts = array(
1 => array(
'title' => 'test Thread',
'tags' => array(
'test', 'russia', 'new site',
),
),
2 => array(
'title' => 'hello',
'tags' => NULL
),
3 => array(
'title' => 'just',
'tags' => NULL
),
)
I trying do it, but i getting not that what i want.
SELECT `post`.`id`, `post`.`title`, `tags`.`tagname` FROM `post`
LEFT JOIN `post_tags` ON `post_tags`.`tagid` = `post`.`id`
LEFT JOIN `tags` ON `post_tags`.`tagid` = `tags`.`tagid`
I getting in SQL next following:
id title tagname
1 test Thread test
1 test Thread russia
1 test Thread newsite
2 hello NULL
3 just NULL
PHP
$query = mysql_query("SELECT `post`.`id`, `post`.`title`, `tags`.`tagname` FROM `post`
LEFT JOIN `post_tags` ON `post_tags`.`tagid` = `post`.`id`
LEFT JOIN `tags` ON `post_tags`.`tagid` = `tags`.`tagid`");
$posts = array();
while ($row = mysql_fetch_assoc($query))
{
$posts[] = $row;
}
var_dump($posts);
Thank you!!!
The query is fine. You just need some logic in your loop:
while ($row = mysql_fetch_assoc($query))
{
if (isset($posts[$row['id']])) {
$posts[$row['id']]['tags'][] = $row['tagname'];
}
else {
$posts[$row['id']] = array(
'title' => $row['title'],
'tags' => $row['tagname'] === null ? null : array($row['tagname'])
);
}
}
If you have already seen a row with the same post id then all you want from the current row is the tag name (so add this to the "tags" array). If it's the first time a row with this post id is seen just add it to $posts, being a little careful to set "tags" to either null or an array with one element.
you cannot get a multi-dimensional arrays back from a mysql database. you must do your own post processing to the results if you want it in that form. Something like this maybe?
$posts = array();
while ($row = mysql_fetch_assoc($query))
{
if (!isset($posts[$row['id']])) {
$posts[$row['id']] = array();
$posts[$row['id']]['title'] = $row['title'];
$posts[$row['id']]['tags'] = array();
}
if ($row['tagname'] != null) $posts[$row['id']]['tags'][] = $row['tagname'];
}
Try this:
while ($row = mysql_fetch_assoc($query))
{
if( !isset( $posts[$row["id"]] ) ) {
$posts[ $row["id"] ] = array( "title" => $row["title"], "tags" => array() );
}
array_push( $posts[ $row["id"] ][ "tags" ], $row["tagname"] );
}
I can't debug it, so tell me if you get any errors

JOIN in an associative array instead of separated records

Table stores
id name date
1 foo 2011-06-15 15:10:34
2 bar 2011-07-02 16:45:18
Table locations
storeid zipcode latitude longitude
1 90001 xxxxx xxxxx
1 45802 xxxxx xxxxx
2 32843 xxxxx xxxxx
How can i produce an associative array that contains a key called locations which is an array of all locations of a store?
My current SQL ( which separate each location in a record ):
SELECT stores.*, locations.* FROM locations INNER JOIN stores ON stores.id = locations.storeid
Example of what i want:
array(
[0] => array(
"id" => 1,
"name" => "foo",
"locations" => array(
[0] => array(
"zipcode" => 90001,
"latitude" => -45.48513,
"longitude" => 82.12432
)
[1] => array(
"zipcode" => 42802,
"latitude" => -31.48513,
"longitude" => 77.12432
)
)
)
)
and so on for other stores...
Thanks
So you can't extract the data in one query because SQL normally works per row and hasn't got data structure like PHP arrays. You can't nest the records using JOIN. That's why you'll have to do it with with separate queries in a PHP loop. Like so:
$query = "SELECT s.id,s.name FROM stores AS s";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_assoc( $result )) {
$data[] = $row['id'];
$data[] = $row['name'];
$query2 = "SELECT l.zipcode, l.latitude, l.longitude FROM locations AS l WHERE storeid=".$row['id'];
$result2 = mysql_query($query2);
while($row2 = mysql_fetch_assoc( $result )) {
$data['locations']['zipcode'] = $row2['zipcode'];
$data['locations']['latitude'] = $row2['latitude'];
$data['locations']['longitude'] = $row2['longitude'];
}
}
Otherwise you can grab all results with JOIN and do as follows:
$query = "SELECT * FROM stores AS s
LEFT JOIN locations AS l
ON s.id = l.storesid";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_assoc( $result )) {
$data[$row[id]]['id'] = $row['id'];
$data[$row[id]]['name'] = $row['name'];
$data[$row[id]]['locations'][] = array($row['zipcode'], $row['latitude'], $row['longitude']);
}
But this will make the main array's index to be set not sequential starting from 0 but each index will be equal to the ID of the "store" item

Categories