【发布时间】:2015-04-30 00:25:07
【问题描述】:
我正在为 mysql 语句构建我的第一个类,以使我自己的查询更容易。基本上我们会这样做。
Query::set_config($host,$username,$password);
if( Query::is_database("database_name") ) {
Query::get_results("SELECT * FROM REGISTRY WHERE `name`=? AND `last`=?",[
"s"=>"firstname",
"s"=>"lastname"
]);
}
我的问题是prepared和not,以及procedural和OO之间的细微差别。
这是get_results背后的底层代码
/*Load Results from SQL Query*/
public static function results($sql,$prepared=null) {
if($is_configurated) {
self::connect();
$rows = array();
if($prepared === null) {
$query = mysqli_query(self::$conn,$sql);
if(!$query)
echo mysqli_error(self::$conn);
while($r = mysqli_fetch_array($query)) {
$rows[] = $r;
}
}
else
{
$stmt = mysqli_prepare(self::$conn,$sql);
/*
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
foreach($prepared as $type=>$param) {
if(strlen($type) > 1) {
self::$errors[]="Only one type is allowed";
continue;
} else {
mysqli_stmt_bind_param($stmt,$type,$param);
}
}
/*STUCK HERE NOW*/
mysqli_stmt_execute($stmt);
while (mysqli_stmt_fetch($stmt)) {
$rows[] = $r;
}
}
self::disconnect();
return $rows;
} else return "NO CONFIGURATED CONNECTION";
}
我写了我卡住的地方,这就像普通的mysqliwhilemysqli_fetch_row 还是什么。 PHP.net 文档不是很流畅,也不是很简单。我只需要帮助来做这件事,看看我的代码中是否有任何小缺陷。我需要从结果中返回行。
这是正确的吗?
/*Load Results from SQL Query*/
public static function results($sql,$prepared=null) {
if($is_configurated) {
self::connect();
$rows = array();
if($prepared === null) {
$query = mysqli_query(self::$conn,$sql);
if(!$query)
echo mysqli_error(self::$conn);
while($r = mysqli_fetch_array($query)) {
$rows[] = $r;
}
}
else
{
$stmt = mysqli_prepare(self::$conn,$sql);
/*
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
foreach($prepared as $type=>$param) {
if(strlen($type) > 1) {
self::$errors[]="Only one type is allowed";
continue;
} else {
mysqli_stmt_bind_param($stmt,$type,$param);
}
}
/*STUCK HERE NOW*/
mysqli_stmt_execute($stmt);
$stored = mysqli_store_result($stmt);
if( count($stored) >= 1) {
while ($data = mysqli_stmt_fetch($stmt)) {
$rows[] = $data;
}
}
}
self::disconnect();
return $rows;
} else return "NO CONFIGURATED CONNECTION";
}
【问题讨论】:
-
mysqli不支持命名占位符。 -
?然后是对的,因为我知道它要么是 PDO 要么被命名为占位符 -
想我现在有了。
标签: php class mysqli prepared-statement