Unable to get rowCount from MySQL SELECT query with PDO

Hi all,

I was wondering if you can help, I’ve been trawling Google for hours and just can’t seem to get anywhere with this!

The aim is to create a hit counter, I’m doing it manually because I want to learn. I’m just not used to PDO’s though so I’m having a bit of a problem transitioning.

To build this hit counter I’m doing it one step at a time, first I want to query the database and echo the number of rows that match the query as an integer or string.

The trouble is, the methods I’m using keep returning boolean values so I get 0 in the echo and a warning that a boolean cannot be output as an integer or string.

I’ve finally found http://php.net/manual/en/pdostatement.rowcount.php and it appears I need to do some extra work if I want to count the rows with a SELECT statement.

I’m trying to botch together something from the second example to simply output the number of rows found but the example is doing some if statements which is not what I want.

I simply want to echo how many rows are found.

This is my connection code, I haven’t included the botched attempt to make example #2 work, as it doesn’t work! I thought a fresh perspective may be needed.

[php]//database connection details
$hostname = “localhost”;
$username = “root”;
$password = “”;
try {
//connect to database
$database = new PDO(“mysql:host=$hostname;dbname=fds”, $username, $password);
$database->exec(“SET time_zone=’+0’;”);

		//close connection
		//$database = null;
	}
	catch(PDOException $e) {
		//error output
		$concern = true;
		$message = "<p>There has been an error.</p>";
		//display error message(s) with $e->getMessage();
}

//spoof IP for test
$ip = "1337.1337.1337.1337";[/php]

My SELECT query is:

SELECT * FROM hits WHERE IP LIKE $ip
Apologies if I haven’t posted enough detail.

Thank you in advance :slight_smile:

Maybe something like this? (This is untested, so I not sure that it will work the first time out the door)
[php]$query = “SELECT * FROM hits WHERE IP LIKE :ip”;
$stmt = $database->prepare($query);
$stmt->bindParam(’:ip’, $ip, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();[/php]

That’s brilliant, thank you, it worked straight out the box!

Sponsor our Newsletter | Privacy Policy | Terms of Service