faster mysql query - php

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!

Looking at your queries, I think you're looking for something like this:
SELECT SUM(type) / COUNT(*) FROM table1 WHERE ...

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.

$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;

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

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

Related

PHP SQL get SELECT COUNT(user) to variable

How do I get the outcome of
SELECT COUNT(user) FROM game_paths WHERE user = '$user'
to a PHP variable
I tried
mysql_num_rows
but it returns nothing.
You should use mysql_result and get the first column of the result. Like this:
$result = mysql_query("SELECT COUNT(user) FROM game_paths WHERE user='$user'");
$count = mysql_result($result, 0);
You can also alias the column like this:
$result = mysql_query("SELECT COUNT(user) AS total FROM game_paths WHERE user='$user'");
$data = mysql_fetch_assoc($result);
$count = $data['total'];
Which might be better if you're going to select several columns at the same time, and also for readability.
Try like this. you need to use mysql_fetch_assoc or mysql_fetch_array functions
$result = mysql_query(" SELECT COUNT(user) as total FROM game_paths WHERE user='$user' ");
$row = mysql_fetch_assoc($result);
echo $row['total'];
Or
$result = mysql_query(" SELECT COUNT(user) FROM game_paths WHERE user='$user' ");
$row = mysql_fetch_array($result);
echo $row[0];
Docs Link: http://us2.php.net/mysql_fetch_array
http://www.w3schools.com/php/func_mysql_fetch_array.asp
Note: mysql_* function are deprecated try to use mysqli or PDO
You can use the following code:
$result = mysql_query(" SELECT COUNT(user) FROM game_paths WHERE user='$user' ");
$row = mysql_fetch_array($result);
$count= $row[0];
or
$result = mysql_query("SELECT * FROM game_paths WHERE user='$user'");
$count=mysql_num_rows($result);
This will return the number of rows satisying the condition.
Hey friend Try this code, ithink this will solve your problem
<?php
$con=mysql_connect('hostname','DBusername','paassword');
mysql_select_db('Db_name',$conn);
$query="SELECT COUNT(user) as total FROM game_paths WHERE user='$user'";
$result=mysql_query($query,$con);
$row=mysql_fetch_array($result);
echo $row['total'];
?>
$result = mysqli_query("SELECT COUNT(user) AS user_count FROM game_paths WHERE user='$user'");
$result_array = mysql_fetch_assoc($result);
$user_count=$result_array['user_count'];
Please use mysqli_ instead of mysql_ as its deprecated in the new version

PHP MySQL with two query

