简体   繁体   English

如何在 PHP 中使用 mysqli_query()?

[英]How to use mysqli_query() in PHP?

I'm coding in PHP.我正在用 PHP 编码。 I have the following mySQL table:我有以下 mySQL 表:

CREATE TABLE `students` (
  `ID` int(10) NOT NULL AUTO_INCREMENT,
  `Name` varchar(255) DEFAULT NULL,
  `Start` int(10) DEFAULT NULL,
  `End` int(10) DEFAULT NULL,
   PRIMARY KEY (`ID`)
 ) ENGINE=InnoDB;

I'm trying to use the mysqli_query function in PHP to DESCRIBE the table.我正在尝试使用PHP中的mysqli_query函数来描述表。

Here's my code:这是我的代码:

$link = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DATABASE);
$result = mysqli_query($link,"DESCRIBE students");

The documentation says For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.文档说对于成功的 SELECT、SHOW、DESCRIBE 或 EXPLAIN 查询 mysqli_query() 将返回一个mysqli_result对象。

But from there I don't know how to print $result so that it shows the query results.但是从那里我不知道如何打印$result以显示查询结果。 If possible I want to print $result so that it looks like:如果可能,我想打印 $result 使其看起来像:

+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| ID       | int(10)      | NO   | PRI | NULL    | auto_increment |
| Name     | varchar(255) | YES  |     | NULL    |                |
| Start    | int(10)      | YES  |     | NULL    |                |
| End      | int(10)      | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+ 

My other question is how to print the query SHOW CREATE TABLE students .我的另一个问题是如何打印查询SHOW CREATE TABLE students

$result = mysqli_query($link,"SHOW CREATE TABLE students");

I have to admit, mysqli_query() manual entry doesn't contain a clean example on how to fetch multiple rows.我不得不承认, mysqli_query()手动输入不包含关于如何获取多行的清晰示例。 May be it's because the routine is so routine, known to PHP folks for decades:可能是因为套路太套路了,几十年来PHP人都知道:

$result = $link->query("DESCRIBE students");
while ($row = $result->fetch_assoc()) {
    // to print all columns automatically:
    foreach ($row as $value) {
        echo "<td>$value</td>";
        // OR to print each column separately:
        echo "<td>",$row['Field'],"</td><td>",$row['Type'],"</td>\n";
    }
}

In case you want to print the column titles, you have to select your data into a nested array first and then use keys of the first row:如果要打印列标题,则必须先将数据选择到嵌套数组中,然后使用第一行的键:

// getting all the rows from the query
// note that handy feature of OOP syntax
$data = $link->query("DESC students")->fetch_all(MYSQLI_ASSOC);
// getting keys from the first row
$header = array_keys(reset($data));
// printing them
foreach ($header as $value) {
    echo "<td>$value</td>";
}
// finally printing the data
foreach ($data as $row) {
    foreach ($row as $value) {
        echo "<td>$value</td>";
    }
}

Some hosts may have no support for the fetch_all() function.某些主机可能不支持fetch_all()函数。 In such a case, fill the $data array the usual way:在这种情况下,以通常的方式填充$data数组:

$data = [];
$result = $link->query("DESC students");
while ($row = $result->fetch_assoc())
{
    $data[] = $row;
}

Two important notes I have to add.我必须补充两个重要的说明。

  1. You have to configure mysqli to throw errors automatically instead of checking them for each mysqli statement manually.您必须将 mysqli 配置为自动抛出错误,而不是手动为每个 mysqli 语句检查它们。 To do so, add this line before mysqli_connect() :为此,请mysqli_connect()之前添加以下行:

     mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
  2. The most important note: unlike mysql_query() , mysqli_query() has a very limited use.最重要的注意事项:mysql_query()不同, mysqli_query()用途非常有限。 You may use this function only if no variables are going to be used in the query.当查询中不使用任何变量时,您才可以使用此函数 If any PHP variable is going to be used, you should never use mysqli_query() , but always stick to prepared statements , like this:如果要使用任何 PHP 变量,则永远不要使用mysqli_query() ,而应始终使用准备好的语句,如下所示:

     $stmt = $mysqli->prepare("SELECT * FROM students WHERE class=?"); $stmt->bind_param('i', $class); $stmt->execute(); $data = $stmt->get_result()->fetch_all();

It's a bit wordy, I have to admit.这有点罗嗦,我不得不承认。 In order to reduce the amount of code you can either use PDO or adopt a simple helper function to do all the prepare/bind/execute business inside:为了减少代码量,你可以使用 PDO 或者采用一个简单的辅助函数来完成里面的所有准备/绑定/执行业务:

$sql = "SELECT * FROM students WHERE class=?";
$data = prepared_select($mysqli, $sql, [$class])->fetch_all();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM