简体   繁体   中英

Using Foreach loop for inserting data into 70 fields long database

I have 70 text fields in my HTML form. I want to insert data from those fields to the database using php and mysqli. So I thought of using the foreach loop while creating the sql query..I tried the following, but I am not able to get the required result.

foreach ($_POST as $key => $value) {
$f = $f . "," . $key ;
$v = $v . ",'" . $value . "'";      
}
$sql = "insert into table1($f) values ($v)";

The variable f is supposed to carry a string of comma seperated field names which are fields of the $_POST array. While variable v is to carry single quoted comma seperated values of the $_POST array. I am getting an extra comma in the starting of f and v right now. How to remove that.

Please help!

you should use rtrim() to remove that extra commas from the right side

foreach ($_POST as $key => $value) {
$f = $f . "," . $key ;
$v = $v . ",'" . $value . "'";      
}
$f = rtrim($f,',');
$v = rtrim($v,',');
$sql = "insert into table1($f) values ($v)";

rtrim($f, ",") would cut trailing commas.

trim($f, ",") would cut trailing and prefixing commas.

you can also use substr() to remove last character from string like below

substr($f, 0, -1);
substr($v, 0, -1);

further reading for

trim() : http://php.net/trim

rtrim() : http://php.net/rtrim

substr() : http://php.net/substr

EDIT A better way would be

$f = array(); // create blank arrays
$v = array();
foreach ($_POST as $key => $value) 
{
    $f[] = $key; // push values to the array
    $v[] = $value;      
}
$f1 = implode(",", $f); // convert array to comma separated string
$v1 = implode(",", $v);
$sql = "insert into table1($f1) values ($v1)";

let me know if that helped you..

Try this

foreach ($_POST as $key => $value) {
$f .= $f . "," . $key ;
$v .= $v . ",'" . $value . "'";      
}
$f = ltrim($f,',');
$v = ltrim($v,',');
$sql = "insert into table1($f) values ($v)";

Better to check first using isset() before prefixing comma, this will also remove the warnings you are getting.

 foreach($_POST as $key => $value) {
        $f = isset($f) ? $f . "," . $key : $key;
        $v = isset($v) ? $v . "," . $value : $value;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM