note 115413 added to pdostatement.rowcount

From: Date: Sun, 20 Jul 2014 09:38:40 +0000
Subject: note 115413 added to pdostatement.rowcount
Groups: php.notes 
Request: Send a blank email to php-notes+get-199982@lists.php.net to get a copy of this message
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()); } ?> ---- Server IP: 72.52.91.14 Probable Submitter: 50.161.196.154 ---- Manual Page -- http://php.net/manual/en/pdostatement.rowcount.php Edit -- https://master.php.net/note/edit/115413 Del: integrated -- https://master.php.net/note/delete/115413/integrated Del: useless -- https://master.php.net/note/delete/115413/useless Del: bad code -- https://master.php.net/note/delete/115413/bad+code Del: spam -- https://master.php.net/note/delete/115413/spam Del: non-english -- https://master.php.net/note/delete/115413/non-english Del: in docs -- https://master.php.net/note/delete/115413/in+docs Del: other reasons-- https://master.php.net/note/delete/115413 Reject -- https://master.php.net/note/reject/115413 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#199982) next »