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.
Related
I've written a PHP script that can populate a table in a particular way so that multiple events (or no events) can be put in one square in an HTML - similar to the layout a calendar would have. But, there's a problem, the while statement I created to fill in squares in the table when there is no data doesn't detect when there is data, and fills the entire table with empty squares. This is what the output looks like (The page is styled using Bootstrap 3). From the mysql data I have provided, these events should be in the square at {Period 1, Monday}.
Here is my data in a mysql database; mysql data
Here is a snippet of the part of the page related to this table;
<?php
$query = "SELECT * FROM configtimetabletwo WHERE term = ".$term." AND week = ".$week." ORDER BY period, day LIMIT 100;";
$results = mysqli_query($conn, $query);
$pp=1; //The current y value of the table
$pd=0; //The current x value of the table
echo '<tr><td>';
while($row = mysqli_fetch_row($results)) {
while((pd!=$row[3] or $pp!=$row[4]) and $pp<6){ //This while statement fills in empty squares and numbers each row.
if($pd==0) {
echo $pp."</td><td>";
$pd++;
}
elseif($pd<5){
echo "</td><td>";
$pd++;
}
else {
echo "</td></tr><tr><td>";
$pd=0;
$pp++;
}
}
echo '<a href="?edit='.$row[0].'" class="label label-default">';
echo $row[5].' '.$row[6].' - '.$row[7]."</a><br>";
}
echo "</td></tr></table>"
?>
I haven't been able to figure out why this happens so far, thanks in advance to anyone who has any idea what's going on.
In the comments below my question, pavlovich pointed out the error. In this case, it was simply an issue of forgetting to use a $ to reference a variable. It would seem that this doesn't throw an error in a while statement like it would elsewhere.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to fill 3 different tables in my database.
Sale table which has the following rows:
sale_id
fk_sale_user
fk_payment_id
sale_date
Print_for_sale which has:
print_for_sale_id
fk_sale_id
price_print_for_sale
Print_has_size_has_print_for_sale
print_has_size_has_print_for_sale_id
fk_print_has_size_id
fk_print_for_sale_id
Here is a screenshot of my database in mysql workbench so you can situate.
I'm trying to make the "buying" action.
This is my markup and php code:
printdetail.php
<?php
$id= $_GET['print_id'];
$printdetails = getprintdetailsById($con, $id);
$line = mysql_fetch_assoc($printdetails);
$selectsize =" select * from size";
$result=mysql_query($selectsize);
?>
<div>
<img width="800px;"src="<?php echo $line['print_img']?>"/>
</div>
<div>
<span> <?php echo $line['print_title']?> </span>
<form action="addprints.php" method="post">
<ul>
<?php while ($line = mysql_fetch_assoc($result)) { ?>
<li> <input type="checkbox" name="sizes[]" value="<?php echo $line['size_id']?>">
<?php echo $line['size_name']." Price: ".$line['size_price']."€ "?>
</li>
<?php } ?>
<input type="submit" value="Add to Cart" >
</ul>
<input type="hidden" name="print_id" value="<?php echo $id; ?>" />
</form>
</div>
addprints.php
<?php
session_start();
$user_id = $_SESSION['user_id'];
print_r($_POST);
$id_print= $_POST['print_id'];
include('database.php');
$bought_sizes=$_POST['sizes'];
$number_of_bought_sizes= count($bought_sizes);
//header('location:index.php?area=printstore');
$sqlinsertsale = "insert into sale
(fk_sale_user,
fk_payment_id)
values(".$user_id.", 2)";
mysql_query($sqlinsertsale);
for($i=0; $i< $number_of_bought_sizes; $i++){
$selectsize = "select *
from size";
$resultsize = mysql_query($selectsize);
while($linesize = mysql_fetch_assoc($resultsize))
{ $size_price = $linesize["size_price"]; }
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
while($linesale = mysql_fetch_assoc($resultsale))
{ $sale_id = $linesale["sale_id"]; }
$sqlinsertprintforsale = "insert into print_for_sale
(fk_sale_id,
price_print_for_sale)
values(".$sale_id.", ".$size_price.")";
mysql_query($sqlinsertprintforsale);
$selectprinthassize = "select *
from print_has_size";
$resultprinthassize = mysql_query($selectprinthassize);
while($lineprinthassize = mysql_fetch_assoc($resultprinthassize))
{ $print_has_size_id = $lineprinthassize["print_has_size_id"]; }
$selectprintforsale = "select *
from print_for_sale";
$resultprintforsale = mysql_query($selectprintforsale);
while($lineprintforsale = mysql_fetch_assoc($resultprintforsale))
{ $print_for_sale_id = $lineprintforsale["print_for_sale_id"]; }
$sqlinserthashas = "insert into print_has_size_has_print_for_sale
(fk_print_has_size_id,
fk_print_for_sale_id)
values(".$print_has_size_id.", ".$print_for_sale_id.")";
mysql_query($sqlinserthashas);
}
?>
I am very new to php and mysql so I'm sorry if this is a dumb or bad question. I can't figure out what I'm doing wrong...
The table Sale is being updated correctly in phpmyadmin. Everything is working. User ID is OK and payment ID is OK too. (I haven't done the payments part yet so I just used a number to test.)
The table Print_for_sale is updating the correct sale ID (fk_sale_id), however the price_print_for_sale is always the same, no matter what print I choose. It's always 150 when sometimes it should be 65 ou 25.
(The print price is defined in the size table. So far I have 3 different sizes, so different prices.)
The table Print_has_size_has_print_for_sale is updating the correct print_for_sale ID, but the fk_print_has_size_id is always number 12 (which is the last from that list) and it has nothing to do with my choices on the form. I believe this is what is making the price come out wrong. If it's always the same combination of prints and size (print_has_size), then it's always going to have the same price... Why is this happening?
Can someone please help me?
Here are some screenshots of phpmyadmin:
Edit: This is the function I used:
<?php
function getprintdetailsById($con, $print_id){
$question = "select * from print where print_id=".$print_id;
$result = mysql_query($question, $con);
return $result;
}
?>
This is a lot of info.. I guess we can start debugging. Let's begin with your while loops. Inside your for loop, the first line select * from size, this should return an array, then you are iterating this array with your while loop, but you are assigning them to just one variable. This will overwrite the data result of the last iteration. Is this what you want?... to be continued.
You don't want that to be overwritten.. so what you need to do for that while loop is assign it to an array, like this:
while ($linesize = mysql_fetch_assoc($resultsize)) {
$size_price[] = $linesize["size_price"];
}
so, once you have the $size_price[] with all the desired sizes, we move on.. your code now runs select * from sale where you want all the sale_ids from. So just like above, assign it to an array, we'll say $sale_ids[]
Now you are trying to run a query that inserts data to the print_for_sale table, but the data comes from the two different arrays you created above.. this is will not work, and if so, you would need to come up with crazy loops and iteration like you already have tried.
To fix it, you first need to look at your tables, assign them unique ids, and link them through indexes, once you do that, you need to use the JOIN SQL command on your queries to get the matched data together.
I would look into separating your code as well. this will help you reuse it. You should look into an MVC framework. Ever heard of Codeigniter? its very easy to learn and powerful for applications.
Hope this helps.
Your code could use work, but I think that your problem is a misplaced bracket at the end. It should be:
while($lineprinthassize = mysql_fetch_assoc($resultprinthassize))
{
$print_has_size_id = $lineprinthassize["print_has_size_id"];
$selectprintforsale = "select *
from print_for_sale";
$resultprintforsale = mysql_query($selectprintforsale);
while($lineprintforsale = mysql_fetch_assoc($resultprintforsale))
{
$print_for_sale_id = $lineprintforsale["print_for_sale_id"];
$sqlinserthashas = "insert into print_has_size_has_print_for_sale
(fk_print_has_size_id,
fk_print_for_sale_id)
values(".$print_has_size_id.", ".$print_for_sale_id.")";
mysql_query($sqlinserthashas);
}
}
The replace code should be in the loop. In your original code, you looped through all the values, ending with the last one, and then used it.
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.
i don't know a lot of php but, i have the following code, it will load all images from the top of the table to the bottom, can i invert this process? load from de bottom to top? I need the ordest lines to be loaded first...
<?php
mysql_connect("localhost","root","");
mysql_select_db("bravo");
$res=mysql_query("select * from coisas");
?>
<div>
<?php
while ($row=mysql_fetch_array($res)) {
echo "<img src=\"{$row['imagem']}\">";
}
?>
</div>
If your table have one identifier column you can do that (assuming id is the identifier column name):
<?php
mysql_connect("localhost","root","");
mysql_select_db("bravo");
$res=mysql_query("SELECT * FROM coisas ORDER BY id DESC");
?>
<div>
<?php
while ($row=mysql_fetch_array($res)) {
echo "<img src=\"{$row['imagem']}\">";
}
?>
</div>
As Mark Baker correctly say, let SQL do it for you with a ORDER BY.
If you still want to do this in PHP, use this snippet of code:
<?php
$html = '';
while ($row=mysql_fetch_array($res)) {
html = "<img src=\"{$row['imagem']}\">".$html;
}
echo $html;
?>
This will concatenate your current (of the loop) fetched array entry with previous one. So, the first will be concatenated before the last (read it as inversed order).
Moreover, don't use msql_* as those functions are deprecated. Use msqli_* or PDO instead
PS.: This code is your code revisited, if there is any error (in fetching array, connection or so) please correct it your own: I only give you a pointer
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.