Yunath Yunath - 1 month ago 19
MySQL Question

PHP MySQL Insert function

I'm a coop student that's been tasked with converting and access database to a MySQL database. I have all the information transferred and now I'm attempting to make a webapp to Insert into the table. The problem is there are 50+ tables with a varying number of columns. I found how to display the number of columns and their names with "SHOW COLUMNS FROM". i need to now insert them and this is where i find the issue.

$conn = new mysqli($servername, $username, $password, $db);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SHOW COLUMNS FROM $table";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)){
echo $row['Field']." <input type=text name=".$row['Field']."><br>";
}

echo"<input type=submit name=Insert>";

if(isset($_POST['Insert']))
{
$query = "INSERT INTO $table VALUES(while($row = mysqli_fetch_array($result)){echo''.$_POST['$row['Field']'].'';})";

if ($conn->query($query) === TRUE) {
echo "Record added successfully";
} else {
echo "Error adding record: " . $conn->error;
}
}


I am finding the error in the "$query=..." line

$query = "INSERT INTO $table VALUES(while($row = mysqli_fetch_array($result)){echo''.$_POST['$row['Field']'].'';})";

Answer

Get the while out of the string :

$query = "INSERT INTO $table VALUES(";
$comma = ""; // NO COMMA FOR THE FIRST VALUE.
while ( $row = mysqli_fetch_array($result) )
{ $query .= "$comma'" . $_POST[ $row['Field'] ] . "'";
  $comma = ","; // THERE IS NO COMMA FOR THE FIRST VALUE.
}
$query .= ")";