select count(*) from table of mysql in php - php

I am able to get both the value and row of the mysql query result.
But I am struggling to get the single output of a query. e.g.:
$result = mysql_query("SELECT COUNT(*) FROM Students;");
I need the result to display. But I am not getting the result.
I have tried with the following methods:
mysql_fetch_assoc()
mysql_free_result()
mysql_fetch_row()
But I didn't succeed to display (get) the actual value.

You need to alias the aggregate using the as keyword in order to call it from mysql_fetch_assoc
$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];

If you only need the value:
$result = mysql_query("SELECT count(*) from Students;");
echo mysql_result($result, 0);

$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];
Try this code.

Please start using PDO.
mysql_* is deprecated as of PHP 5.5.0 and will be removed entirely in 7. Let's make it easier to upgrade and start using it now.
$dbh = new \PDO($dsn, $user, $password);
$sth = $dbh->prepare('SELECT count(*) as total from Students');
$sth->execute();
print_r($sth->fetchColumn());

here is the code for showing no of rows in the table with PHP
$sql="select count(*) as total from student_table";
$result=mysqli_query($con,$sql);
$data=mysqli_fetch_assoc($result);
echo $data['total'];

$num_result = mysql_query("SELECT count(*) as total_count from Students ") or exit(mysql_error());
$row = mysql_fetch_object($num_result);
echo $row->total_count;

You can as well use this and upgrade to mysqli_ (stop using mysql_* extension...)
$result = mysqli_query($conn, "SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysqli_fetch_array($result);
$count = $row['count'];
echo $count;

With mysql v5.7.20, here is how I was able to get the row count from a table using PHP v7.0.22:
$query = "select count(*) from bigtable";
$qresult = mysqli_query($this->conn, $query);
$row = mysqli_fetch_assoc($qresult);
$count = $row["count(*)"];
echo $count;
The third line will return a structure that looks like this:
array(1) {
["count(*)"]=>string(4) "1570"
}
In which case the ending echo statement will return:
1570

For mysqli users, the code will look like this:
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
$result = $mysqli->query("SELECT COUNT(*) AS Students_count FROM Students")->fetch_array();
var_dump($result['Students_count']);
or:
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
$result = $mysqli->query("SELECT COUNT(*) FROM Students")->fetch_array();
var_dump($result[0]);

$db = new PDO('mysql:host=localhost;dbname=java_db', 'root', 'pass');
$Sql = "SELECT count(*) as `total` FROM users";
$stmt = $db->query($Sql);
$stmt->execute();
$total = $stmt->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($total);
print '</pre>';
Result:

You need to alias the aggregate using the as keyword in order to call it from mysqli_fetch_assoc
$result=mysqli_query($conn,"SELECT count(*) as total from Students");
$data=mysqli_fetch_assoc($result);
echo $data['total'];

$howmanyuser_query=$conn->query('SELECT COUNT(uno) FROM userentry;');
$howmanyuser=$howmanyuser_query->fetch_array(MYSQLI_NUM);
echo $howmanyuser[0];
after the so many hours excellent :)

Related

PHP and MYSQLi list names and count instances from a table [duplicate]

