1

I'm trying to get specific columns from a database table rather than selecting the whole table and put them to json format. There's no need for irrelevant columns. This is what i have so far.

$sql = "SELECT (col1,col2,col3) FROM table1";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    $emparray = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

    mysqli_close($connection);

This code returns with an error: Operand should contain 1 column(s)

Any ideas what I'm doing wrong?

Thanks

Michael
  • 109
  • 1
  • 1
  • 13

2 Answers2

1

The error is with the query. You are selecting 3 columns but putting them in brackets () would project them as single column. Try -

SELECT col1,col2,col3 FROM table1

You can refer to this answer for details.

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
-1

You have to specify column name when access query result.

$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

$sql = "SELECT col1,col2,col3 FROM table1";

$emparray = array();
$index = 0;
while($row =mysqli_fetch_assoc($result))
{
    $emparray[$index][] = $row['col1'];
    $emparray[$index][] = $row['col2'];
    $emparray[$index][] = $row['col3'];

    $index++;
}
echo json_encode($emparray);

mysqli_close($connection);
jonggu
  • 146
  • 1
  • 2
  • 10