Richard Olsen Sandberg Richard Olsen Sandberg - 8 days ago 7
PHP Question

When putting rows into array it duplicates

I am trying to create a class for easier safe MySQLi connections an queries, but I came across this problem where it duplicates $row like

[0] => 47, [example_id] => 47
Basically lets say I got a table like this

╒═══════════════════════════════════════════════╕
│ 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;

}


Using the code above on the example table you can see on the very top of this post will output an array looking like this:

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"
),
);


How would I avoid these duplicates?

Thanks. Richard.

Answer

You are using $result->fetch_array() and this function, if used without a parameter will use the default parameter which is MYSQLI_BOTH which returns both a numeric array and an assoc array with each fetch

So either use $result->fetch_array(MYSQLI_ASSOC)

or you can use $result->fetch_assoc() which will return just an assoc array

Comments