将行放入数组时,它会重复

时间:2016-11-25 00:39:48

标签: php mysqli prepared-statement

我正在尝试创建一个类,以便更安全的MySQLi连接查询,但我遇到了这个问题,它复制$ row就像[0] => 47, [example_id] => 47基本上让我说我有一个像这样的表

╒═══════════════════════════════════════════════╕
│                     Content                   |
╞════════════╤═══════════════╤══════════════════╡
│ example_id │ example_title │ example_content  │
╞════════════╪═══════════════╪══════════════════╡
╞════════════╪═══════════════╪══════════════════╡
│ 1          │ Hello World 1 │ Some content 1   │
╞════════════╪═══════════════╪══════════════════╡
│ 2          │ Hello World 2 │ Some content 2   │
╘════════════╧═══════════════╧══════════════════╛


public function select_all(string $table){ // In this case $table = 'Content'
  $this->remove_stmt();

  $this->num_rows = null;
  $this->rows = Array();

  if(!$stmt = $this->con->prepare("SELECT * FROM $table")){
    $this->stmt_is_errors = true;
    $this->stmt_errors = 'Could not prepare statement!';
    return false;
  }

  if(!$stmt->execute()){
    $this->stmt_is_errors = true;
    $this->stmt_errors = 'Could not execute statement!';
    return false;
  }

  if(!$result = $stmt->get_result()){
    $this->stmt_is_errors = true;
    $this->stmt_errors = 'Could not get result content!';
    return false;
  }

  if(!$this->num_rows = $result->num_rows){
    $this->stmt_is_errors = true;
    $this->stmt_errors = 'Could not get number of rows';
    return false;
  }

  $row = Array();
  while($row = $result->fetch_array()){
    $this->rows[] = $row;
    print_r($row);
    echo '<br><br>';
  }

  return true;

}

使用上面示例表中的代码,您可以看到本文最上面的代码将输出如下所示的数组:

Array(
    [0] => Array(
        [0] => 1,
        [example_id] => 1,
        [1] => "Hello World 1",
        [example_title] => "Hello World 1",
        [2] => "Some content 1",
        [example_content] => "Some content 2"
    ),
    [1] => Array(
        [0] => 2,
        [example_id] => 2,
        [1] => "Hello World 2",
        [example_title] => "Hello World 2",
        [2] => "Some content 2",
        [example_content] => "Some content 2"
    ),
);

我如何避免这些重复?

感谢。理查德。

1 个答案:

答案 0 :(得分:1)

您正在使用$result->fetch_array()这个函数,如果在没有参数的情况下使用,将使用默认参数MYSQLI_BOTH,该参数返回数值数组和每个fetch <的关联数组/ p>

所以要么使用$result->fetch_array(MYSQLI_ASSOC)

或者你可以使用只返回一个关联数组的$result->fetch_assoc()

相关问题