我有一个由三个表组成的基本数据库:
产品表包含所有可用产品的目录,订单表包含所有订单参考的列表及其各自的日期,最后order_line表包含有关每个命令中订购的信息的信息
这是我用来在订单表中插入订单及其行到Order_Line表的代码:
<?php
if (isset($_POST['ref'])) {
$ref = $_POST['ref'];
$date = $_POST['date'];
$choosed_product = $_POST['choosed_product'];
$quantity = $_POST['quantity'];
$cn = mysqli_connect("localhost", "root", "");
mysqli_select_db($cn, "vente_db");
$res = mysqli_query($cn, "select * from commande where ref=" . $ref);
$cn->close();
if ($res != null) {
$cn->query("insert into Order_Line values (" . $choosed_product . ",$ref,$quantity)");
} else {
$co = mysqli_connect("localhost", "root", "");
mysqli_select_db($co, "vente_db");
mysqli_query($co, "insert into Commande
values('$ref',''$date'')");
mysqli_query($co, "insert into Order_Line values
(" . $choosed_product . ",$ref,$quantity)");
}
}
?>
但是当我检查数据库时,我找不到插入的行,你可以帮我解决一下代码中的问题
[编辑]:我知道我的代码容易受到sql注入攻击,但这仅适用于学校项目,我们并不需要保护数据库免受黑客攻击。
答案 0 :(得分:2)
此代码存在很多问题。您的代码非常容易受到SQL注入攻击!我已经评论了代码中的所有内容:
$cn->close();
$co = mysqli_connect("localhost", "root", ""); mysqli_select_db($co, "vente_db");
使用之前的连接。更正后的代码:
<?php
if (isset($_POST['ref'])) {
// Put connection string in the first line for making it available to use.
// Add the DB selector to the connection.
// Give an alternate message if connection fails.
$cn = mysqli_connect("localhost", "root", "", "vente_db") or die("Cannot Connect. " . mysqli_connect_error());
// Make sure you sanitize the data.
$ref = mysqli_real_escape_string($cn, $_POST['ref']);
$date = mysqli_real_escape_string($cn, $_POST['date']);
$choosed_product = mysqli_real_escape_string($cn, $_POST['choosed_product']);
$quantity = mysqli_real_escape_string($cn, $_POST['quantity']);
// Optional: Make sure you backtick the column names and add single quotes for values.
$res = mysqli_query($cn, "select * from `commande` where `ref`='" . $ref . "'");
// This is not needed here.
// $cn->close();
if ($res != null) {
// Make sure you use the same implementation. Either OOP or Procedural.
mysqli_query($cn, "insert into `Order_Line` values ('" . $choosed_product . "', '$ref', '$quantity')");
} else {
// You don't need another connection.
// $co = mysqli_connect("localhost", "root", "");
// mysqli_select_db($co, "vente_db");
// Use the previous connection.
// You have an error in the SQL Syntax with double single quotes.
mysqli_query($cn, "insert into `Commande` values('$ref', '$date')");
// Add single quotes for the values.
mysqli_query($cn, "insert into `Order_Line` values ('" . $choosed_product . "', '$ref', '$quantity')");
}
}
?>
这应该可行。如果没有,至少会告诉你它失败的原因。