Access specific row in mysql recordset - php

I have a database table with options that looks like this
I do a SELECT * FROM options and load all records into a recordset.
How do I then access just the optionValue of optionName = SMSactive
[EDIT]
Yes, I could do SELECT * FROM options WHERE optionName ='SMSactive' - I know that.
But as I said, since I have a recordset with a bunch of rows in it (from the SELECT), I want to pull a specific row where optionName = SMSactive
[EDIT]
If you are using PHP >= 5.5 you can use array_column() http://php.net/array_column
But if not, the question has already been asked and answered here PHP multidimensional array search by value

To access to all records with optionName = SMSactive the SQL should be:
SELECT * FROM `TableName` WHERE `optionName` = 'SMSactive'
if your array result from the query is something like this:
$array = array(
0 => array(
'optionName' => 'lala0',
'optionDescription' => 'lala01',
'optionValue' => 'lala03',
),
1 => array(
'optionName' => 'lala1',
'optionDescription' => 'ala2',
'optionValue' => 'SMSactive',
)
);
You can grab who has 'optionValue' => 'SMSactive', by this way
foreach ($array as $key) {
if ($key['optionValue'] == 'SMSactive') {
$filtered[]=$key;
}
}
echo '<pre>';
print_r($filtered);
echo '</pre>';
Side Note: If the array is very large you have to be careful with the memory...it's advisable just get from the db what you are using in the moment...IMO

Related

Build PHP array from query

I'm currently manually building an array.
$this->array_list = array('Alaska' => 'Alaska',
'Amanda' => 'Amanda',
'America' => 'America',
'Anthea' => 'Anthea',
'Arena' => 'Arena',
'Atlantis' => 'Atlantis'
);
I have a database that i can query this list from, My question is how do I create the array with key and value once getting the list from the query? Key and Value will always be the same. Using mysql and codeigniter.
Query DB for list, create two arrays and use combine? Has to be an easier way?
Here is what I ended up doing. Probably not the best way, feel free to give better way to do this.
$sofa_list2 = $this->get_media_model->get_sofas();
foreach ( $sofa_list2 as $k=>$v )
{
$newkey = $sofa_list2[$k]['collection_name'];
$sofa_list2[$k] ["$newkey"] = $sofa_list2[$k] ['collection_name'];
unset($sofa_list2[$k]['collection_name']);
}
$sofa_list2 = call_user_func_array('array_merge', $sofa_list2);

PHP: accessing mysqli result by record id

i'm having an array which contains record ids as follows:
Array
(
[0] => 113
[1] => 43
[2] => 64
)
so for achieving the corresponding records, i'd have to run 3 queries:
select * from mytable where id=113
select * from mytable where id=43
select * from mytable where id=64
my question: wouldn't it be possible executing just ONE query on the whole table then directly access the mysqli result like an associative array by passing the ID?
something like $record = $res['id'][113];?
thanks in advance
You need the IN clause
SELECT * FROM mytable WHERE id IN ( 113,43,64 );
Custom function indexme takes an array of arrays (numeric or associative) and by default gets the first element value of each sub-array and makes it the associative index in a return array. Optionally, a column name can be passed as the second parameter to designate which column value to use for the index.
$array = array(array('id' => 12, 'name' => 'Joe'), array('id' => 9, 'name' => 'Jane'));
$array_keyed = indexme($array);
// > array(12 => array('id' => 12, 'name' => 'Joe'), 9 => array('id' => 9, 'name' => 'Jane'));
print $array_keyed[12]['name'];
// > Joe
function indexme($arr, $key = '') { // <- custom function indexme
$return_arr = array();
if ( '' == $key ) {
$keys = array_keys($arr[0]);
$key = $keys[0];
}
foreach ( $arr as $value ) {
$return_arr[$value[$key]] = $value;
}
return $return_arr;
}
Pass the mysqli response to this function to make an ID indexed array:
$results_keyed = indexme($result->fetch_assoc(), 'id');
Check out the accepted answer on this page MySQL Prepared statements with a variable size variable list for a nice solution to the WHERE IN technique.

Create array from mysql query. Column2 as key Column 1 as value