I am able to get both the value and row of the mysql query result.
But I am struggling to get the single output of a query. e.g.:
$result = mysql_query("SELECT COUNT(*) FROM Students;");
I need the result to display. But I am not getting the result.
I have tried with the following methods:
mysql_fetch_assoc()
mysql_free_result()
mysql_fetch_row()
But I didn't succeed to display (get) the actual value.
You need to alias the aggregate using the as keyword in order to call it from mysql_fetch_assoc
$result=mysql_query("SELECT count(*) as total from Students");
$data=mysql_fetch_assoc($result);
echo $data['total'];
If you only need the value:
$result = mysql_query("SELECT count(*) from Students;");
echo mysql_result($result, 0);
$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];
Try this code.
Please start using PDO.
mysql_* is deprecated as of PHP 5.5.0 and will be removed entirely in 7. Let's make it easier to upgrade and start using it now.
$dbh = new \PDO($dsn, $user, $password);
$sth = $dbh->prepare('SELECT count(*) as total from Students');
$sth->execute();
print_r($sth->fetchColumn());
here is the code for showing no of rows in the table with PHP
$sql="select count(*) as total from student_table";
$result=mysqli_query($con,$sql);
$data=mysqli_fetch_assoc($result);
echo $data['total'];
$num_result = mysql_query("SELECT count(*) as total_count from Students ") or exit(mysql_error());
$row = mysql_fetch_object($num_result);
echo $row->total_count;
You can as well use this and upgrade to mysqli_ (stop using mysql_* extension...)
$result = mysqli_query($conn, "SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysqli_fetch_array($result);
$count = $row['count'];
echo $count;
With mysql v5.7.20, here is how I was able to get the row count from a table using PHP v7.0.22:
$query = "select count(*) from bigtable";
$qresult = mysqli_query($this->conn, $query);
$row = mysqli_fetch_assoc($qresult);
$count = $row["count(*)"];
echo $count;
The third line will return a structure that looks like this:
array(1) {
["count(*)"]=>string(4) "1570"
}
In which case the ending echo statement will return:
1570
For mysqli users, the code will look like this:
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
$result = $mysqli->query("SELECT COUNT(*) AS Students_count FROM Students")->fetch_array();
var_dump($result['Students_count']);
or:
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
$result = $mysqli->query("SELECT COUNT(*) FROM Students")->fetch_array();
var_dump($result[0]);
$db = new PDO('mysql:host=localhost;dbname=java_db', 'root', 'pass');
$Sql = "SELECT count(*) as `total` FROM users";
$stmt = $db->query($Sql);
$stmt->execute();
$total = $stmt->fetch(PDO::FETCH_ASSOC);
print '<pre>';
print_r($total);
print '</pre>';
Result:
You need to alias the aggregate using the as keyword in order to call it from mysqli_fetch_assoc
$result=mysqli_query($conn,"SELECT count(*) as total from Students");
$data=mysqli_fetch_assoc($result);
echo $data['total'];
$howmanyuser_query=$conn->query('SELECT COUNT(uno) FROM userentry;');
$howmanyuser=$howmanyuser_query->fetch_array(MYSQLI_NUM);
echo $howmanyuser[0];
after the so many hours excellent :)

MySQL AVG function returning 0

I'm using the code below to query the database.
mysql_query ("SELECT * FROM _$symbol ORDER BY date DESC;");
$_10day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 10;");
$_21day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 21;");
$_50day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 50;");
echo "$_10day\n";
echo "$_21day\n";
echo "$_50day\n";
mysql_query ("INSERT INTO _$symbol(_10day) VALUE ('$_10day');");
echo mysql_errno($sql) . ": " . mysql_error($sql). "\n";
I need to get the average of close from the database, and I'm using the AVG()function, then insert the return value into the database. The queries work in mysql however they do not work through the script. It does enter a value into the database, but it always enters 0. What am I doing wrong?
EDIT--solution found
$get10 = mysql_query ("SELECT AVG( close ) AS CloseAverage from ( SELECT close FROM _$symbol ORDER BY date DESC limit 10 ) sub1 ;");
$row = mysql_fetch_assoc($get10);
$_10day = $row['CloseAverage'];
if (!mysql_query ("UPDATE _$symbol SET _10day = $_10day, _21day = $_21day, _50day = $_50day, _100day = $_100day, _120day = $_120day, _150day = $_150day, _200day = $_200day, _240day = $_240day, _20dayVol = $_20dayVol, _50dayVol = $_50dayVol where date = '$date';"))
{
echo "Update query failed";
}
I was querying it incorrectly apparently it needed to be selected as a sub query, solution is above, it is working now.
Here's an example on how to manage multiple result-rows:
function connect()
{
$db = mysql_connect("localhost","username","password") or die("your error msg");
mysql_select_db("database_name");
return $db;
}
$db = connect();
$query = "SELECT value1 FROM my_table";
$result = mysql_query($query, $db);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
// This one will loop through the data in your output//
$outputValue = $row['value1'];
}
For inserting data:
// Continued from the state above //
$query = "INSERT INTO table_name (column1) VALUES (value1)";
$result = mysql_query($query, $db) or die(mysql_error());
$_10day is a mysql result, not a value. You can't just put a result into a query string and expect it to work.
You need to get the result data first, eg;
while($row = mysql_fetch_assoc($_10day)) {
$10day = $row['AVG(close)'];
}
Then you can execute your insert query;
mysql_query ("INSERT INTO _$symbol (_10day) VALUES ('$10day')");
Hope this helps.

