-2

我只是熟悉准备好的陈述。我有一个查询工作,有一个循环将结果绑定到我可以更轻松地使用的东西。

现在,我想添加另一个查询,但我不确定语法是否正确

/* 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

我不确定这三个位置中的哪一个是最佳位置/最佳实践。我可以通过反复试验来完成它,但我想知道最佳做法是什么,但我似乎找不到明确的答案。

提前致谢。

4

1 回答 1

2

把你的陈述一个接一个。不要使用close(),不要使用mysqliprepared statements,不要收集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

等等

或者,使用更智能的库,它甚至可以是

// 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 吗?

于 2013-05-24T03:52:34.983 回答