简体   繁体   中英

Database: Count rows in a table

How to count rows in a table, if it's equals to one(1) record the data can't be deleted.

I tried something like this:

$query = mysql_query("SELECT COUNT(*) FROM mytable");

if (mysql_num_rows($query) === 1){
   echo "Delete not allowed.";
} else {
   DELETE query here
}

Please help.

You may change your query to

$query = mysql_query("SELECT * FROM mytable");

and the code will do.

You may change your query to

$query = mysql_query("SELECT COUNT(*) as rows FROM mytable");

and look into the value of "rows", this will be the best and faster one.

Try this:

<?php

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$query = mysql_query("SELECT * FROM mytable", $link); // Change query to this
$num_rows = mysql_num_rows($query); // Count rows

if ($num_rows === 1){ 
  echo "Delete not allowed.";
} else {
 // DELETE query here
}

?>

Check the documentation: http://php.net/manual/en/function.mysql-num-rows.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM