查看PDO。它比程序命令需要更多的时间来适应mysql_
,但完全值得。
$my_id = // whatever;
$my_name = // whatever;
$db_obj = new PDO (/* connection string */);
$query_str = "select * from some_table where some_name_id =
(select some_name_id from some_names where some_name = :name
and some_other_id = 1)
and year(some_start_date) = 2012 and some_other_id = :id";
$query_obj = $db_obj->prepare ($query_str); // creates a PDOStatement object
$query_obj->bindParam(":name", $my_name); // essentially replaces :name with $my_name*
$query_obj->bindParam(":id", $my_id); // essentially replaces :id with $my_id*
$query_obj->execute(); // executes the query
while ($row = $query_obj->fetch (PDO:FETCH_ASSOC)) {
/* some code */
};
注 1:注释中的bindParam 解释过于简单化了。值得阅读 PDO 以及 bindParam 如何实际工作以获取更多信息。
注 2:很多人更喜欢命名$query
$query_str 和 $query_obj $result
。我更喜欢这种方式,但这只是一种风格。