note 115413 deleted from pdostatement.rowcount by salathe

From: Date: Mon, 21 Jul 2014 07:54:46 +0000
Subject: note 115413 deleted from pdostatement.rowcount by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-199990@lists.php.net to get a copy of this message
Note Submitter: cjsimon333 at gmail dot com ---- After doing a PDO SELECT query, one can easily get the number of rows of the query without having to use the fetch method. After preparing and executing the statement, rowCount() can be used. Consider the following: <?php //The user inputted key $key = filter_input(INPUT_GET, 'key', FILTER_SANITIZE_STRING); try { //Establish a connection to the database $db = new PDO("mysql:host=127.0.0.1;dbname=$dbname", $dbuser, $dbpass); //Set PDO to discard emulated prepared statements $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //Set PDO to handle exceptions $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Authentication //Select key from channels where a key entry that matches the user specified key exists $sql = 'SELECT key FROM keys WHERE key = :key = 1 LIMIT 1'; //Prepare the SQL query $query = $db->prepare($sql); //Execute the prepared statement //Substitute the :key placeholder for the $key variable specified by the user $query->execute(array(':key' => $key)); //Have any rows been returned? if($query->rowCount() == 0) { //Invalid key. Terminate the process exit("No rows were returned!"); } } catch(PDOException $e) { //An error occurred. Terminate the session exit($e->getMessage()); } ?>

« previous php.notes (#199990) next »