I have a php file and a sample form which is quite big ( around 60 fields and all optional ) Now What i want to do is get whatever parameters were passed and insert them to the table. I created a sample for 15 fields, but i can't go on and keep doing this for 60 items.
$a1 = $_REQUEST['a1'];
$a2= $_REQUEST['a2'];
$a3= $_REQUEST['a3'];
$a4= $_REQUEST['a4'];
$a5= $_REQUEST['a5'];
$a6= $_REQUEST['a6'];
$a7= $_REQUEST['a7'];
$a8= $_REQUEST['a8'];
$a9= $_REQUEST['a9'];
$a10= $_REQUEST['a10'];
$a11 = $_REQUEST['a11'];
$a12 = $_REQUEST['a12'];
$a13 = $_REQUEST['a13'];
$a14 = $_REQUEST['a14'];
$id = $_REQUEST['id'];
include 'conn.php';
$sql = "insert into med_history (a1 ,a2 ,a3 ,a4 ,a5 ,a6 ,a7 ,a8 ,a9 ,a10 ,a11 ,a12 ,a13,a14,id) values(
'$a1','$a2','$a3','$a4','$a5','$a6','$a7','$a8','$a9','$a10','$a11','$a12','$a13','$a14','$id')";
@mysql_query($sql);
echo "Inserted successfully";
Also with this one the problem is error is recieved if some parameter is not passed. So, how to fix it.
I am not using PDO or mysqli because this is done on testing server and not on actual server. When i migrate to the production server i will make the PDO connection
I hope this piece of code would help you:
$a = array();
foreach ( $_REQUEST AS $key => $value ) {
# !!! make some tests on key and value ... e.g.
if ( preg_match("/^a\d+$/", $key) ) {
$a[] = ' `'.$key.'` = "'.mysql_real_escape_string($value).'"';
}
}
if ( count($a) ) {
$sql = "insert into med_history SET ".implode(', ', $a);
mysql_query($sql) or exit(mysql_error());
echo "Inserted successfully";
}
simple solution
<?php
$first_string="";
$second_string="";
if(isset($_REQUEST['a1']))
{
$first_string.=",a1";
$second_string.=",$a1"
}
//do this to all values and after u finish u need delete the first (,) from first and second string
$first_string=substr($first_string,1);
$second_string=substr($second_string,1);
include 'conn.php';
$sql="insert into med_history(".$first_string.",$id)values(".$second_string.",id)";
@mysql_query($sql);
echo "Inserted successfully";
?>
u can use your skills as a programmer to make the code good and small using for loops,for each ..etc , but this is the general idea to help you with the (not passed parameters error) i hope this is what you looking for