Assign MySQL query result to a PHP variable

3

How, after telling how many records I have in a database, how do I put the value inside a PHP variable:

$sql = mysql_query("SELECT COUNT(*) FROM 'users'");
$row = mysql_fetch_array($sql); 
$total = $row['COUNT(*)'];

I managed to do what I wanted to do this, but is this correct? Is there any better way?

    
asked by anonymous 17.06.2015 / 16:07

2 answers

3

The form you've developed is correct, otherwise you can use other types of returns you expect as Object, Associative, or Array.

Examples

    //Objeto
      while ($row = mysql_fetch_object($result)) {
          echo $row->column1;
          echo $row->column2;
      }



    //Associativo
      while ($row = mysql_fetch_assoc($result)) {
          echo $row["column1"];
          echo $row["column2"];
      }



     //Array
       while ($row = mysql_fetch_array($result)) {
          echo $row[0];
          echo $row[1] ;
       }
    
17.06.2015 / 16:18
4

Add the query an alias for the desired column. For example:

$sql = mysql_query("SELECT COUNT(*) as total_registros FROM 'users'");

Then just select the alias you used:

$total = $row['total_registros'];
    
17.06.2015 / 16:13