Easy Mysql insert with PHP
Let’s see how to cut short code to insert or update mysql queries just with few lines of code.The key to making this happen is to name your html form elements with the same names as your column names.
<form name="myform" method="post" action="insert.php"> Name:<input type="text" name="name" /> Comment:<textarea cols="42" rows="8" name="comment"></textarea> <input type="submit" value="Send" /> </form>
Observe that there is no name provided for the submit button.Now on to the PHP code.
<?php
$keys = "";
$vals = "";
foreach($_POST as $key=>$val) {
$keys .= "`".$key."`,";
$vals .="'".$val."',";
}
//Remove the last comma, else SQL will fail
$keys = substr($keys,0,-1);
$vals = substr($vals,0,-1);
$sql = "insert into table_name ($keys) values ($vals)";
mysql_query($sql);
?>