How to use avg function? - php

I'm new at php and mysql stuff and i'm trying to use an avg function but i don't know how to.
I'm trying to do something like this:
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die ("Did not connect to $database");
mysql_query("AVG(column1) FROM table1 ") or die(mysql_error());
mysql_close();
echo AVG(column1);
(Q1)I'd like to see the value printed in the screen, but i'm getting nothing but an error message. How could I print this average on the screen ?
(Q2)If I had a column month in my table1, how could I print the averages by the months ?
Sorry for any bad English, and thanks for the attention.

Solution for Q1: SELECT AVG(column1) FROM table1
Solution for Q2: SELECT AVG(column1), month FROM table1 GROUP BY month

What to read?
MySQL SELECT syntax
MySQL AVG() function - there is even an example of exactly what you need
PHP mysql_fetch_assoc() function which is one of several ways to retrieve data from result set
btw: PDO is much better for database communication in PHP
Ad. 1:
$sql = 'SELECT AVG(col_name_1) AS avgColName FROM tbl_name;';
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
var_dump($result['avgColName']);
Ad. 2:
SELECT ... FROM ... GROUP BY MONTH(date_col_name);

You need to return the result of the query into a variable which you can then use.
For example:
$query = "AVG(column1) FROM table1";
$result = mysql_query($query);
// Print out result
while($row = mysql_fetch_array($result)) {
echo $row['AVG(column1)'];
}

Related

Display the amount of Paid items in my database using php

