codeigniter - foreach query not working - php

I'm starting with codeigniter and I have a trouble with a DB query.
If I run the query in a standard PHP code, it show all data passed in the query but if I run the query using codeigniter, it show only one row with a foreach.
In the Model:
$query = $this->db->query('select C.display_name AS "Servicio", B.output AS "Status", B.last_time_ok AS "Ultimo OK" , B.last_time_critical AS "Ultimo Critical"
from system_hosts AS A
INNER JOIN system_services AS C ON C.host_object_id = A.host_object_id
INNER JOIN system_servicestatus AS B ON B.service_object_id = C.service_object_id
WHERE A.alias = "'.$hostname.'" GROUP BY C.display_name;');
return $query->row_array();
In the view:
<?php foreach ($hosts_service as $services):
?> <tr>
<h2><td><?php echo $hosts_service['Servicio'] ?></a></td></h2>
<h2><td><?php echo $hosts_service['Status'] ?></a></td></h2>
<h2><td><?php echo $hosts_service['Ultimo OK'] ?></a></td></h2>
<h2><td><?php echo $hosts_service['Ultimo Critical'] ?></a></td></h2> </tr>
<?php endforeach ?>
In Controller:
$data['hosts_service'] = $this->news_model->get_service($hostname);
It return the same value 4 times, but if I run in normal PHP it return the 3 different values containing in the DB, so the query is correct. ( I tried the same query in Toad and the result are OK).
¿What can be the problem?
Thanks a lot!

By returning a row_array(), you are only going to return a single row. For example:
get_user(user_id)
That would return a single result - the user I am looking for.
Try using:
return $query->result();
Check out Generating Query Results.

You should use result_array() instead of row_array()
try
return $query->result_array();
instead of
return $query->row_array();
See more info here

In addition to Nouphal.M's answer, you also need to use the item variable in the loop instead of the array variable.
<?php foreach ($hosts_service as $services): ?>
<tr>
<h2><td><?php echo $services['Servicio'] ?></a></td></h2>
<h2><td><?php echo $services['Status'] ?></a></td></h2>
<h2><td><?php echo $services['Ultimo OK'] ?></a></td></h2>
<h2><td><?php echo $services['Ultimo Critical'] ?></a></td></h2>
</tr>
<?php endforeach ?>
There's also some unrelated issues with your html. <h2> tags should be inside the <td> tags. You have a closing <a> tag, but no opening <a> tag.

Related

Retrieving dropdown options out of a database

I want to create a dropdown filled with numbers. These numbers need to be retrieved from a database. The connection to the database and the supposed display code are as follows:
The Function to retrieve the options for the dropdown
<?php
function dropdown_menu() {
global $wpdb;
/* Query the database */
$query = $wpdb->prepare('SELECT * FROM LID ORDER BY LidID', 'LID', 'LidID');
$results = $wpdb->get_results($query);
/* Check for $results */
if(!empty($results)) :
/* Loop through the $results and add each as a dropdown option */
global $options;
$options = '';
foreach($results as $result) :
echo ("<option value=\"<?php echo $item->LidID ?>\"> <?php echo $item->LidID ?> </option>");
endforeach;
endif;
}
?>
The statement which includes the aforementioned function into a form:
<tr class="form-field form-required">
<th scope="row"><label for="LidID">Lid ID <span class="description">(verplicht)</span></label></th>
<td><select name="LidID" id="LidID" value="<?php echo $item->LidID ?>" aria-required="true"> <?php dropdown_menu(); ?> </select></td>
</tr>
The problem I'm having, is that it creates a dropdown list with the corresponding amount of records of "LidID" in the database, but they all show up blank. I've already been toying around with it, and I think I know what the problem is, but I don't know how to solve it. I presume the problem lies within the echo-statement;
echo ("<option value=\"<?php echo $item->LidID ?>\"> <?php echo $item->LidID ?> </option>");
when I remove the second LidID ?> and replace it with, for example, a 5, it shows a list of fives. For some reason it doesn't recognize the statement I wrote. I've tried to switch out both the $item->LidID in the echo statement into $result->LidID, but that doesn't seem to have any impact. Does anyone have the slightest idea of what is going wrong here?
Oh yeah, I don't know if it's relevent but it's a plug-in for wordpress.
You're right, that is the issue. You are already in PHP when echoing, so you don't need to open more PHP tags. The other issues is $item doesn't exist. Another issue is you're not using MySQLi correctly, you only use prepare if you have a variable, you don't so don't use it. You also don't use get_results in that context. Try this:
function dropdown_menu($default) {
global $wpdb;
/* Query the database */
$query = 'SELECT * FROM LID ORDER BY LidID, LID, LidID';
$results = $wpdb->query($query);
while ($item = $results->fetch_assoc()):
echo '<option value="'.$item->LidID.'"'.($item->LidID == $default ? ' selected="selected"' : '').'>'.$item->LidID.'</option>';
endwhile;
}
Then when calling the function
<td>
<select name="LidID" id="LidID" aria-required="true"> <?php dropdown_menu($item->LidID); ?> </select>
</td>

How to use sum in active records in codeigniter?

I wanted to know if my syntax is right, this is my model where I query using
active records. I wanted to sum up the column 'amount' inside select however it won't work for me. I wonder id I am possibly doing it right? Should I separate the summation part?
function result_getAssessment()
{
$this->db->select('register.regnum,register.studentid,accountspayable.accountno,accountspayable.accounttype,accountspayable.amount,sum(amount) AS sum');
$this->db->from('accountspayable');
$this->db->join('register', 'accountspayable.regnum = register.regnum');
$this->db->where('accountspayable.regnum','15459');
$query=$this->db->get();
return $query->result();
}
This is how I call it in the views:
<?php foreach ($query as $row){ ?>
<?php echo $row->regnum;?> <br>
<?php echo $row->studentid;?> <br>
<?php echo $row->accountno;?> <br>
<?php echo $row->accounttype;?> <br>
<?php echo $row->amount;?><br>
<?php echo $row->sum;?><br>
<?php } ?>
The overall query seems to be right, but the column name does not look right to me. Instead of naming the column sum, try naming it something else (as sum is an inbuilt function), or atleast quote the sum column in backticks e.g.
function result_getAssessment()
{
$this->db->select('register.regnum,register.studentid,accountspayable.accountno,accountspayable.accounttype,accountspayable.amount,sum(accountspayable.amount) AS `sum`');
$this->db->from('accountspayable');
$this->db->join('register', 'accountspayable.regnum = register.regnum');
$this->db->where('accountspayable.regnum','15459');
$query=$this->db->get();
return $query->result();
}
It will be easier to debug if you provide the output that you are getting, but my gut feeling says that the problem is right there in the column name.
Edit: It also seems that you are summing up the wrong column. See the updated code.

How to get DQL result from the template with symfony 1.4?

I'm working with symfony 1.4 and Doctrine. I'm writing an app about some pubs/bars, and I've got 4 tables:
products
orders
product_order
pubs.
I want to get the times all products have been ordered in the first pub (i.e. pubs.id = 1). This is what I've got, but I can only get the sum of the first product (products.id = 1) and I need the sum of all of them, in this case there are two different products in my db.
ProductOrderTable:
public function ordersGetCount(){
$q = Doctrine_Query::create()
->from('ProductOrder l')
->innerJoin('l.Order p ON l.id_order = p.id')
->select('SUM(l.amount) as units')
->andWhere('p.id_pub = 1')
->groupBy('l.id_product')
->orderBy('p.id');
return $q->execute();
}
Here my action class:
$this->resultCount= Doctrine_Core::getTable('productorder')->ordersGetCount();
And here my template:
for($i=0; $i<2; $i++){
echo "<tr>";
echo "<td>".$resultCount[0]->getUnits()[$i]."</td>";//
echo "<td>1</td>";
echo "<td>1</td>";
echo "</tr>";
}
Please need help :)
I think there's nothing wrong with your query, but you should have a look at how you display your results.
echo "<td>".$resultCount[0]->getUnits()[$i]."</td>";
Firstly, you're always referring to the first element in the $resultCount array. Secondly, I'm not sure if you can use a getter for a virtual column (you're not using a column which is mapped to your model.
So I would go with something like this:
In the ordersGetCount I would use
return $q->fetchArray();
This will return an array of arrays, not an array of objects, and will allow you to access the virtual column units.
To display the results:
<?php foreach ($resultCount as $row): ?>
<tr>
<td>
<?php echo $row['units']; ?>
</td>
<td>1</td>
<td>1</td>
</tr>
<?php endforeach ?>
EDIT:
This is quite strange ;) Can you try to build the query this way: (in theory it should be the same):
$q = $this->createQuery('l')
->select('l.id_product, sum(l.amount) as units')
->innerJoin('l.Order')
->where('p.id_pub = 1')
->groupBy('l.id_product')
->orderBy('p.id');
You must try remove
->groupBy('l.id_product')
it reduces you results to one product.

