Assign Mysql query result to a PHP variable

Asked

Viewed 8,263 times

3

As if, after counting 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 was able to do what I wanted, but is this correct to do? Is there any better way?

2 answers

4

Add the query an alias to 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'];

3


It is correct the way you have developed, alias, can use other types of returns that 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] ;
       }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.