Using a php foreach loop with ALTER TABLE mysql to update multiple column names

716 views Asked by At

My first post on stack after all these years of learning :) So much to thank this community. But anyway...

I'm trying to add new column names to a database dynamically based on what my array will hold. The array's data is unknown/can change, otherwise I'd set it all manually in mysql.

So far, I can get the ALTER TABLE to add a single column entry with this code, but I can't get the foreach loop to iterate through the array for the others following. Surely you can do this I presume?

$test_prod = [ 
    ['name' => 'sunny', 'was' => 111, 'now' => 222,],
    ['name' => 'moon', 'was' => 333, 'now' => 444,],
    ['name' => 'eclipse', 'was' => 555, 'now' => 666,]
];

foreach ($test_prod as $v) {
    $t = $v['name'];
    $column_name = $conn->real_escape_string($t);   
    $update = mysqli_query($conn, "ALTER TABLE table ADD $column_name    VARCHAR(255)") or die(mysql_error());
    return $update;
}
0

There are 0 answers