MySQL - count total number of rows in php - php

What is the best MySQL command to count the total number of rows in a table without any conditions applied to it? I'm doing this through php, so maybe there is a php function which does this for me? I don't know. Here is an example of my php:
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("some command");
$row = mysql_fetch_array($result);
mysql_close($con);
?>

<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>

Either use COUNT in your MySQL query or do a SELECT * FROM table and do:
$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";

mysqli_num_rows is used in php 5 and above.
e.g
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>

Use COUNT in a SELECT query.
$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);

you can do it only in one line as below:
$cnt = mysqli_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE"));
echo $cnt;

use num_rows to get correct count for queries with conditions
$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";

for PHP 5.3 using PDO
<?php
$staff=$dbh->prepare("SELECT count(*) FROM staff_login");
$staff->execute();
$staffrow = $staff->fetch(PDO::FETCH_NUM);
$staffcount = $staffrow[0];
echo $staffcount;
?>

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo "number of rows: ",$rowcount;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
it is best way (I think) to get the number of special row in mysql with php.

<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>
Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php

$sql = "select count(column_name) as count from table";

Well, I used the following approach to do the same: I have to get a count of many tables for listing the number of services, projects, etc on the dashboard. I hope it helps.
PHP Code
// create a function 'cnt' which accepts '$tableName' as the parameter.
function cnt($tableName){
global $conection;
$itemCount = mysqli_num_rows(mysqli_query($conection, "SELECT * FROM `$tableName`"));
echo'<h6>'.$itemCount.'</h6>';
}
Then when I need to get the count of items in the table, I call the function like following
<?php
cnt($tableName = 'projects');
?>
In my HTML front end, so it renders the count number
It's to be noted that I create the cnt() function as a global function in a separate file which I include in my head, so I can call it from anywhere in my code.

Related

how to add rows in mysqli using sum()

I am trying to add numbers located in my database. so I tried sum() in SQL but it didn't show the total number. I don't know whats wrong with my code.
This is my code
<?php
session_start();
$email = $_SESSION['login_user'];
$con = mysqli_connect("localhost" , "root" , "" , "db_name");
if (mysqli_connect_errno()) {
echo "failed to connect:" . mysqli_connect_error();
}
$sql = "SELECT SUM(points) FROM points WHERE email='$email '";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
echo $row[0]. "total number" ;
mysqli_free_result($result);
mysqli_close($con);
?>
it just shows total number. i don't know what is wrong here
Use as total, and row of 'total' by mysqli_fetch_assoc.

Read value from database, echo

Very basic but as a rookie I am struggling. The echo doesnt show any value, just the text. What am I doing wrong?
Connect.php:
<?php
$connection = mysqli_connect('test.com.mysql', 'test_com_systems', 'systems');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'swaut_com_systems');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
?>
Get.php:
<?php
require('connect.php');
$query2 = "SELECT systemid FROM user WHERE username=test";
$result2 = mysqli_query($connection, $query2);
echo ( 'SystemID: '.$result2);
?>
Assuming you have connected to the database successfully then the query is incorrect. You must wrap all text values in quotes like this
<?php
require('connect.php');
$query2 = "SELECT systemid FROM user WHERE username='test'";
$result2 = mysqli_query($connection, $query2);
Now the mysqli_query submits the query to the database where it is run and a result set built. To see the result set you need to read the result set back from the database using one of the fetch functions for example
$row = mysqli_fetch_assoc($result2);
echo 'SystemID: ' . $row['systemid'];
If there are more than one rows in the result set you must do that in a loop like this
while ($row = mysqli_fetch_assoc($result2)){
echo 'SystemID: ' . $row['systemid'];
}
You are printing the mysqli result object. In order to printthe result you have to use:
$row = mysqli_fetch_assoc($result2);
print_r($row);
You need to collect the results of the mysqli_query using the following:
require('connect.php');
$query2 = "SELECT systemid FROM user WHERE username=test";
$result2 = mysqli_query($connection, $query2);
while ($row = mysqli_fetch_assoc($result2))
{
echo "System ID is: " . $row['systemid'];
}

