note 62247 added to function.mysql-query

From: Date: Thu, 23 Feb 2006 07:11:27 +0000
Subject: note 62247 added to function.mysql-query
Groups: php.notes 
Request: Send a blank email to php-notes+get-104268@lists.php.net to get a copy of this message
If, like me, you come from perl, you may not like having to use sprintf to 'simulate' placeholders that the DBI package from perl provides. I have created the following wrapper function for mysql_query() that allows you to use '?' characters to substitute values in your DB queries. Note that this is not how DBI in perl handles placeholders, but it's pretty similar. <?php // mysql_query() wrapper. takes two arguments. first // is the query with '?' placeholders in it. second argument // is an array containing the values to substitute in place // of the placeholders (in order, of course). function mysql_prepare ($query, $phs = array()) { foreach ($phs as $ph) { $ph = "'" . mysql_real_escape_string($ph) . "'"; $query = substr_replace( $query, $ph, strpos($query, '?'), 1 ); } return mysql_query($query); } // sample usage list($user, $passwd) = array('myuser', 'mypass'); $sth = mysql_prepare( 'select userid from users where userid=? and passwd=?', array($user, sha1($passwd)) ); $row = mysql_fetch_row($sth); // successfull username & password authentication if ($row !== false) { echo "logging in as '{$row[0]}'!\n"; } // oops, wrong userid or passwd else { echo "Invalid username and password combination.\n"; } ?> ---- Server IP: 66.207.199.35 Probable Submitter: 68.148.210.62 ---- Manual Page -- http://www.php.net/manual/en/function.mysql-query.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+62247 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+62247&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+62247&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+62247&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+62247&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+62247&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+62247&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+62247&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+62247&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#104268) next »