If I have [x]
[y]
[z]
columns inside a [mytable]
table in MSSQL, I would like to know how can I loop through each of them using php in order to have all of the columns' name? The reason is because I could potentially delete or add a column so that php code would make this dynamic without having to hardcode the php page. Basically, if I could have a php code similar to the following,
foreach( COLUMN as $columname in [SQL table])
echo "$columname";
// do something else
}
it would be awesome.
Select the data from the INFORMATION_SCHEMA.COLUMNS system view. Filtered on your table name.
select column_name
from information_schema.columns
where table_name = 'mytable'
Returns
Column_name
-----------
x
y
z
This gives you a resultset containing all column names, loop through and use the values.
If it's PHP, your foreach should look like this:
foreach ($rows as $row) {
var_dump($row); // you'll see columns and values
echo $row['user_id']; // for example
}
Or, you can do a key/value foreach:
foreach ($rows as $row) {
foreach($row as $column => $value){
echo 'Column '.$column.' has value '.$value."
";
}
}