如何进行参数化查询

时间:2010-02-20 05:06:34

标签: php mysql parameterized

[状况:学习者]

我正在尝试实现参数化查询,但我遇到了问题。 Jonathan Sampson最近暗示如何做到这一点(#2286115),但我没有正确地遵循他的建议。这是我的剧本

$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() ) ) ;

查询在ORDER BY短语中与grade配合使用。

感谢。

2 个答案:

答案 0 :(得分:7)

查看MySQLi prepared statements课程:

$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();

从PHP手册。

我觉得这是一种更优秀的参数化查询方式,我尽可能切换到预备语句,特别是在批量插入/选择期间。

答案 1 :(得分:0)

Xorlev的回答是完全正确的。语法还有其他选项。您可以按名称在查询中指定绑定变量:

$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();

或者,如果您想以速记方式做事并跳过对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"));