My situation is this:
- I have an array that contains the names of the columns of a table
- I must, with a loop , iterates through the array and check if that field (this column name) exists in the table
If it exists, I do not do anything, otherwise I have to add
$array_column = ["column1 NOT NULL","column2 NOT NULL","column3 NOT NULL","column4 NOT NULL"]; for($j = 0 ; $j < count($array_column) ; $j++){ $query = "SELECT ".$array_column[$j]." FROM my_table"; $result = $db->query($query); $check = false; //try{ foreach ($result as $row) { //error here $check = true; } //}catch (Exception $e) { //echo "here"; //$check = false; //} if(!$check){ echo "column [".$array_column[$j]."] to add <br>"; } }
But when I find a column that does not exist in the table, php gives me error
Warning: Invalid argument supplied for foreach ()
I also tried a TryCatch, but the same error. I wish that php did not return that error when it doesn't finds a column
UPDATE 1 :
i try this , it works, but unfortunately not when there are no records in the table
$select = $db->query('SELECT * FROM mytable');
$total_column = $select->columnCount();
var_dump($total_column);
for ($counter = 0; $counter <= $total_column; $counter ++) {
$meta = $select->getColumnMeta($counter);
$column[] = $meta['name'];
}
print_r($column);
UPDATE 2 : This solution works perfectly, even if there are no records in the table!
$result = $db->query("PRAGMA table_info(test2)");
$result->setFetchMode(PDO::FETCH_ASSOC);
$meta = array();
foreach ($result as $row) {
array_push($meta, $row['name']);
}