The following code is a simple select statement that should use the array_sum function to return a value. The result should be getting stored in an array and then getting added up in the SUM function:
$this->db->select('period')
->from('calcdata');
$query = $this->db->get()->result_array();
$query = array_sum($query);
echo "SUM " . $query . "\n" ;
return $query;
the result of this is "SUM 0" but it should be 147 after adding all values up in the period column.
The following code works so i don't understand why the array would be any different from this:
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
I am using codeigniter to create the arrays, does anyone know what is wrong here?
Thanks
Try calling the content of the field instead, not of the whole result array:
$this->db->select('period')->from('calcdata');
$query = $this->db->get();
$period_array = array();
foreach ($query->result_array() as $row)
{
$period_array[] = intval($row['period']); //can it be float also?
}
$total = array_sum($period_array);
UPDATE:
#uzsolt is right, I almost forgot there's a dedicated function in the Active Record class, select_sum(); you might want to try that out also, something like
$this->db->select_sum('period')->get('calcdata');
Quoting from the docs:
$this->db->select_sum();
Writes a "SELECT SUM(field)" portion for your query. As with
select_max(), You can optionally include a second parameter to rename
the resulting field.
$this->db->select_sum('age'); $query = $this->db->get('members');
//> Produces: SELECT SUM(age) as age FROM members
Related
How can I return only 1 record on this statement?
public function edititem($id){
$this->db->select('*');
$query = $this->db->get('tblitem');
$this->db->where('item_id',$id);
foreach ($query->result() as $row){
echo $row->item_id.'</br>';
echo $row->item_name.'</br>';
echo $row->item_description.'</br>';
echo $row->item_price.'</br>';
}
}
It gives me all the records instead
Use $this->db->limit(1); to get 1 record only.
For fetching single row form table use ->row()
function edititem($id) {
$this->db->select('item_id,item_name, item_description,item_price');
$this->db->where('item_id', $id);
$this->db->limit(1);// only apply if you have more than same id in your table othre wise comment this line
$query = $this->db->get('tblitem');
$row = $query->row();
echo $row->item_id . '</br>';
echo $row->item_name . '</br>';
echo $row->item_description . '</br>';
echo $row->item_price . '</br>';
}
Read https://www.codeigniter.com/userguide3/database/results.html
Use these
Method 01 - $this->db->get()
$query = $this->db->get('tblitem' ,1 , 0); # Set Limit
Method 02 - $this->db->limit() in CI
$this->db->limit(1);
Method 03 - Result Rows in CI
$row = $query->first_row('array');
$row = $query->last_row('array');
$row = $query->next_row('array');
$row = $query->previous_row('array');
These will only produce one set of data. and in your foreach loop it will always return one
Use limit, so sql will return you the only first row found, but not the whole set of rows. The CI's manual is explicit about getting results.
here're two one-liner solutions, through the get():
// ... other query conditions
$this->db->limit(1)->get('tblitem')->row()->your_key;
// or with the short syntax for defining limit, through the get:
$this->db->get('tblitem', 1, 0)->row()->your_key;
if you need to reference several values later on, assign result of row() to variable, to re-use later.
$row = $this->db->limit(1)->get('tblitem')->row();
Use this:
$this->db->get()->custom_row_object(0, 'Your_Model');
The code above is mentioned by the codeigniter user guide. The best about this is no need to loop foreach where you can get very specific row value.
This question already has answers here:
PDO fetch one column from table into 1-dimensional array
(2 answers)
Closed 2 years ago.
I am using PDO to call my database from xampp's phpmyadmin.
XAMPP version 7.0.1-0
When I create an array from scratch, and implode it, it gives me the results I want to see.
For Example:
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
Which gives me:
Hello World! Beautiful Day!
However, when I do the same thing to my database query, this happens:
Notice: Array to string conversion in C:\xampp\htdocs\WHS_Webtour\Search_Categories\People_Search_Result\people_search.php on line 57
Array Array Array Array Array Array Array...
I have used var_dump() to see if the array actually shows and it does.
This is the code I used to call from my sql database:
function getData($db)
{
$stmt = $db->query('SELECT NAME FROM people');
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
I then added echo implode(" ",$result); which gave me the error result above.
If this helps, I had imported a database file which was converted from a .dbf to a .sql.
UPDATE
I updated this line of code: $result = $stmt->fetch(PDO::FETCH_ASSOC);
It only prints out one out of 50 names.
Another solution would be to do this right in your Query.
SELECT
GROUP_CONCAT(`NAME` SEPARATOR ' ') AS `NAMES`,
1 AS `x`
FROM `people`
WHERE 1
GROUP BY `x`
Judging by your query, I'm guessing you are wanting to implode all the names, but the problem you are running in to is that each row you fetch is going to be an array.
function getData($db)
{
$stmt = $db->query('SELECT NAME FROM people');
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$names = array();
foreach($result as $name) {
$names[] = $name['NAME'];
}
return $names;
}
This specifically will return the information in the way you are anticipating it. It will go through each row and pull the name out in to a new array that will then be returned.
fetchAll() returns an array of arrays (a multidimensional array). Multidimensional arrays cannot be converted to text straight away due to constraints in the language. Try to return your values with fetch() which will get one row as a single array. You do this in a loop:
while($row = $stmt->fetch() {
$line = implode(" ",$row);
}
PDO Fetch
Since you're only getting one column from the database could put all of the returned values in an array:
while($row = $stmt->fetch() {
$names[] = $row['NAME'];
}
$allNames = implode(" ", $names);
This way you push each returned item into an array ($names) which you can then implode.
fetchAll() returns an array of arrays. If you want to implode() your data, you may want to try something like this using fetch():
function getData($db)
{
$stmt = $db->query('SELECT NAME FROM people');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo implode(" ",$row);
}
}
That should help!
$implodedVal = implode(', ', array_map(function ($indArray) {
return implode(", ", $indArray);
}, $result));
edited function
function getData($db) {
$stmt = $db->query('SELECT NAME FROM people');
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return implode(', ', array_map(function ($entry) {
return implode(", ", $entry);
}, $result));
}
This could help you, if I'm not wrong in understanding your question.
I have this sql query that returns no result. The table it queries has data but no results being pull. The query is put into an array.
$qry = array();
$qry[] = "SELECT events_id as 'Reference ID', event_level as 'Level', events_date as 'Date', events_time as 'Time', events_opponent as 'Opponent', events_place as 'Place', events_results as 'Results'";
$qry[] = "FROM wp_events WHERE events_id = ".$sched_id."";
$val = array();
$val = implode(" ", $qry);
$result = $wpdb->get_results($val, ARRAY_A);
i var_dump the $result but it only output Array ( ). I also tried to var_dump($val) if there is something wrong on the query but query is ok. I don't know what im missing here. please help.
There are two points in this code which can remain problematic:
Do you always have the $sched_id filled?
Does passing a complete query string to the $wpdb->get_results() return anything?
Try doing a fully complete query in phpMyAdmin to see the expected result and work the PHP code until you have the same results back.
try something like this if u want to print variable values..
<?php
$id = $_GET['value'];//value received from array[]
$N = count($id);
for($i=0; $i <N; $i++)
{
$result_h = mysql_query("SELECT * FROM `table` where id='$id[$i]'");
$pks_h = mysql_fetch_array($result_h);
echo $pks_h['mysql coloumn name'];
}
?>
or use while loop if u want to print only mysql table value.
The following is the query that I'm trying to get to work.
$array = array();
SELECT * FROM ENTRIES
WHERE
entry_id = '12'
OR
entry_id_extra IN ('$array')
This is of course simplified. The problem is that it works great if the array has items and it returns everything fine. But if the array has no item it fails to work.
What is the correct way to construct this statement that doesn't break if there are no items in the array? I tried IN ('NULL','$array') but that didnt work.
Any help is appreciated.
You can make the OR portion of the where clause go through a conditional check:
$sql = "SELECT * FROM entries WHERE entry_id = 12"
if (count($array) > 0) {
$sql .= ' OR entry_id_extra IN ($array)';
}
$array = array(...);
$array = array_map('mysql_escape_string', $array); // make sure it's safe
$query = "SELECT *
FROM entries
WHERE entry_id = '12'"
. (count($array) > 0
? " OR entry_id_extra IN ('" . implode("','", $array) . "')"
: "");
// echo the query to see what it looks like (optional)
echo "<pre>{$query}</pre>";
You can use implode, but also make sure you escape the values so quotes don't set the query off.
I have a basic PHP function that I am working with. Sometimes, it is passed an array of variables, and other times it is just passed one variable. So, currently, I have something like this:
<?
function do_this($user_id_array) {
$user_ids = array();
foreach ($user_id_array as $single_user_id) {
$sql = 'SELECT username FROM users
WHERE id = $single_unit';
while($row = mysql_fetch_assoc($result)) {
array_push($user_ids, $row['id'];
}
}
return $user_ids;
}
?>
My issue is this: If I call the function and send it only one variable (and not an array), it (obviously) gives me the following error: Invalid argument supplied for foreach()
My question is: How can I change this function in the most efficient way with the least amount of code? Do I have to use an if is_array() statement and just create 2 SELECT statements, one for each case (array and non-array)?
Many thanks!
I see several options:
Pass an array even if it's one element long
Test for is_array() and act accordingly
Add another argument which states whether to check for an int or an array.
I'd go with options 1 or 2, as option 3 is error prone.
Also, there might be a better solution to your problem, you shouldn't have a single query for every user, you should instead use the IN keyword in MySQL, something like this:
$users = (is_array($user_id_array)) ? implode(',',$user_id_array) : $user_id_array;
$query = "SELECT `username` FROM `users` WHERE `id` IN({$users})";
wow. that's a lot of queries. What about to delete foreach and do something like
if (is_array($user_id_array)){
$sql = 'SELECT username,id FROM users
WHERE id IN ('.implode(",", $user_id_array).')';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$users[$row['id']] = $row;
}
}
You can write:
$user_id_array = (array)$user_id_array;
if (!is_array($user_id_array))
$user_id_array = array($user_id_array);
function do_this($user_id_array) {
$ids = array_map('intval', (array)$user_id_array);
$sql = 'SELECT username FROM users
WHERE id IN(' . implode(',', $ids) . ')';
$result = mysql_query($sql);
$usernames = array();
while ($row = mysql_fetch_assoc($result)) {
$usernames[] = row['id'];
}
return $usernames;
}
First line makes sure that you have an array ((array)$user_id_array) and that all values are valid integers. Then a single SQL query is executed for all user ids.