I need to do a SELECT * FROM table_X , the problem is table_X is the result of another query, I don't know how to do it, perhaps with two loop, something like this :
<?php
$query1 = mysql_query("SELECT * FROM table_ref");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query(" SELECT * FROM '$name' ");
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
?>
The tables are all similar & I can't do joint there's no keys. So what I want is to show only the results of the second query from each results of the first query !
So, what's your structure? I don't understand. You have column table_name where are listed a lot of tables? If so, just use backquotes on your $name:
$query2 = mysql_query(" SELECT * FROM `$name` ");
Apart from the obvious that has been pointed out in the comments, you're overwriting $row in the second loop.
Also, you're trying to read an array ($data) that is not defined.
The following will work much better (but still isn't ideal):
$query1 = mysql_query("SELECT `table_name` FROM `table_ref`");
while ($row = mysql_fetch_array($query1))
{
$name = $row['table_name'];
$query2 = mysql_query("SELECT `itime` FROM `$name`");
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
}
just change your quotes to have the query ready to be started
change
$query2 = mysql_query(" SELECT * FROM '$name' ");
to
$query2 = mysql_query(" SELECT * FROM `".$name."` ");
i would also rather sugest to check this part
while ($row = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
you already used variable $row to fetching previus query so better to change to something else, look like $data is matching your needs because you already used but you did not declare it
while ($data = mysql_fetch_array($query2))
{
$time = $data['itime'];
echo $time;
}
Try this query:
select x.* from ( SELECT table_name FROM table_ref) as x

How do I use the results of a SQL query in a subsequent query?

I want to use the result set of a query in the where statement of a subsequent query.
Running into a problem because the first query returns multiple results and I don't know how to convert these to a comma-separated string for use in an 'IN' () statement.
$Result1 = mysql_query ("
select id from Table1
where
upper('$Input') = Employee_number
")
or die(mysql_error());
$Result2 = mysql_query ("
Select * from table2 where ID in ($Result1)")
You can combine this into a single MySQL statement like this:
SELECT * FROM Table2 WHERE id IN
(SELECT id FROM Table1 where upper('$Input') = Employee_number);
But if you really want to do it like in your question, you will probably have to lookup how to work with the results from mysql_query, just look that up in a function reference.
$query1 = mysql_query("
select id from Table1
where upper('$Input') = Employee_number
") or die(mysql_error());
$ids = array();
while($Result1 = mysql_fetch_array($query1))
{
$ids[] = $Result1['id'];
}
if(sizeof($ids))
{
$n_ids = implode(',', $ids);
$query2 = mysql_query("
select * from Table2
where ID IN (" . $n_ids . ")
") or die(mysql_error());
}

Conditional counting of records

Am trying to calculate the number of rows in a table depending on a certain condition.
So, I did manage to write a piece of code that would function as required.
But, it's bit too long. So am wondering if there is any easier way to achieve it.
Code:
// Comments
$sql_total_comments = mysql_query("SELECT * FROM comments");
$sql_pending_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '0'");
$sql_approved_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '1'");
$sql_declined_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '2'");
$total_comments_num = mysql_num_rows($sql_total_comments);
$pending_comments_num = mysql_num_rows($sql_pending_comments);
$approved_comments_num = mysql_num_rows($sql_approved_comments);
$declined_comments_num = mysql_num_rows($sql_declined_comments);
SELECT comment_status, COUNT(comment_status)
FROM comments GROUP BY comment_status;
In your code, either total the counts up for the total number or run a separate query on COUNT(*) as in the other answers.
So your code would look something like this, assuming you're using PDO:
$sql = 'SELECT comment_status, COUNT(comment_status) AS "count" '.
'FROM comments GROUP BY comment_status;';
$query = $db->query($sql);
$count_total = 0;
$count = array( );
while (($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$count_total += $row['count'];
$count[$row['comment_status']] += $row['count'];
}
$query = null; // Because I'm neurotic about cleaning up resources.
Use COUNT() DB FUNCTION to do such job.
$ret = mysql_query("SELECT COUNT(*) FROM comments");
$row = mysql_fetch_row($ret);
$total_comments_num = $row[0];
Use select count(*) from comments where .....

PHP variables in WHERE clause, how to?

I have following PHP script. I want to count and print comments for each article.
The id for each article can be "recalled" by this: <?php echo $listing['Listing']['listing_id'];?> (this return the contentid number)
Now, I have this script:
<?php
$db =& JFactory::getDBO();
$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ????? ";
$db->setQuery($query);
$count = $db->loadResult();
echo ($count); ?>
I tried to add in WHERE clause this:
"... WHERE contentid = {$listing['Listing']['listing_id']}"
but $count returns "0" zero.
How can I add this variable in the WHERE clause?
Thanks in advance!
In the case of an integer:
$query = "SELECT
COUNT(comments) AS totalcount
WHERE
contentid = " . ((int) $listing['Listing']['listing_id']);
In the case of a string:
$query = "SELECT
COUNT(comments) AS totalcount
WHERE
contentid = " . mysql_real_escape_string($listing['Listing']['listing_id']);
The biggest thing to be weary of is SQL injection. This makes your queries safe. The explicit cast to int will ensure an int value is passed, even if the value is erroneous, at least you wont be open to any attack.
Use sprintf and escape the string.
$query = sprintf("SELECT COUNT(comments) AS totalcount WHERE contentid = '%s'",mysql_real_escape_string($listing['Listing']['listing_id']));
try
$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = '".mysql_real_escape_string($listing['Listing']['listing_id'])."'";
or
$query = "SELECT COUNT(comments) AS totalcount WHERE contentid = ".mysql_real_escape_string($listing['Listing']['listing_id']);
depending on the data type.

Categories