Hi all:

I am starting to use mysqli after getting my feet wet with sqlsrv (switching from MSSQL to MySQL).

The following code appears fine, but my gut feeling is this isn't the "right" way to do things.

I had read somewhere that fetch_array is not necessary with mysqli. If that is true I am not sure why. Also, I originally was closing the stmt with mysqli_stmt_close($stmt) but that was throwing errors. I switched to mysqli_free_result($stmt). The errors stopped but I am not sure why or if I did the right thing.

Any words of wisdom appreciated!

	$sql="SELECT COUNT(DISTINCT Player) AS Total FROM WishList";
			$stmt = mysqli_query($link, $sql);

			if(!$stmt)
				{
			die('MySQL error: ' . mysqli_error($link));
				}

			$TotalRows = mysqli_fetch_array($stmt);
			mysqli_free_result($stmt);

    From http://se2.php.net/manual/en/mysqli-stmt.close.php

    Closes a prepared statement

    which obviously means you'd need a prepared statement. Looking at http://se2.php.net/manual/en/mysqli.query.php

    Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a result object. For other successful queries mysqli_query() will return TRUE.

    Which means that your function call always returns one of false, true or (mysqli) result object. You can obviously do little with a boolean value, and http://se2.php.net/manual/en/class.mysqli-result.php tells you what you can do with a mysqli result object. mysqli_free_result is one of those things, mysqli_stmt_close is not.

    Other than missleading variables names, I see nothing wrong with the code.
    I'd rename $stmt to $result.
    I'd also rename $totalRows to $row (since it is what it is). After fetching the first (and only) row in the result set, $row['Total'] contains the number of distinct names.
    You allready know that total number of rows for this query is 1. And the query did not tell you how many rows in total there are in the table either.

      Write a Reply...