note 61013 added to function.mysqli-prepare

From: Date: Mon, 23 Jan 2006 16:53:09 +0000
Subject: note 61013 added to function.mysqli-prepare
Groups: php.notes 
Request: Send a blank email to php-notes+get-102300@lists.php.net to get a copy of this message
Here is an example using bind_param and bind_result, showing iteration over a list of cities. Note that there's some bug-potential in cases where the query returns NULL for some parameter value, but the bind_result variables still might be bound. So, we use a conditional to spray the spot first. $mysqli->select_db("world"); $template = "SELECT District, CountryCode FROM City WHERE Name=?"; printf("Prepare statement from template: %s\n", $template); $cities = array('San Francisco', 'Lisbon', 'Lisboa', 'Marrakech', 'Madrid'); printf("Cities: %s\n", join(':', $cities)); if ($stmt = $mysqli->prepare($template)) { foreach($cities as $city) { // bind the string $city to the '?' $stmt->bind_param("s", $city); $stmt->execute(); // bind result variables $stmt->bind_result($d,$cc); // 'Lisbon' is not found in the world.City table, but 'Lisboa' is. // Using a conditional we avoid putting Lisbon in California. if($stmt->fetch()) { printf("%s is in %s, %s\n", $city, $d, $cc); } } $stmt->close(); } With the conditional statement we get the desired result: Prepare statement from template: SELECT District,CountryCode FROM City WHERE Name=? Cities: San Francisco:Lisbon:Lisboa:Marrakech:Madrid San Francisco is in California, USA Lisboa is in Lisboa, PRT Marrakech is in Marrakech-Tensift-Al, MAR Madrid is in Madrid, ESP But, without the conditional statement we would put Lisbon in California: San Francisco is in California, USA Lisbon is in California, USA Lisboa is in Lisboa, PRT Marrakech is in Marrakech-Tensift-Al, MAR Madrid is in Madrid, ESP ---- Server IP: 64.71.164.2 Probable Submitter: 66.92.9.47 ---- Manual Page -- http://www.php.net/manual/en/function.mysqli-prepare.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+61013 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+61013&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+61013&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+61013&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+61013&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+61013&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+61013&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+61013&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+61013&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#102300) next »