Hello.
I'm trying to make an simple dynamic script that will insert values into a table. I want to make it so it's not dependant on spesific column names, so it will break if I update/change the column names in eg phpmyadmin.
In other words the script should automatically recognize any new or changed columnnames.
The script below first prints out the column names with mysqli_fetch_field. Then prints out an form for the user to input values. Finally it's supposed to insert these values into the table. This is where my script doesn't work properly.
I get an warning message : Warning: Invalid argument supplied for foreach() in /var/www/utstyr/insert.php on line 24
0 row inserted into table equipement.
I'v also tried changing out mysqli_fetch_field with $POST, but that doesn't work either. Just echoing $values actually prints out the values to screen but doesnt insert them into the table. Also I don't want all of the data from $POST. Only the values.
Here is the script. Any suggestions are greatly apreciated.
<?php
echo "<a href=./>Home</a><br>";
# Connect to the DB
$conn = mysqli_connect("localhost", "user", "pass", "db");
# Check if post is empty and prints out the form if it is
if(!$_POST) {
if($query = mysqli_query($conn, "SELECT * FROM table")) {
print "<form action='".$_SERVER['PHP_SELF']."' method='post'><table>";
while($fetch_field = mysqli_fetch_field($query)) {
if($fetch_field->name=="id") { } else {
print "<tr><td>".$fetch_field->name."</td><td><input type='text' name='".$fetch_field->name."'></td></tr>";
}
}
}
print "<tr><td><input type='submit' name='submit' value='insert'></td></tr></form>";
}
# Check that atleast one field (name) is filled out.
elseif(empty($_POST['name'])) {
echo "You have to fill out all the fields";
}
# Inserts the values into the table
else {
mysqli_query($conn, "ALTER TABLE table AUTO_INCREMENT =0");
foreach($fetch_field->name as $value) {
mysqli_query($conn, "INSERT INTO table VALUES ($value)");
}
echo mysqli_affected_rows($conn)." row inserted into table utstyr.";
}
?>