MySQL rows count with PHP and show result

I want to make an API that when you access it it will show result in text format of how many rows are on my database.
Database info:
Username: predator_db
DB Name: predator_db
Table Name: database
I tried a couple of codes and I could not get it to work.
Code tried:
<?php
$con = mysql_connect("localhost","predator_db","PASS");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("predator_db", $con);
$result = mysql_query("select count(1) FROM database");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
Response Of Code: "Total Rows: " < Does not show how many rows. Error Log:
[05-Feb-2015 23:44:58 UTC] PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/predator/public_html/api/resolver/number.php on line 2
[05-Feb-2015 23:44:58 UTC] PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/predator/public_html/api/resolver/number.php on line 10
You're trying to fetch the results from database... not from your actual database of predator_db.
I'll do it with the basics, but please look into MySQLi prepared statements and/or PDO.
$link = mysqli_connect("localhost", "predator_db", "PASS", "predator_db");
$result = mysqli_query($link, "select COUNT(id) AS count FROM `database`");
// make sure it worked
if(!$result) {
die('Error: ' . mysqli_error($link));
} else {
$num_rows = mysqli_fetch_assoc($result);
// echo it
echo "Rows: " . $num_rows['count'];
}
First off, it's not a good idea to name a table after a reserved keyword like database. However, if you are going to go that route, you will always have to place the name in backticks ``. So, your query should be
$result = mysql_query("select count(1) FROM `database`");
Also, look into MYSQLi, as the old MySQL driver is deprecated.
<?php
$link = mysqli_connect("localhost", "DB_USER", "DB_PASS", "DB_NAME");
$result = mysqli_query($link, "select COUNT(*) AS count FROM DB_NAME.DB_TABLE");
if(!$result) {
die('Error: ' . mysqli_error($link));
} else {
$num_rows = mysqli_fetch_assoc($result);
echo "Rows: " . $num_rows['count'];
}
?>

How to Select Specific Info From MySQL

I'm trying to a number from a specific table, row, and column but can't seem to get it right.
The table is tblproducts. The column is qty. And I need to select where id is 13.
This is the code I'm using but it isn't returning anything:
<?php
$con=mysqli_connect("localhost","blank","blank","blank");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT qty FROM tblproducts");
while($row = mysqli_fetch_array($result))
{
echo $row['13'];
}
mysqli_close($con);
?>
Any help would be appreciated
do it all in the query like so
SELECT qty FROM tblproducts where id =13
no loop needed
$result = mysqli_query($con,"SELECT qty FROM tblproducts where id =13");
$row = mysqli_fetch_assoc($result);
echo $row['qty'];
Your sql syntax is a bit off, see my corrections. Your echo of the row['13'] also looks suspicous. You can use print_r() to print arrays to find which key you need to use. It is probably $row['qty'].
<?php
$con=mysqli_connect("localhost","blank","blank","blank");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT qty FROM tblproducts where id = 13");
while($row = mysqli_fetch_array($result))
{
print_r($row); // You can use print_r to have a look at your full array. The index '13' might not be what you where looking for.
}
mysqli_close($con);
?>

Unable to count database users

I can't count my users in the database with my current configurations.
<?php
require_once 'scripts/app_config.php';
mysqli_connect(DATABASE_HOST,DATABASE_USER,DATABASE_PASS,DATABASE_NAME);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT COUNT(*) FROM users";
$result = mysql_query($query);
$num = mysql_num_rows($result);
echo "There are: ". $num . " users in the database";
mysqli_close($con);
?>
Your problem is this:
$num = mysql_num_rows($result);
Your query only returns 1 row, so I presume the problem you're having is that it always outputs: There are 1 users in the database.
You should instead use:
$num = mysqli_fetch_array($query)[0];
Either use COUNT(*) OR use mysql_num_rows
$query = "SELECT COUNT(*) FROM users";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$num = $row[0];
echo "There are: ". $num . " users in the database";
Note : mysql_* function is deprecated, move on mysqli_* function asap.

Categories