Search code examples
phpmysqlsqlcountautonumber

How to use count in php?


I want to insert data to database. I have a table, named member that has 7 column (ID, User, Password, Address, Phone, Gender, Email). I used count to make auto number like this

$no = "SELECT COUNT(ID)FROM member";
$nors = mysql_query($no);
$nors = $nors + 1;
$query = "INSERT INTO member VALUES (".$nors.",'".$user."','".md5($pass)."','".$name."','".$addr."',".$hp.",'".$gender."','".$email."')";

Why, the result of nors is 6 not 2, although I only have 1 data?


Solution

  • mysql_query returns a result object, not the value. Your query also lacks a needed space between COUNT(ID) and FROM...

    $no = "SELECT COUNT(ID) AS count FROM member";
    $result = mysql_query($no);
    $row = mysql_fetch_object($result);
    $nors = $row->count;
    

    You should consider using something more modern like PDO, though, as mysql_* functions have been deprecated and will eventually go away entirely.

    edit: @andrewsi noted in the comments that you really should be using MySQL's built-in auto increment functionality for IDs, anyways. Much better than what you're currently doing.