Sql count примеры php

Sql count примеры php

  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?

PHP Date Based

  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?

PHP String Based

  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?

PHP Class Based

PHP JSON Based

PHP File Systems Based

Источник

Display the results of a SELECT COUNT(*) in PHP

Current trying to display the results of a SELECT COUNT(*) from SQL within my website. I’m 100% new to PHP and SQL so understand this must be the basics! If anyone could recommend a good book or website to learn that would also be great. Here is my current code:

SELECT COUNT(*) FROM project_directory 

7 Answers 7

you did not execute the query using mysql_query() function.

Читайте также:  Php удаление всех спецсимволов

Note: if you have started learning PHP/Mysql then try to use mysqli_* functions. mysql_ will be deprecated in future PHP versions.

Hi Maz, I’m getting the following error Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

please first check if you db connection is ok. mysql_connect is ok then mysql_select_db is correct. 3rd. print your query and run it directly in phpmyadmin and see there is not issue in query

$result is an array, so you should use $result[0] or $result[0][0]

if you use print_r($result) you will see the structure of your array and which once you should use.

also you did not use mysql_query($sql) .
you should use it like:

$result = mysql_query($sql); $out = mysql_fetch_array($result); print($out[0][0]); // or print($out[0]); 

$result = mysql_fetch_array($sql); will cause the error because mysql_fetch_array() method needs resource argument, but the OP use $sql which is a string.

This was the only one that worked for me.. geeez.. how hard can it be..HARD apparently $sql = «SELECT COUNT(*) FROM genericsignup WHERE REF LIKE ‘».$compref.»‘»; $query = mysqli_query($db_conn,$sql); $out = mysqli_fetch_array($query); print($out[0]);

Hello , if you are fresher then you can read w3schools.com enjoy

again! $result = mysql_num_rows($sql); will cause the error because mysql_num_rows() method needs resource argument but $sql is just a string. incorrect answer!

I’m just confused, nothing has worked. I continue to get a number of errors. I assumed this would be easy? It’s seems to be a lot harder than expected.

it is very easy, @tgcowell, please check Amir Noori and Agha Umair Ahmed‘s answers again. their answers are corrected

$abc="SELECT count(*) as c FROM output WHERE question1=4"; $result=mysqli_query($conn,$abc); if($result) < while($row=mysqli_fetch_assoc($result)) < echo $row['c']; >> 
$qry_appr = "SELECT COUNT(*) FROM comments WHERE admin_panel_id ='$id' AND status = 'ON'"; $qry_data = mysqli_query($con, $qry_appr); $approve_count = mysqli_fetch_array($qry_data); $toatalCount = array_shift($approve_count); echo $toatalCount; 

This will also fine but this is do what returning 0 index value by shifting fetch array.this can use without alias. welcome all

if you are new in php and mysql try to use mysqli not mysql

$result = mysql_num_rows($sql); will cause the error . because the method mysql_num_rows() needs resource argument but $sql is simply a string.

you need to execute query first $query = mysql_query($sql); and then $result = mysql_num_rows($query); sorry not written execute query

Get the result from the resource returned by the count query:

 $resource = mysql_query("SELECT COUNT(col) FROM table"); $count = mysql_result($resource,0); 

Or, get the number of rows from the resource returned by the query (without count).

 $resource = mysql_query("SELECT col FROM table WHERE col IS NOT NULL"); $count = mysql_num_rows($resource); 

I would recommend that you use the first, the reason being is that it is unnecessary to extract all the data from the table when you only need the count.

Читайте также:  Create new instance of class java

Источник

MySQL — count total number of rows in 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:

 mysql_select_db("db", $con); $result = mysql_query("some command"); $row = mysql_fetch_array($result); mysql_close($con); ?> 

11 Answers 11

 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); ?> 

**2022: STOP USING MYSQL METHODS, THESE ARE NOT SECURE AND REMOVED FROM PHP! Use MySQLi or PDO instead.

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."; 

You’re first part is correct. I would emit the last part pulling back the entire dataset. In this questions scope, that’s a waste of resources for a simple count.

@George I would not suggest using it either. But as he asked if there was any PHP function that could do it, I just shared the option. Just answering the question.

And that’s fine, however, it’s always good to point out potential issues like this when you answer a question. Not only does it help the user understand the differences, it increases the legitimacy of your answer, and the attention it gets. Which means, more points for you! 🙂

mysqli_num_rows is used in php 5 and above.

 $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); ?> 
$result = mysql_query('SELECT COUNT(1) FROM table'); $num_rows = mysql_result($result, 0, 0); 

Use mysql_result (the best for this instance, IMHO) or one of the similar functions for fetching data from result sets.

you can do it only in one line as below:

$cnt = mysqli_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE")); echo $cnt; 

Why are you writing this answer, when there’s accepted answer? And this question has been asked in 2011.

This answer is wrong. It return always 1 because you count the amount of records returned from the query. Since that you are using an aggregate function like COUNT you will get always an row in the result, and later you count this row thereby you’ll get always 1. Furthermore you are using a deprecated library

use num_rows to get correct count for queries with conditions

$result = $connect->query("select * from table where "); $count=$result->num_rows; echo "$count"; 
prepare("SELECT count(*) FROM staff_login"); $staff->execute(); $staffrow = $staff->fetch(PDO::FETCH_NUM); $staffcount = $staffrow[0]; echo $staffcount; ?> 

Good addition. A small enhancement: If you use $staffcount = $staff->fetchColumn(); you can get rid of the $staffrow temporary variable.

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

 $sql="select count('user_id') from login_user"; $result=mysqli_query($conn,$sql); $row=mysqli_fetch_array($result); echo "$row[0]"; mysqli_close($conn); ?> 
$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.

Читайте также:  Размытие краев блока css

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'
'.$itemCount.'
'; >

Then when I need to get the count of items in the table, I call the function like following

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.

Источник

How to get count of rows in MySQL table using PHP?

I simply want to use PHP to get a count of the total number of rows in a MySQL table, and store the number in a variable called $count . I prefer procedural code since my mind doesn’t work in object-oriented fashion.

$sql="SELECT COUNT(*) FROM news"; $result = mysqli_query($con, $sql); $count = mysqli_fetch_assoc($result); echo $count; 

3 Answers 3

You have a couple of options how to get the value of COUNT(*) from the SQL. The easiest three are probably this:

$sql = "SELECT COUNT(*) FROM news"; $result = mysqli_query($con, $sql); $count = mysqli_fetch_assoc($result)['COUNT(*)']; echo $count; 
$sql = "SELECT COUNT(*) as cnt FROM news"; $result = mysqli_query($con, $sql); $count = mysqli_fetch_assoc($result)['cnt']; echo $count; 
$sql = "SELECT COUNT(*) FROM news"; $result = mysqli_query($con, $sql); $count = mysqli_fetch_row($result)[0]; echo $count; 

If you are using PHP 8.1, then you can do it even simpler:

$sql = "SELECT COUNT(*) FROM news"; $result = mysqli_query($con, $sql); $count = mysqli_fetch_column($result); echo $count; // or using OO style echo $con->query("SELECT COUNT(*) FROM news")->fetch_column(); 

Do not use mysqli_num_rows to count the records in the database as suggested in some places on the web. This function has very little use, and counting records is definitely not one of them. Using mysqli_num_rows you would be asking MySQL to retrieve all matching records from database, which could be very resource consuming. It is much better to delegate the job of counting records to MySQL and then just get the returned value in PHP as shown in my answer.

I would also recommend to learn OOP, which makes your code cleaner and easier to read. The same with OOP could be done as follows:

$sql = "SELECT COUNT(*) FROM news"; $count = $con->query($sql)->fetch_row()[0]; echo $count; 

If your query uses variables, then you could do a similar thing, but using prepared statements.

$sql = "SELECT COUNT(*) FROM news WHERE category=?"; $stmt = $con->prepare($sql); $stmt->bind_param('s', $category); $stmt->execute(); $count = $stmt->get_result()->fetch_row()[0]; echo $count; 

Источник

Оцените статью