0

Is there a faster way to do this?

$data1 = mysql_query(
 "SELECT * FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error()); 

$num_results = mysql_num_rows($data1); 
$data2 = mysql_query(
 "SELECT sum(type) as total_type FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error()); 

while($info = mysql_fetch_array( $data2 )){
    $count = $info['total_type'];
} 
$total = number_format(($count/$num_results), 2, ',', ' ');
echo $total;

Cheers!

5 Answers 5

1

Looking at your queries, I think you're looking for something like this:

SELECT SUM(type) / COUNT(*) FROM table1 WHERE ...
Sign up to request clarification or add additional context in comments.

Comments

0
 SELECT COUNT(*) AS num_results, SUM(type) AS total_type FROM table1
    WHERE id = $id and type = $type

This single query will produce a one-row result set with both values that you want.

Note that you should use a parameterized query instead of direct variable substitution to avoid SQL injection attacks.

Also, I'm guessing that SUM(type) isn't what you really want to do, since you could calculate it as (num_results * $type) without the second query.

5 Comments

This is what I'm after thank you, could you specify the parameterized query issue please?
If, for instance, the $type field comes from user input and the user were to type "13; DELETE FROM Users" in that field, you can see what would happen. By specifying the query with parameters (something like WHERE ID = @id AND type = @type, but it depends on your database library) and then binding properly typed values to the parameters you are safe against this kind of attack.
He would get an error, but nothing would be deleted. mysql_query() will not execute more than one query.
@Dan: Obviously, I'm not a php expert. Is mysql_query injection-proof?
You can still alter the query in malicious ways (set $type to "something OR 1=1"?), you just can't inject a second query to run.
0
$data1 = mysql_query("SELECT sum(type) as total_type,count(*) as num_rows FROM table1 WHERE id='$id' AND type='$type'"
) or die(mysql_error()); 
$info = mysql_fetch_array( $data1 );
$count = $info['total_type'];
$num_results = $info['num_rows'];
$total = ($count/$num_results); 
echo $total;

Comments

0

In general: SELECT * can be 'shortened' to e.g. SELECT COUNT(*), if all you care about is the number of matching rows.

2 Comments

COUNT(*) is slightly better (since it doesn't rely on the field data, as it is for COUNT(id))
No way to JOIN the two queries then?
0

One line:

echo number_format(mysql_result(mysql_query("SELECT SUM(type) / COUNT(*) FROM table1 WHRE id = $id AND type = '$type'"), 0), 2, ',', ' ');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.