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;
}
Related
I'm using CodeIgniter framework for the easyappointments.org library. I'm trying to update the field data through the id of a row. Actually this is my code for the update:
return $this->db
->update('ea_appointments', $appointment)
->where('ea_appointments.id', $appointment_id);
The problem's that the update method need two parameter (table to update, associative array with the fields name column of db). In my above function I pass only the $appointment_id, so the variable $appointment is empty and doesn't contain any associative array. I want to know how to update only the field data to 1. And remain the other field in the same value condition.
This is the structure of the table:
id|book|start|end|notes|hash|unavailable|provider|data
Logic example:
previous condition row:
id => 0
book => example
start => 18/10/2015
end => 19/10/2015
notes => empty
hash => akdjasldja
unavailable => false
provider => 5
data => 0
I pass in the function $appointment_id with 0 value. I'm waiting this new result:
id => 0
book => example
start => 18/10/2015
end => 19/10/2015
notes => empty
hash => akdjasldja
unavailable => false
provider => 5
data => 1
So the main problem is retrieve first the all field value of the specific row and later update? Or something like this. Could someone help me?
In my above function I pass only the $appointment_id, so the variable
$appointment is empty and doesn't contain any associative array.
If you simply want to update the column data to 1 for appointment_id 0 then pass in an array with data for the key and 1 for the value.
$appointment_id = 0;
$appointment = array('data' => 1);
$this->db->where('id', $appointment_id);
$this->db->update('ea_appointments', $appointment);
We are using the Zend Framework in our company and thus we're using Zend_Db_Select.
Now we are building a query with it which is then (pre fetch) passed to a function.
The query is built as follows:
$select = $this->_selectAll()
->setIntegrityCheck(false)
->joinLeft('shop', $conShop, $colShop)
->joinLeft('ptool', $conPtool, $colPtool)
->where('ptool.product_id > 0')
->where('ptool.product_is_from_shop = 0')
;
Where $conShop and $colShop are something like:
$colShop = array('shop_id','shop_channel');
$conShop = "shop.shop_id = ptool.shop_id";
In a new method I want to get all joined tables and their columns that are going to be selected. So the $select gets passed to the method and now I would like to get something like this:
Array
(
['shop'] => Array
(
[0] => 'shop_id',
[1] => 'shop_channel',
...
),
['ptool'] => Array
(
[0] => 'shop_id',
[1] => 'ptool_id',
...
),
...
)
It would be nice if I can get this pre fetch.
The background is that I want to sort by shop_id for example and this table name is used in two joined tables. If I do something like "ORDER BY shop_id" I'd get the error that the column is ambiguous. That's why I need to know which columns belong to which table so that I can do something like "ORDER BY shop.shop_id"
Hope you can help me. Thanks! :)
I'm trying to get records from a table using a given ID and I want to store specific columns into another array but I'm getting null every time I var_dump() my array.
My code:
$getOrder = array();
foreach($ordersInWaypoint as $ordersInWaypoints)
{
$getOrder[] = array(
array($ordersInWaypoints),
array(Order::where('id', '=', $ordersInWaypoints)->get()->lists('tracking_id')),
array(Order::where('id', '=', $ordersInWaypoints)->get()->lists('shipper_ref_no'))
);
}
For those wondering where $ordersInWaypoint came from, I retrieved that from here:
$ordersInWaypoint = array();
ordersInWaypoint = Transaction::where('waypoint_id', "=", $firstWaypoint)->get()->lists('order_id');
Don't mind the $firstWaypoint since that is determined by user input.
Everytime I var_dump($getOrder); I get the following result set:
array (size=1)
0 =>
array (size=3)
0 =>
array (size=1)
0 => int 637
1 =>
array (size=1)
0 =>
array (size=1)
...
2 =>
array (size=1)
0 =>
array (size=1)
...
The first element is correct, but the rest return empty sets.
I think you're getting no value because those Order::where(...) return Eloquent objects, not just single values.
You could better try this way:
$getOrder = array();
foreach($ordersInWaypoint as $ordersInWaypoints)
{
$order = Order::where('id', '=', $ordersInWaypoints)->get();
$getOrder[] = array(
array($ordersInWaypoints),
array($order->tracking_id),
array($order->shipper_ref_no)
);
}
Let me know if this fixes it ;)
Edit
It's even better if you don't use a multidimensional array as you need just these three values, so the final code becomes:
$getOrder = array();
foreach($ordersInWaypoint as $ordersInWaypoints)
{
$order = Order::where('id', '=', $ordersInWaypoints)->get(); // create Eloquent object from query
$getOrder[] = array(
$ordersInWaypoints,
$order->tracking_id, // Calls column value as method from the Eloquent object
$order->shipper_ref_no // Same (you could also call it as an array,
); // in that case you would type $order['shipper_ref_no']
}
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.
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