因此,我将在使用时会发生变化的值数组传递给一个方法,然后将它们插入数据库。我的问题是绑定参数的方式。
public function insertValues($table, $cols, $values)
{
$mysqli = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBDATABASE);
$colString = implode(', ', $cols); // x, x, x
$valString = implode(', ', array_fill(0, count($values), '?')); // ?, ?, ?
$sql = "INSERT INTO $table ($colString) VALUES($valString)";
if (!$stmt = $mysqli->prepare($sql))
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
// THIS IS THE PROBLEM AREA
foreach ($values as $v)
if (!$stmt->bind_param('s', $v))
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
if (!$stmt->execute())
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
$stmt->close();
$mysqli->close();
}
我需要一种方法来一次绑定所有参数,而不是一次绑定一个,但我想不出一种有用的方法来做到这一点。任何帮助将不胜感激。