<?
$tablae = mysql_query("SELECT * FROM order_history where (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "' GROUP BY user_id");
while ($order = mysql_fetch_array($tablae)) {
?>
<tr>
<?
$tablaes = mysql_query("SELECT * FROM members where id='$order[user_id]'");
$user = mysql_fetch_array($tablaes);
$idsd=$user['id'];
$rPaid=mysql_query("SELECT SUM(`price`) AS total FROM order_history WHERE (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "'");
$hdPaid = mysql_fetch_array($rPaid);
$sPaid=mysql_query("SELECT SUM(`price`) AS total FROM order_history WHERE user_id='$idsd' AND (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "'");
while ($hPaid = mysql_fetch_array($sPaid)) {
?>
<td><?=$user['username']?></td>
<td><?=$hPaid['total']?></td>
<?
}
?>
</tr>
<? } ?>
This gets me this result http://dl.dropbox.com/u/14384295/test.jpeg
I want to order the price totals by DESC.
I would need
$sPaid=mysql_query("SELECT SUM(`price`) AS total FROM order_history WHERE user_id='$idsd' AND (type!='rent_referral' AND type!='rental_balance') AND date>'" . strtotime($time1) . "' AND date<'" . strtotime($time2) . "'");
the total on that to be ordered by DESC.
Be really carefull with GROUP BY instructions in your SQL query. All columns which are in the result and which are not aggregate expressions (expressions would be the count, SUM, max, etc working on the group and not on the rows) should be in your group by expression;
Here you use a select *, you should try to list the real columns instead, and get this list in your group by, or use only SELECT user_id.
Most database would prevent you of running such not-very-well-formted group by query, but MySQl is not bailing you, tthat does not mean he won't gives you completly wrong results if you do not rexpect this rule (all columns which are not aggregates must be in the group by).
Then you should be able to order by an agregate expression by reusing this expression and not his alias in the order clause.
You could either use client side sorting with javascript, there are some nice jQuery addons that can do that.
Or you have to totaly rewrite your code to have a single sql using joins and group by.
But I cannot realy follow the logic with $rPaid, $hPaid and $sPaid so I cannot help you there.
Related
Trying to join this table, so that i can change the code if the tutor ID matches the session tutor ID. But it shows multiple results in the calendar that its generating.
Below is the current PHP code, although the entries are being duplicated due to having multiple tutor ID's within the table. i'm not sure how to change this.
<?php
$sqlAssignments = "SELECT * FROM tbl_assignments LEFT JOIN tbl_tutorModules ON tbl_assignments.module_code = tbl_tutorModules.module_code"; //
$qryAssignments = mysqli_query($con, $sqlAssignments); // running the query
while($rowAssignment = mysqli_fetch_assoc($qryAssignments)){
if ($_SESSION["ID"] == $rowAssignment['tutor_id']) {
echo "{ title: '" . $rowAssignment['assignment_name'] . "', start: '" . $rowAssignment['hand_in_date'] . "', end: '" . $rowAssignment['hand_in_date'] . "', url: 'view/assignments.php?id=" . $rowAssignment['assignment_id'] . "', color: '#f1f1f1'},";
} else {
echo "{ title: '" . $rowAssignment['assignment_name'] . "', start: '" . $rowAssignment['hand_in_date'] . "', end: '" . $rowAssignment['hand_in_date'] . "', url: 'view/assignments.php?id=" . $rowAssignment['assignment_id'] . "'},";
}
}
?>
The actual results at the moment is that when the tutorModules has multiple tutors, the output duplicates calendar results.
Thanks
Edit: Tables look like this with some example data
tbl_tutorModules
con_id module_code tutor_id
2 ISYS30025 1
3 ISYS30025 2
tbl_assignments
assignment_id
module_code
assignment_name
assignment_weight
set_date
hand_in_date
hand_in_method
assignment_type
This is the current output
The expected output is for these not to be duplicated.
You want to know whether a certain tutor is involved in an assignment. So pass the tutor ID to the DBMS in order to let it find out in a query.
SELECT
assignment_id, assignment_name, hand_in_date,
case when module_code in (SELECT module_code FROM tbl_tutorModules WHERE tutor_id = ?)
then 'yes' else 'no'
end as tutor_involved
FROM tbl_assignments
ORDER BY assignment_id;
As you can see, I don't join the tables, because I'm not interested in the joined result. I merely want to look up a record in tbl_tutorModules. We use IN or EXISTS in SQL to look up records in another table.
See here how to pass parameters to the DBMS in mysqli: http://php.net/manual/en/mysqli.prepare.php
I'm trying to select all of the products that a user has purchased from my site, based on an order ID.
$orderid = mysql_query("SELECT MAX(orders_id) FROM orders") or die(mysql_error());
$orderid = mysql_fetch_row($orderid);
$productinfo = mysql_query("SELECT products_model, products_name, products_price, products_quantity FROM orders_products WHERE orders_id=" . $orderid[0]);
$productinfo = mysql_fetch_row($productinfo);
echo $productinfo[0] . " | " . $productinfo[1] . " | $" . $productinfo[2] . " | " . $productinfo[3] . "<br><br>";
This will pull one product from the database, but if the customer ordered 8 items, I would need this to loop until all of the products with an order ID of $orderid[0] have been selected. What would be the best way to go about this? Any help is appreciated!
A few things.
First, everyone here will tell you to look into using mysqli or pdo as an alternative to mysql_query, as they are much more secure, and actually easier to maintain and use.
See this article:
http://www.pontikis.net/blog/how-to-use-php-improved-mysqli-extension-and-why-you-should
Second, you could easily cut down your code by writing more efficient queries.
In this case you would want to use a SQL JOIN. (more about joins here http://www.sitepoint.com/understanding-sql-joins-mysql-database/)
SELECT products_model, products_name, products_price, products_quantity
FROM orders_products as products
JOIN orders as orders on products.order_id = order.order_id
WHERE products.order_id = {whatever order id you are trying to find}
This will give you all products that have been ordered for each order id.
And use a while loop to loop through all of your results that come out of your query
I want to make a voting list kind of thing. I have a form that saves the entered data to mysql database. Suppose a user entered "Something". It'll be saved in column called "bname". Now what I want is Suppose 10 people entered "Something" or "something"(case sensitivity to be ignored automatically if there is a way?) then I want: "Something - 10" to be printed in php page.
My try:
$query="SELECT bname, count
FROM brandnames
GROUP BY bname
HAVING COUNT(*) > 0
LIMIT 11";
$result=mysqli_query($con,$query) or die('Error!: ' . mysqli_error($con));
$query2="SELECT count
FROM brandnames
GROUP BY count
HAVING COUNT(*) > 0
ORDER BY count DESC
LIMIT 11";
$result2=mysqli_query($con,$query2) or die('Counting Error!: ' . mysqli_error($con));
while ($row=mysqli_fetch_assoc($result))
{
while ($row2=mysqli_fetch_assoc($result2))
{
echo ($row['bname'] . ' ' . '-' . ' ' . $row2['count'] . '<br />');
}
}
This thing prints
Something - 4
Something - 3
I do not want to use this method. I posted this as if I don't post someone will point me out to post. :/
I don't want to use "count" column. I want a simple voting list as I mentioned above.
Thanks, :)
The query your looking for should be something like
select bname, count(*) as nbr
from brandnames
group by bname
order by nbr desc
limit 11;
count(*) will return the number of rows that was grouped together by bname. Case sensitivity is depending on your coalition. If it's a case sensitive coaltion you need to group by lower(bname) instead. Be aware thou that this might prevent indexes from working for this query.
Thanks all of you. I got to know how to do this. Hope this helps someone :)
Special thanks to #Andreas Wederbrand
<?php
//Create Connection
$query="SELECT columnname, count(*)
AS alias
FROM tablename
GROUP BY columnname
ORDER BY alias DESC";
$result=mysqli_query($con,$query) or die('Counting Error!: ' . mysqli_error($con));
while ($row=mysqli_fetch_array($result))
{
echo ($row['columnname'] . ' ' . '-' . ' ' . $row['alias'] . '<br />');
}
//Close Connection
?>
any ideas how to get orderTotal and orderId inside the tpl_checkout_success_default for the conversions tracking purposes ?
So far it looks like order id can be accessed by using this variable $zv_orders_id but how to get order total ?
will this code work:
$orders_query = "SELECT * FROM zen_orders WHERE orders_id = " . $zv_orders_id ." LIMIT 1";
$orders = $db->Execute($orders_query);
$order_total = $orders->fields['order_total'];
many thanks,
cheers
look in /includes/modules/pages/checkout_success/header_php.php
in there you will see the queries already being run by zencart to do with your order, and id say its already pulling out the info you want.
so you just need to set said data you need to a variable that you can then use in your tpl_checkout_success_default.php file.
eg, something like $customer_has_gv_balance, you will see where it is set in the hearder file and then used in the template file
heres something i found in order.php that would almost do it as is:
$order_total_query = "select text, value
from " . TABLE_ORDERS_TOTAL . "
where orders_id = '" . (int)$order_id . "'
and class = 'ot_total'";
$order_total = $db->Execute($order_total_query);
For a simple tracking code like one used for a shopping comparison site, I've used the following for the order ID and order amount. Use these in the tpl_checkout_success.php page
Order ID:
echo $zv_orders_id;
Use this select statement:
$to_send_sql = 'select REPLACE (text,"$","") text from orders_total where orders_id = '.$zv_orders_id.' and class = "ot_subtotal"';
$to_send= $db->Execute($to_send_sql);
Order amount:
echo $to_send->fields['text'];
Hope this helps someone!
Looking for some advice on the best way to accomplish this. I've tried Unions, Joins, and Alias examples from a few Stack Overflow questions - none seems to get me where I want to go to no fault of theirs. I think I've just been looking to solve this the wrong way.
I've got one table that logs all activity from our users. Each log contains a column with an ID and another with a TIMESTAMP. There is no column that states what the event type is.
What I'm looking to do is grab counts within a range and append a virtual column with the activation date (first access) regardless if it is in the range or not. The business case for this is that I'd like to have reports that show users active within a range, their activation date, and the amount of events in the range.
The HTML output of this would look like this:
User / Total Visits in the Range / First Visit (in the range or not) / Most Recent Visit (in the range)
How I've gotten this far is by doing this:
$result = mysql_query("
SELECT user, MIN(timestamp), MAX(timestamp), count(user)
AS tagCount FROM " . $table . "
WHERE date(timestamp) BETWEEN '" . $startdate . "' AND '" . $enddate . "'
GROUP BY user
ORDER BY " . $orderby . " " . $order) or die(mysql_error());
I then loop:
$i = 1;
while($row = mysql_fetch_array($result)){
$user_name = str_replace("www.", "", $row['user']); // removing www from usernames
if( $i % 2 != 0) // used for alternating row colors
$iclass = "row";
else
$iclass = "row-bg";
echo "<div class=\"" . $iclass . "\"><div class=\"number\">" . $i . "</div><div class=\"number\">" . $row['tagCount'] . "</div><div class=\"name\">" . "" . $server_name . "" . "</div>" . "<div class=\"first\">" . $row['MIN(timestamp)'] . "</div><div class=\"recent\">" . $row['MAX(timestamp)'] . "</div></div>";
$i++;
}
The MIN(timestamp) in the above grabs the first timestamp in the range - I want to grab the first timestamp regardless of range.
How can I do this?
The key is to create a virtual derived table that calculates their first access separately and then join to it from your query that returns records for the time period you specify.
The below is SQL Server code, but I think it's fine in mysql too. If not, let me know and i'll edit the syntax. The concept is sound either way though.
Just setup code for the sample
if object_id('tempdb..#eventlog') is not null
drop table #eventlog
create table #eventlog
(
userid int ,
eventtimestamp datetime
)
insert #eventlog
select 1,'2011-02-15'
UNION
select 1,'2011-02-16'
UNION
select 1,'2011-02-17'
UNION
select 2,'2011-04-18'
UNION
select 2,'2011-04-20'
UNION
select 2,'2011-04-21'
declare #StartDate datetime
declare #EndDate datetime
set #StartDate = '02-16-2011'
set #EndDate = '05-16-2011'
Here's the code that would solve your problem, you can replace #eventlog with your tablename
select e.userid,
min(eventtimestamp)as FirstVisitInRange,
max(eventtimestamp) as MostRecentVisitInRange,
min(e2.FirstAccess) as FirstAccessEver,
count(e.userid) as EventCountInRange
from #eventlog e
inner join
(select userid,min(eventtimestamp) as FirstAccess
from #eventlog
group by userid
) e2 on e.userid = e2.userid
where
e.eventtimestamp between #StartDate and #EndDate
group by e.userid