I have a table that contains
column 1 = state column 2 = link
Alabama auburn.alabama.com
Alabama bham.alabama.com
Alabama dothan.alabama.com
I need to grab from my database table and put into an array that i can array_walk() through. they need to be accessed like this array.
$arraytable = array(
"auburn.alabama.com"=>"Alabama",
"bham.alabama.com"=>"Alabama",
"dothan.alabama.com"=>"Alabama",
);
I have tried everything but not sure how make this work using php to print the array like such. Any help is greatly appreciated.
Note Your question title is inconsistent with your example. In the title you ask for column 1 as the key, but your example uses column 2 as the key. I've used column 2 here...
It isn't clear what MySQL API you are using to fetch, but whichever it is, use the associative fetch method and create new array keys using the pattern $arraytable[$newkey] = $newvalue. This example would be in object-oriented MySQLi:
$arraytable = array();
while($row = $result->fetch_assoc()) {
// Create a new array key with the 'link' and assign the 'state'
$arraytable[$row['link']] = $row['state'];
}
You can use array_column for this, since PHP5.5 (http://php.net/array_column)
Description
array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.
For PHP < 5.5:
https://github.com/ramsey/array_column/blob/master/src/array_column.php
To implement AcidReign's suggestion, here is the snippet:
Code: (Demo)
$resultset = [
['state' => 'Alabama', 'link' => 'auburn.alabama.com'],
['state' => 'Alabama', 'link' => 'bham.alabama.com'],
['state' => 'Alabama', 'link' => 'dothan.alabama.com']
];
var_export(array_column($resultset, 'state', 'link'));
// ^^^^-- use this column's data for keys
// ^^^^^-- use this column's data for values
Output:
array (
'auburn.alabama.com' => 'Alabama',
'bham.alabama.com' => 'Alabama',
'dothan.alabama.com' => 'Alabama',
)
However, array_column() won't directly work on a result set object, but a foreach() can immediately access the data set using array syntax without any fetching function calls.
Body-less foreach: (Demo)
$result = [];
foreach ($mysqli->query('SELECT * FROM my_table') as ['link' => $link, 'state' => $result[$link]]);
var_export($result);
Or a foreach with a body: (Demo)
$result = [];
foreach ($mysqli->query('SELECT * FROM my_table') as $row) {
$result[$row['link']] = $row['state'];
}
var_export($result);
All of the above snippets return:
array (
'auburn.alabama.com' => 'Alabama',
'bham.alabama.com' => 'Alabama',
'dothan.alabama.com' => 'Alabama',
)

Format MySQL Select into Associative Array in CakePHP

I like how CakePHP automatically loops through the results of MySQL queries and formats them in a nice map for you.
Here's a sample query that I'm using:
# Inside some model
return $this->query("
SELECT
Profile.id,
SUM( IF( HOUR(Log.event_one) > 3, 1, 0 ) ) as EventOne
FROM profiles Profile
JOIN logs Log ON Log.id = Profile.log_id
WHERE Profile.id = {$pUserId}
");
CakePHP would return a map like the following as the result:
array
0
array
'Profile'
array
'id' => 23
'0'
array
'EventOne' => 108
1
array
'Profile'
array
'id' => 23
'0'
array
'EventOne' => 42
2
...
What I'm trying to do is have the result be something like this:
array
'Profile'
array
'id' => 23
'Events'
# ^ I want to be able to specify this key
array
'EventOne' => 108
Any ideas?
You can't do that directly
The top level array keys are derived from the table name which mysql says the field relates to - in your case it's a calculated field and therefore (according to mysql) belongs to no table - hence the 0 array key.
Post processing
What you can do however, is post process the result so that it is the format you want:
public function getStuff() {
// The query call in the question can very easily be a normal find call
$return = $this->query("don't use query unless you have no choice");
foreach($return as &$row) {
$row['Events'] = $row[0];
unset($row[0]);
}
return $return;
}

Convert mysql result (big associative array) to nested arrays

I have a simple query like this
SELECT hometeam.name AS hometeamName, hometeam.shortname AS hometeamShortName,
roadteam.name AS roadteamName, roadteam.shortname AS roadteamShortName,
smatch.startdate
FROM smatch
JOIN team hometeam
ON smatch.hometeamid = hometeam.uid
JOIN team roadteam
ON smatch.roadteamid = roadteam.uid
which be default returns a one dimensional array, like this:
array(5) {
["homeTeamName"] => "Brasil"
["homeTeamShortName"] => "BRA"
["roadTeamName"] => "Norway"
["roadTeamShortName"]=> "NOR"
["startdate"]=> "1309709700"
}
Question is, is there a mysql-way to let the result be a nested array, with a structure like the following?
result =>
hometeam =>
name
shortname
roadteam =>
name
shortname
startdate
And if not, is there a (php) post processing best practice to do this conversion?
Many thanks,
Robson
I don't think there's a way to directly get the result you want, but to generate that array after the query shouldn't be hard.
Something like this?
foreach($rows as $row) {
$resultArray[] = array(
'hometeam' => array(
'name' => $row['homeTeamName'],
'shortname' => $row['homeTeamShortName']
),
'roadteam' => array(
'name' => $row['roadTeamName'],
'shortname' => $row['roadTeamShortName']
),
'startdate' => $row['startdate']
);
}
MySQL (or any database) has no concept of arrays.
The only way I can think of is that you'd need to do it in a Stored Procedure and serialise the result in some way - essentially creating a serialised string... wich you'd then need to re-construct the array from.
However, would be better doing this in PHP to be honest, the gain from doing it in an SP will be minimal. Will be more efficient to query the main and then query within using loops PHP-side.
You have to fetch the result in PDO::FETCH_CLASS mode.
by specifying the __set()-method respectively you can store the result-field-data how ever you like.
This class should also extend ArrayAccess so you can access it like an array or have it return one.

Categories