【发布时间】:2016-11-25 00:39:47
【问题描述】:
我正在尝试创建一个类以更轻松地进行安全 MySQLi 连接和查询,但我遇到了这个问题,它与 [0] => 47, [example_id] => 47 一样重复 $row 基本上可以说我有一个这样的表
╒═══════════════════════════════════════════════╕
│ 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"
),
);
如何避免这些重复?
谢谢。理查德。
【问题讨论】:
-
使用
fetch_assoc代替fetch_array: php.net/manual/en/mysqli-result.fetch-assoc.php -
哈哈,谢谢!从头痛中拯救了我的头
-
张贴作为答案并说明原因并将其作为正确答案
标签: php mysqli prepared-statement