我有一长串表单值需要插入数据库。有没有一个有效的方法将所有这些值插入到数据库中的单独列中,而不是拥有一长串庞大的条件?
这是我的代码:
菲律宾比索:

// I've removed most of them to simplify demonstration
$title = isset($_POST['title']) ? $_POST['title'] : "";
$name = isset($_POST['name']) ? $_POST['name'] : "";
$description = isset($_POST['description']) ? $_POST['description'] : "";
$how_hear = isset($_POST['how_hear']) ? $_POST['how_hear'] : "";

// I have to do this for every single form element:
if (!empty($title)) {
    DB::query('INSERT INTO `table` (`title`) VALUES (?);', array($title));
}

最佳答案

$usrData = array(
    "user" => "hello",
    "pass" => "pass1",
    "mail" => "test@email.com"
);

$cols = "";
$vals = "";
foreach($usrData as $col => $val) {
    $col = mysql_real_escape_string($col);
    $val = mysql_real_escape_string($val);

    $cols.= "`{$col}`, ";
    $vals.= "'{$val}', ";
}
$query = "INSERT INTO `myTable` (". rtrim($cols, ", ") .") VALUES (". rtrim($vals, ", ") .");";
mysql_query($query);

关于php - 如何有效地将多个表单值插入到MySQL表中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29206914/

10-16 19:19
查看更多