Get a single sql result set value

Consider this SQL query

$sql = "select count(*) as count from table where value='this'"; 

This query returns only one value in the count field.

Is there a way to get this value without using fetch_array and instead specify the first value of the returned array?

+4
source share
3 answers

mysql_result() will allow you to pull the value directly from the result set without using the fetch method. Here is a very simple example of how you can use it to get your only value:

 mysql_select_db( "mysql", mysql_connect( "localhost", "root", "" ) ); $r = mysql_query( "SELECT count(name) as total FROM `help_keyword`" ); echo $r ? mysql_result( $r, 0 ) : mysql_error() ; // Outputs 450 

There are three parameters to the mysql_result() function; first, this is the result of the result set itself, the second is the row index, and the third is the field index. I use only the first two parameters, since the third by default is 0, the first field is returned.

+2
source

As a beginner sql, I also spent a lot of time trying to use these one-dimensional sql query results directly. I thought that since the result is not an array, I could skip these while-loops with these fetch_arrays.

However, only now I understand that although the result can be an integer value of 8, if you do not convert it to the value that it is, it is still considered simply a “query result” instead of an integer.

Jonathan's code helped me figure this out. For myself, I used a slightly different code that helped me. Here is what worked for me:

 $con=mysql_connect("host", "user", "password"); if(!$con) {die('could not connect: '.mysql_error()); } $db_selected=mysql_select_db("database", $con); $sql = "the sql query that yiels one value, for example a SELECT COUNT query"; $outcome_considered_as_a_query-result-set = mysql_query($sql,$con); $outcome_considered_as_the_one_element_of_the_result_set = mysql_result($outcome_considered_as_a_query-result-set,0); echo $outcome_considered_as_the_one_element_of_the_result_set; mysql_close($con); 
+1
source

Usage: mysql_num_rows

 $count = mysql_num_rows(mysql_query($sql); 

Just do not use count in this case. Select everything and it will count.

0
source

All Articles