The max value in a column with php

I have a MySql table "MyTable" with the column "order"
order
-----
3
4
2
1
I want to get the highest number. The sql statement works well inside MySql:
SELECT MAX(order) FROM MyTable"
But I do not know how to use it with php and echo it? Something like:
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row[0];
If you don't provide an alias to a MySQL function it will be shown as you've written it:
$row = mysqli_fetch_array($result);
echo $row['MAX(order)'];
What you can do is write something like:
$result = mysqli_query($con, "SELECT MAX(order) as 'max' FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row['max'];
Which is using an alias.
Hope this helps!
Alternatively you can use ORDER BY DESC and Limit result to 1 this way you can easily get the maximum of an column .
$result=$con->query("SELECT order FROM MyTable ORDER BY order DESC LIMIT 1");
$row=mysqli_fetch_array($result);
echo $row['order'];
Or using MAX
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row=mysqli_fetch_array($result);
echo $row[0];
This tutorial is directly from tizag, using the MySql Max function
MySQL Aggregate Functions - MAX()
// Make a MySQL Connection
$query = "SELECT type, MAX(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "The most expensive ". $row['type']. " is $" .$row['MAX(price)'];
echo "<br />";
}
Here's my answer:
$host = "localhost";
$username = "your_username";
$password = "your_password";
$db_name = "your_db_name";
$connection = mysql_connect($host, $username, $password) or die ("Error:: [1]");
mysql_select_db($db_name, $connection) or die ("Error:: [2]");
$query = "SELECT `order` FROM `MyTable` order by `order` desc";
$res = mysql_query($query, $connection);
$row = mysql_fetch_array($res);
print $row[0];
With this query , you always have the highest value of the give column.

Display single column value of mysqli query

How can I get a single column value from mysqli? The result should be single row with only one column.
This is what I have tried:
$query = "SELECT MAX(`userid`) FROM `user`";
$rlt = mysqli_query($this->db, $query);
echo $rlt['userid'];
You are not fetching the row after executing the query:
$query = "SELECT MAX(`userid`) FROM `user'";
$rlt = mysqli_query($this->db,$query);
$row = mysqli_fetch_row($this->db, $rlt);
echo $row[0];
The alternative would be to use an alias for the computed field and use fetch_assoc:
$query = "SELECT MAX(`userid`) as `maxid` FROM `user'";
$rlt = mysqli_query($this->db,$query);
$row = mysqli_fetch_assoc($this->db, $rlt);
echo $row['maxid'];
try with create alias and fetch result after query execution also your quote of user' looking wrong
$query = "SELECT MAX(`userid`) as userid FROM `user`";
$rlt = mysqli_query($this->db,$query);
$r = mysqli_fetch_assoc($rlt);
echo $r['userid'];
or fetch only one row like:-
$r = mysqli_fetch_row($this->db, $rlt);
echo $r[0];
You should create alias here.
Use this one:
$query = "SELECT MAX(`userid`) as Max_Userid FROM `user'";
$rlt = mysqli_query($this->db,$query);
$row = mysqli_fetch_assoc($this->db, $rlt);
echo $row['Max_Userid'];
Note: Always use alias when you use mysql function in query with fields.

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

Categories