While loop only executing once

I have a form that displays contact email addresses in text boxes, and drop down selections for titles for those corresponding emails.
TitleSelect1 Email1
TitleSelect2 Email2 ....
the emails have a title_id set, and the select list selects the existing Title. This works fine for the first contact, but the rest will only display the email address, the title dropdown is empty.
<?php
while ($row2 = mysql_fetch_array($Contact_list)) {
?>
<tr>
<td align="right"><select id="Contacts_title" name="Contacts_title[]">
<?
while ($row3 = mysql_fetch_array($title_list)) { //put the contact titles into an array
if ($row3['title_id'] == $row2['title_id']) {
?>
<option value="<? echo $row3['title_id'] ?>" selected="true"><? echo $row3['title'] ?>!</option>';
<?
}
else {
?>
<option value="<? echo $row3['title_id'] ?>"><? echo $row3['title'] ?> </option>';
<?
}
}
?>
</select>
</td>
<td align="left"><input type="text" id="Contacts" name="Contacts[]" value="<? echo $row2['email'] ?>"/></td>
</tr>
<?
$count++;
}
mysql_fetch_array() only goes through the results of a given query once. Since you're not executing the title_list query every time though your contact list loop, it's still at the end of the query results when you start every iteration after the first.
What you need to do is take all the results from your title_list query, put them into an array, and iterate over that for each of your contacts.
Here's a general example of how you'd do this (with extraneous bits trimmed out):
$contact_list = //some query
$title_list = //some query
$titles = array();
while($title_ar = mysql_fetch_array($title_list)) {
$titles[] = $title_ar;
}
while($contact_ar = mysql_fetch_array($contact_list)) {
// some stuff
foreach($titles as $title) {
// do something with each title
}
}
you should put the rows in a variable and echo that after the while loop.
once the inner while loop executes once fully, you wont get any more values in that mysql_fetch_array call again. Since the cursor reached the end of rows.
You should store the results of the inner while loop into a php array and then iterate through this array every time within the inner while loop.

msql fetch array no longer listing all results

I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.

Categories