How to do a parameterized query
[ Status: Learner ]
I am attempting to implement a parameterized query but I am having problems. Jonathan Sampson recently hinted at how this could be done (#2286115), but I'm not following his suggestion correctly. Here is my script
$cGrade = "grade" ;
include_once ( "db_login.php" ) ;
$sql = "SELECT last_name AS last_name
, first_name AS first_name
, grade AS gr
, ethnic 开发者_开发知识库 AS eth
, sex AS sex
, student_id AS id_num
, reason AS reason
, mon_init AS since
FROM t_tims0809
WHERE tag <> '' AND
tag IS NOT NULL AND
schcode = {$schcode}
ORDER
BY ('%s') " ;
$qResult = mysql_query ( sprintf ( $sql, $cGrade ) or ( "Error: " . mysql_error() ) ) ;
The query works fine with grade
in the ORDER BY phrase.
Thanks.
Check out the MySQLi prepared statements class:
$query = "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sss", $val1, $val2, $val3);
$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';
/* Execute the statement */
$stmt->execute();
From the PHP manual.
I feel it's a much superior way of doing parameterized queries, I've switched over to prepared statements when possible, especially during bulk inserts/selects.
Xorlev's answer is entirely correct. There are other options for syntax too. You can specify the bind variables within the query by name:
$stmt = $mysqli->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
Or if you want to do things shorthand and skip the call to bindParam()
:
$stmt = $mysqli->prepare('INSERT INTO tbl VALUES(?)');
$stmt->execute($stmt, array("some input"));
$stmt->execute($stmt, array("some other input"));
$stmt->execute($stmt, array("some more input"));
精彩评论