我有一个表格(使用php从另一个网站抓取),但现在我想将其内容导入我的数据库(而不仅仅是打印出表格)。
这是使用以下代码的表中的打印输出 (https://i.stack.imgur.com/NnbAo.png):
<?php
$uitvoer = getTable();
echo "<table">;
foreach ($uitvoer as $row) {
echo "<tr>";
foreach ($row as $col) {
echo "<td>" . $col . "</td>";
}
echo "</tr>";
}
echo"</table>";
?>
当我尝试这样做时,我的数据库没有任何反应:
<?php
$con = mysqli_connect("mysql1.000webhost.com","a2902119_lowavol","pswd")
$uitvoer = getTable();
foreach ($uitvoer as $row) {
foreach ($row as $col) {
$query += "'" . $col . "', ";
}
$sql="INSERT INTO test (cel1, cel2, cel3, cel4, cel5, cel6, cel7, cel8, cel9) VALUES ($query)";
mysqli_query($con, $sql);
}
?>
我对PHP知之甚少。谢谢你帮助我!
PHP 的连接运算符是 (.) 而不是 (+)
<?php
$con = mysqli_connect("mysql1.000webhost.com","a2902119_lowavol","pswd")
$uitvoer = getTable();
foreach ($uitvoer as $row) {
$query = array();
$insert = "";
$insert_values = "";
foreach ($row as $col) {
$query[] = $col;
}
$insert_values = implode("','", $query) ;
$insert = "'".$insert_values."'";
$sql = "INSERT INTO test (cel1, cel2, cel3, cel4, cel5, cel6, cel7, cel8, cel9) VALUES ($insert)";
mysqli_query($con, $sql);
}
?>
您的查询将如下所示:
INSERT INTO test (....) VALUES (val, val, val, )
这显然是一个语法错误...尝试将字段添加到数组中:
foreach ($uitvoer as $row) {
$fields = array();
foreach ($row as $col) {
$fields[] = $col; // TODO: add escaping!
}
// now you can build the values list with implode
$values = implode(', ', $fields);
$sql="INSERT INTO test (...) VALUES ($values)";
有关详细信息,请参阅有关implode()
的文档。
使用预准备语句:
$sql="INSERT INTO test (cel1, cel2, cel3, cel4, cel5, cel6, cel7, cel8, cel9) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "sssssssss", $row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7], $row[8]);
foreach ($uitvoer as $row) {
mysqli_stmt_execute($stmt);
}
尝试回显$sql
。我认为最后有一个逗号。
用
$query = substr($query, 0, strlen($query) - 1)
为了删除$query
的最后一个字符
(编辑命令)