There is probably something dumb I am doing wrong here.
public function get_scores($id)
{
$results = array();
$sql = "SELECT * FROM scores WHERE comp_id = $id";
$rows = $this->db->query($sql)->result();
foreach($rows as $row) {
if($row->confirmed_id) {
$results[$row->uid] += $row->score;
}
}
sort($results);
return $results;
}
So basically what I am trying to do is add all of the users scores in the database and return them in order of rank. confirmed->id is just a check to make sure the score has been confirmed (and thus is addable to their total score). I am basically trying to just make an associative array where the key is the users ID, and the score of each question they have in the database is added on. The query works fine, and $row-uid and $row->score both return the correct thing for every row, but $results[] never has anything added to it. If I even change it just to something silly like $results[3] = 0 at top, and then $results[3]++ or += 1 in the for loop, it doesn't add anything to $results[3].
EDIT: Problem solved. Indeed was something dumb -- confirmed_id was set to null by my partner when he reran our database after I had previously set it all to 1. Thanks guys :)
You are adding to $results[something] before it exists. You need to create it in the first case and then only increment it once it exists.
You need to remove the "+=" operation from the code. Check with this.
public function get_scores($id)
{
$results = array();
$sql = "SELECT * FROM scores WHERE comp_id = $id";
$rows = $this->db->query($sql)->result();
foreach($rows as $row)
if($row->confirmed_id)
$results[$row->uid] = $row->score;
sort($results);
return $results;
}
Your previous operation is similar to
$results[$row->uid] = $results[$row->uid] + $row->score;
So it will not add values to your row.
Related
$query = $this->db->query("SELECT field_name FROM table_name;");
$getData= array();
foreach ($query->result() as $row) {
array_push($getData, $row->field_name);
}
I use codeigniter, for every table that I need to manage if the data exist for update or make a new insert I use this code so i would like to see is there are more options for dont replicate the code every time. I'm just a student, sorry for mi english
It is not clear why you are doing this, but I would call it "flattening" the array. If you find the need to do this often then creating a "worker" method might help.
For example, in a model, you might have two methods that both need "flat" results.
public function get_something()
{
$query = $this->db->query("SELECT field_name FROM table_name;");
//call the "worker"
return $this->make_flat($query);
}
public function get_something_else()
{
$query = $this->db->query("SELECT field_name FROM table_name;");
//call the "worker"
return $this->make_flat($query);
}
Elsewhere in the model, there is this "worker" method used in the code above used.
// The "worker" method to flatten the results
protected function make_flat($query)
{
$getData = []; //is same as $getData = array(); but with less typing
foreach ($query->result() as $row)
{
$getData[] = $row->field_name;
}
return $getData;
}
The line $getData[] = $row->field_name; does exactly the same thing as array_push($getData, $row->field_name);. But it is actually a bit faster. It is also less typing.
http://php.net/manual/en/function.array-column.php should work great for this.
$query = $this->db->query("SELECT field_name FROM table_name;");
$array = array_column($query, 'field_name');
print_r($array);
your question seems to contradict your code. if you just want to see if a particular entry already exists you can do:
$this->db->where('field_name', $var);
$exists = $this->db->count_all_results('table_name');
if ($exists > 0) {
// update
// there is an entry with $var for `field_name` in table `table_name`
} else {
// insert
}
I have a problem with a mysql_query - YES, i know it's updated and i need to upgrade it to pdo or mysqli..
However, it only get one row from the database, where it needed to pull out 3 rows. It only take the first row it find.
$result = mysql_query("SELECT * FROM packages WHERE workerid = '$id' AND approved = '1'");
$packed = array();
while($row = mysql_fetch_assoc($result)){
$packed[] = $row;
return $packed;
}
Right now i just print_r($packed);, which only give me the first row of the table. Workerid and approved are checked on the other rows, and they should be able to get pulled out. I have a similar code in my functions, which work perfect, so i cant really see the error here.
could try
while($row = mysql_fetch_assoc($result)){
array_push($packed, $row);
}
print_r($packed);
return $packed;
or
while($row = mysql_fetch_assoc($result)){
$packed[] = $row;
}
print_r($packed);
return $packed;
This should push each row return onto the end of the array. I am using print_r so that you can see if the array contains all the values you are looking for.
I often need to retrieve results and access them by a given column.
Is there a way to write this without walking through the whole dataset each time?
I looked into various PDO fetch modes, but nothing jumped out as being simpler than that. Thanks.
function get_groups() {
$stmt = $dbc->prepare("SELECT * FROM groups ORDER BY group_name");
$stmt->execute();
$groups = $stmt->fetchAll();
$return = [];
foreach($groups as $group) {
$return[$group['id']] = $group;
}
return $return;
}
My proposed solution was pretty obsolete. The right solution comes from this answer
$stmt = $pdo->query("SELECT foo,baz FROM bar")
$groupedByFooValuesArray = $stmt->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE)
to group it by another column, change the first column you select
if your goal is to have your same array indexed by different column values, I think the only option is to actually index them by different column values.
you can do that by controlling by which field the array is returned
function get_groups($sql,$key,$values='') {
if ($values != '') {
$stmt = $dbc->prepare($sql);
$stmt->execute($values);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else {
$rows = $dbc->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
foreach ($rows as $row) {
$indexed[$row[$key]] = $row;
}
return $indexed;
}
then, use get_groups to build an indexed array:
$sql = 'SELECT * FROM groups ORDER BY group_name'
var_dump(get_groups($sql,'id'));
There might be a way to store a resultset in some way that you can fetchAll() it multiple times, that would be awesome. but I don't know it.
How would i go about the following problem which involves running an update query for every row in the array defined below? I hope it becomes clear...
<?php
//Some code
user = array();
while ($row = mysql_fetch_array ($auctioncheck)){
$fdt[] = $row['finish_time'];
if ($date_time >= $fdt) {
$user[] = $row['current_bidder'];
{
{
I then want to update a table which sets the value as "user[]". What is the neatest way of doing this? I presume it requires a while loop only i don't know how to do it in this context. So it would be like...
<?php
//Above while loop and then...
$update = mysql_query("UPDATE homepage SET username = '$user[]'...so on");
Basically i want the update to be performed for every user[] in the above array. I might be able to figure it out if i knew how to determine the number of rows in the the user array. Any help would be much appreciated. Cheers.
It looks like the for each will come into play. Only i am now concerned with the elements of multiple arrays being used in the update.
$user = array();
$seller = array();
while ($row = mysql_fetch_array ($auctioncheck)){
$fdt[] = $row['finish_time'];
if ($date_time >= $fdt) {
$user[] = $row['current_bidder'];
$seller[] = $row['seller'];
}
}
$update = mysql_query("UPDATE homepage SET username = '$user[]'...WHERE username = '$seller'");
Any ides anyone for the multiple elements and arrays.
It should be $user = array();
Is this what you're looking for?
<?php
//Above while loop and then...
foreach($user as $value){
$update = mysql_query("UPDATE homepage SET username = '$value'");
}
?>
This is not PHP
user = array();
You are missing the $
Besides
where is
{
{
come into play?
tl;dr - Pushing an array (by $array[] or $array[$id] is not working in Kohana 3, it gives a blank white page.
I'm using Kohana (3), it's my first experience with MVC and it's been great so far; however, I'm working with a database and encountered a weird problem that I was hoping someone could shed some light on:
My workflow is like this, to give you an idea of my problems surrounding:
$sql = "SELECT table1.row1, max(table2.row1) as `maxAwesome` FROM table1, table2 WHERE table1.id=table2.table1id GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
foreach ($table1Results as $result1)
{
$sql = "SELECT * FROM table2 WHERE table2id='" . $result1['id'] . "' AND column > 21";
$table2Results = DB::query(Database::SELECT, $sql)->execute();
$subArray = array();
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
I do a query where I run a couple max/min functions then do a query within the foreach doing another select to build a master array of data formatted the way I want it and all the SQL etc works fine and dandy; however, the problem arises when I'm pushing the array.
It seems whenever I push the array by doing either $array[] = array("data"); or by specifying the key $array[$id] = array("data"); Kohana gives me a straight blank page, no error, no output etc.
Sometimes I get a Kohana error indicating the key does not exist (duh, I'm creating it) but for the most part the output is straight white.
Why is this happening? Am I going about it wrong?
Thanks in advance.
Clarity edit:
My SQL blunders aside, the issue lies in the building of the secondary array, for example:
$queryStores = "SELECT stores.store_id, stores.title, max(product.discount) as `max_discount`, min(product.discount) as `min_discount`
FROM stores, products
WHERE products.store=stores.store_id
GROUP BY products.store";
$stores = DB::Query(Database::SELECT, $queryStores)->execute();
$formattedStores = array();
if (count($stores))
{
foreach ($stores as $store)
{
$formattedStores[$store['store_id']] = array(
"title" => $store['title'],
);
// Same result if just doing $formattedStores[] = array();
// Problem goes away should I do:
// $formattedStores = array("This works");
//
}
}
echo "<pre>";
print_r($formattedStores);
echo "</pre>";
That does not print an array, it simply gives a blank page; however, if i change it to just re-set the $formattedStores array to something I get an output. What is it about pushing the array that's causing a problem, perhaps a Kohana bug?
Thanks
Your code should be like:-
$sql = "SELECT table1.id, table1.row1, max(table2.row1) as `maxAwesome`
FROM table1, table2
WHERE table1.id = table2.table1id
GROUP BY table1.id";
$table1Results = DB::query(Database::SELECT, $sql)->execute();
$masterArray = array();
if (count($table1Results))
{
foreach ($table1Results as $result1)
{
$sqlInner = "SELECT * FROM table2
WHERE table2id = '" . $result1['id'] . "'
AND column > 21";
$table2Results = DB::query(Database::SELECT, $sqlInner)->execute();
$subArray = array();
if (count($table2Results))
{
foreach ($table2Results as $result2)
{
$subArray[$result1['id']] = $result2;
// Even had just $subArray[] = array("whatever");
}
}
$masterArray[] = array("table1Data" => array(), "table2Data"=> $subArray);
}
}
Some valuable coding standards & miss-ups:-
You have got the "id" field (w.r.t. the "table1" DB table) missing from the first SQL.
The second SQL should be better written using another variable naming, so as to keep it separate from the first one. Hence the second variable is named as "$sqlInner".
It's always better to check for any existence of array elements in an array variable, so I have used the simple checks using the "if" statement.
Hope it helps.
I've determined this to be memory related.