使用php中的输入字段将表行数据提交到另一个表
问题描述:
How can I submit a table row data to another table using an input field in PHP and 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");
}
}
What is wrong with my code?
如何使用PHP和MYSQL中的输入字段将表行数据提交到另一个表? p>
HTML p>
&lt; form method =“post”action =“post.php”&gt;
&lt; input type =“number”name =“code”占位符=“代码...”/&gt;
&lt; input type =“submit”name =“submit”value =“提交”/&gt;
&lt; / form&gt;
code> pre>
Post.php p>
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管理(价格)价值($ price)SELECT
价格FROM产品”;
mysqli_query($ connection,$ migrating);
header(“location:index.php “);
}
}
code> pre>
我的代码出了什么问题? p>
div>
答
The syntax is :
INSERT INTO managment(price) SELECT price FROM products
Maybe you want add a WHERE
clause :
INSERT INTO managment(price) SELECT price FROM products WHERE code=$code
Note: in your code, $_POST['code'] == $code
doesn't make sense, because of $code = $_POST['code']
earlier.
I also suggest you to have a look to How can I prevent SQL injection in PHP? to secure your queries.
Your code updated (untested) :
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;
}
}