Webeng Webeng - 7 months ago 10
SQL Question

SELECT 1 FROM table, weird print_r result

From what I have read, when executing the following sql command and fetchAll() on my table with 6 rows and 11 columns:

$sql = "SELECT 1 FROM table";
$sqlPrepared = $conn->prepare($sql)
$sqlPrepared->execute()
$result = $sqlPrepared->fetchAll();
$print_r($result);


I should be getting 6 rows of just one value in each row, with the value 1 inside each of those values. However, I am getting 6 rows of two values in each row, with the value 1 inside each of those values:

Array (
[0] => Array (
[1] => 1
[2] => 1 )
[1] => Array (
[1] => 1
[2] => 1 )
[2] => Array (
[1] => 1
[2] => 1 )
[3] => Array (
[1] => 1
[2] => 1 )
[4] => Array (
[1] => 1
[2] => 1 )
[5] => Array (
[1] => 1
[2] => 1 )
)


QUESTION 1: Why am I getting 2 values for each array instead of just 1?

QUESTION 2: Instead of the inner arrays being

Array (
[1] => 1 ...


why doesn't it start from [0]?:

Array (
[0] => 1 ...

Answer

If you don't provide any flag on ->fetchAll() method, this includes the associative and numeric indices on the multidimensional array row.

So when you used SELECT 1 FROM, the associative index is 1 (meaning, column name is 1), and since array keys are unique, the numeric index adjusted, the numeric index with the value pair is assigned to 2.

Comments