我只是熟悉准备好的陈述。我有一个查询工作,有一个循环将结果绑定到我可以更容易使用的东西。
现在,我想添加另一个查询,我不确定正确的语法
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli($hostname_db, $username_db, $password_db, $database_db);
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT * FROM table WHERE id = ?")) {
/* Bind parameters, s - string, b - blob, i - int, etc */
$stmt -> bind_param("i", $rid);
$stmt -> execute();
/* USE loop to bind result and fetch */
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {$parameters[] = &$row[$field->name];}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach($row as $key => $val) { $x[$key] = $val;
}
$results[] = $x;
}
/* Close statement */
$stmt -> close();
------------------>SHOULD I PUT ANOTHER QUERY HERE?
}
------------------>OR SHOULD I PUT ANOTHER QUERY HERE INSTEAD?
/* Close connection */
$mysqli -> close();
----------------->Or, should I put it here
//END mysqli query method
我不确定这三个职位中哪一个是最佳位置/最佳实践。我可以通过反复试验来完成它,但我想知道什么是最佳实践,我似乎无法找到明确的答案。
提前致谢。
答案 0 :(得分:0)
将你的陈述置于另一个之下。不要使用close(),不要使用mysqli预处理语句,不要收集200:
$stmt = $pdo -> prepare("SELECT * FROM table WHERE id = ?");
$stmt -> execute(array($rid));
$results = $stmt -> fetchAll(); // for many rows
$stmt = $pdo -> prepare("SELECT id FROM table WHERE name = ?");
$stmt -> execute(array($name));
$id = $stmt -> fetchColumn(); // for single scalar value
$stmt = $pdo -> prepare("SELECT * FROM table WHERE id = ? LIMIT 1");
$stmt -> execute(array($rid));
$row = $stmt -> fetch(); // for single row
等等
或者,使用even more intelligent library,它甚至可以
// one single line to get your $results instead of screenful of code, mind you
$results = $db->getAll("SELECT * FROM table WHERE id = ?i",$rid);
// as well as others
$id = $db->getOne("SELECT id FROM table WHERE name = ?s", $name);
$row = $db->getRow("SELECT * FROM table WHERE id = ?i LIMIT 1",$rid)
还想坚持使用原始的mysqli?