I am using php and mysql to create a page that displays all of the jobs we have in the database. The data is shown is a table and when a row is clicked a modal window triggers with the information of the clicked job inside. At the top of the page I want a simple counter that shows amount of paid jobs, invoiced jobs etc etc. I am using the code below but having no luck...
<?php
$con = mysql_connect("localhost","databaseusername","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databasename", $con);
$result = mysql_query("select count(1) FROM jobslist");
$row = mysql_fetch_array($result);
$total = $row[0];
mysql_close($con);
?>
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0. No matter what I try I can't seem to get it to count the amount of 'paid' items in the database or 'invoiced' etc etc.
Once the count function is complete currently I am echoing out the outcome as below:
<?php echo "" . $total;?>
I am sure I am overlooking something simple, but any help is appreciated.
EDIT: TABLE STRUCTURE INCLUDED
http://i.stack.imgur.com/hcMJV.png
Assuming a column called paid you could restructure the query similar to the following. If you needed to sum the amounts involved that requires additional tweaking.
$result = mysql_query("select
( select count(*) from `jobslist` where `paid`=1 ) as 'paid',
( select count(*) from `jobslist` where `paid`=0 ) as 'unpaid'
from jobslist");
$rows = mysql_num_rows( $result );
while( $rs=mysql_fetch_object( $result ) ){
$paid=$rs->paid;
$unpaid=$rs->unpaid;
echo 'Total: '.$rows.'Paid: '. $paid.' Unpaid: '.$unpaid;
}
When I do this I usually name the COUNT result. Try this out:
$result = mysql_query("SELECT COUNT(*) AS total_rows FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['total_rows'];
If you do not want to name the COUNT result, then give the following a go:
$result = mysql_query("SELECT COUNT(*) FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['COUNT(*)'];
select count(1) FROM jobslist
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0.
No, this is just counting rows in your table and not filtering. If you want to count something with a specific filter you have to add that filter condition:
SELECT COUNT(*) AS `MyCount`
FROM `joblist`
WHERE `MyColumn` = 1; -- assuming MyColumn contains the INT you're looking for
You should stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
First you should change deprecated mysql_... to mysqli_... (look here how to). But it's not the reason you fail.
Unlike you seem to suppose, COUNT(1) will not look for an INT column having value 1.
Instead you must use COUNT(*) or COUNT(a_column_name) (same result), with adding a WHERE clause stating which condition is involved.
Here you seem wanting to count records where a given column (say the_column) has value 1. So you should:
SELECT COUNT(*)
FROM jobslist
WHERE the_column = 1
Last point: you don't need echo "" . in <?php echo "" . $total;?>.
Merely write <?php echo $total;?>.

Get the count of the mysql query results in php

I would like to get the count of the mysql query results in php.
The query usually returns up to 10 rows.
Which one in the below is better to use:
1.
$query = "SELECT * FROM test_table WHERE test_no=12345";
$queryResult = $db->query($query);
$count = $queryResult->size();
if($count < 5){}
2.
$query = "SELECT COUNT(test) AS count FROM test_table WHERE test_no=12345";
$queryResult = $db->query($query);
$result = $queryResult->fetch();
if($result['count'] < 5){}
Also, please let me know if there is another better way to use it
$query = 'SELECT COUNT(1) FROM test_table WHERE test_no=12345';
$queryResult = $db->query($query);
$count = $queryResult->fetchColumn();
This is the best way, assuming you are using PDO. Do not specify a column name in COUNT(), use * or 1. Then use fetchColumn() to get the first column's data.
It's probably better to let MySQL handle row counting. This is more important when large amounts of data are in play. If PHP were in charge of counting the rows, all of that data would need to be sent from MySQL to PHP, only for PHP to then count & discard it. It's better to skip the middle man. So the SELECT COUNT(test) query is the preferable one, of the two choices you provided.
If you're using PDO, the best way is to use PDO's rowCount() method. This methods returns the number of rows returned by the query.
Here's an example.
try
{
$s = $conn->execute("YOUR QUERY HERE");
$count = $s->rowCount();
}
catch(PDOException $e)
{
echo $e->getMessage();
}

mysql and php - dont know how to select and echo

My question is.... i have a table with 2 columns and 24 rows.
first column is only id and it goes from 1 to 24 and second column is some text in each row and follows id.
i don't know how to SELECT text from each row separated by id in first column and echo it.
I am using xampp - mysql and working in php. TY
i tried something like this and than i used variable $row to call row 0. but i think thats not right way.
$nap_query = "SELECT napomena FROM napomena";
$nap_result = mysql_query($nap_query) or die (mysql_error());
$row = mysql_fetch_row($nap_result);
You need to look at the php mysql_fetch_array documentation: http://php.net/manual/en/function.mysql-fetch-array.php
As the comments suggest mysql_fetch_row doesn't work for multiple rows.
So you can do that
while($row = mysql_fetch_array($nap_result))
echo $row['napomena'];
Aditions
It's best not to use mysql anymore and use mysqli or prefebly PDO in order to handle database connections. Read PDO and mysqli documentation here.
If you want to get only one row result
$rownum=0; //zero or something
echo mysql_result($nap_result, $rownum, "napomena");
Multi values use mysql_fetch_array
while($row=mysql_fetch_array($nap_result)){
echo $row['napomena'];
}
$nap_query = "SELECT field FROM table";
$nap_result = mysql_query($nap_query) or die (mysql_error());
while($row = mysql_fetch_row($nap_result))
echo $row['field'].'<br/>';
This will result like this
resultA
resultB
resultC
etc
Just like #punitha said, it's better to use PDO

PHP & MySQL: How can I use "SET #rank=0;" in $query=

In my PHP file, I use this line to pull data from my mySQL database:
$query = "SET #rank=0; SELECT #rank:=#rank +1 as rank, Blah Blah...";
If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.
But, if I use it in PHP, then I get an error. It doesn't like the "SET #rank=0;" bit. Is there a way to use "SET #rank=0;" when it's in "$query=" ? Is there a workaround?
The rest of the code is standard stuff for pulling data from a db:
public function getmyData() {
$mysql = mysql_connect(connection stuff);
$query = "SELECT #rank:=#rank +1 as rank, formatted_school_name, blah blah";
$result = mysql_query($query);
$ret = array();
while ($row = mysql_fetch_object($result)) {
$tmp = new VOmyData1();
$tmp->stuff1 = $row-> stuff1;
$tmp->stuff2 = $row->stuff2;
$ret[] = $tmp;
}
mysql_free_result($result);
return $ret;
}
Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:
$query = "SET #rank = 0";
$query .= "SELECT #rank:=#rank +1 as rank...
I changed the result to:
$result = $mysqli_multi_query($query);
But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?
This guy here seems to have a way of setting the variable in the same query to zero. I don't have MySQL set on up on this machine to try it, though.
Here's the query he suggests in his blog post:
select #rownum:=#rownum+1 ‘rank’, p.* from player p, (SELECT #rownum:=0) r order by score desc limit 10;
(Is there some homework assignment coming due somewhere having to do with computing ranks? This is the third question I've seen on this in two days.)
Are you checking for duplicate scores?
Try executing it as 2 separate successive queries.
You have to enable the use of multiple queries in one, but i forgot how do do this at the moment. It's a security feature.
Use mysql_multi_query() or rather mysqli_multi_query() instead of mysql_query()

how to return array for mysql_query?

// make empty array
$sqlArray=array();
$jsonArray=array();
// START NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// first 20 vistors
$query = "SELECT user_id FROM vistors LIMIT 20";
$result = mysql_query ($query) or die ($query);
// make vistors user query array
while ($vstr_line = mysql_fetch_array($result)){
array_push($sqlArray, $vstr_line['user_id']);
}
// implode vistors user array
$sqlArray_impl = implode("', '", $sqlArray);
// END NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN ('$sqlArray_impl')";
$qry_result = mysql_query($query) or die($query);
while ($usr_line = mysql_fetch_array($qry_result)){
array_push($jsonArray, $usr_line['id'].' - '.$usr_line['username'].' - '.$usr_line['picture']);
}
print_r($sqlArray);
echo '<br><br>';
print_r($jsonArray);
see this my functions..
i need a replacement for fast working alternatives..
function within the range specified above, to me, running faster than the alternative.
the query will return back array ?
thx for all helpers !
Can you use a JOIN or SUB SELECT to reduce the query count from 2 to 1? Might not give much of a boost but worth a shot and a cleaner implementation.
Where is the bottleneck? Most likely the db and not the php code.
Are the tables/columns properly indexed? Run EXPLAIN on both queries.
Easiest would be to include first query as subquery eliminating one turn to the DB and a lot of code:
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN (SELECT user_id FROM vistors LIMIT 20)";
$qry_result = mysql_query($query) or die($query);
Unless there is more reason to have the first one seperate, but that is not visible in your code example.
If you use PDO (recommended anyway...), you can return the result array all at once using fetchAll().
For your second query, you can use string concatenation in MySQL to directly return the result you want.

Categories