如何使用PHP和MYSQL中的输入字段将表行数据提交到另一个表?
HTML
<form method="post" action="post.php">
<input type="number" name="code" placeholder="Code..."/>
<input type="submit" name="submit" value="Submit"/>
</form>
post.php中
if (isset($_POST['submit'])) {
$code = $_POST['code'];
$getCode = "SELECT * FROM products WHERE code=$code";
mysqli_query($connection, $getCode);
if ($_POST['code'] == $code) {
$migrating = "INSERT INTO managment(price) VALUES ($price) SELECT
price FROM products";
mysqli_query($connection, $migrating);
header("location: index.php");
}
}
我的代码出了什么问题?
答案 0 :(得分:0)
syntax是:
INSERT INTO managment(price) SELECT price FROM products
也许您想要添加WHERE
子句:
INSERT INTO managment(price) SELECT price FROM products WHERE code=$code
注意:在您的代码中,$_POST['code'] == $code
没有意义,因为之前有$code = $_POST['code']
。
我还建议您查看How can I prevent SQL injection in PHP?以确保查询安全。
您的代码已更新(未经测试):
if (isset($_POST['submit'])) {
$code = $_POST['code'];
$getCode = "SELECT * FROM products WHERE code=$code";
$result = mysqli_query($connection, $getCode);
if (!$result) die("Error: " . mysqli_error($connection));
$row = mysqli_fetch_assoc($result);
if ($row['code'] == $code) {
$migrating = "INSERT INTO managment(price)
SELECT price FROM products WHERE code=$code";
$result2 = mysqli_query($connection, $migrating);
if (!$result2) die("Error: " . mysqli_error($connection));
header("Location: index.php");
exit;
}
}