我不知道这段代码有什么问题。数据没有插入数据库。
$connection = mysqli_connect('localhost', 'root', '', 'login-system');
if ($connection) {
echo "everything works fine";
} else {
echo "there is something wrong";
}
if (isset($POST['submit'])) {
$username = $POST['username'];
$password = $POST['password'];
$query = "INSERT INTO users(username, password)";
$query .= 'VALUES("$username", "$password")';
$result = mysqli_query($connection,$query);
if (!$result) {
die('Query Failed'. mysqli_error());
}
}
您对此有何建议? 请记住,服务器已连接到数据库,但未插入数据。
谢谢
答案 0 :(得分:3)
问题是您正在使用$POST['submit']
,这是错误的,您需要使用
$_POST['submit']
因为php没有任何名为$POST
的变量。
您的完整代码应如下所示。
include_once 'db.php';
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO users(username, password) VALUES('$username', '$password')";
$result = mysqli_query($connection,$query);
if (!$result) {
die('Query Failed'. mysqli_error($connection));
}
}
注意::您的代码可以进行SQL注入 攻击您需要使用准备好的查询。
答案 1 :(得分:1)
尝试不同的方式:)
$connection = mysqli_connect('localhost', 'root', '', 'login-system');
if ($connection) {
echo "everything works fine";
} else {
echo "there is something wrong";
}
if ($_SERVER['REQUEST_METHOD']=='POST') {
$username = $_POST['username'];
$password = $_POST['password'];
$query = sprint_f("INSERT INTO users set username='%s', password='%s'" ,$username,$password);
$result = mysqli_query($connection,$query);
if (!$result) {
die('Query Failed'. mysqli_error());
}
}
答案 2 :(得分:0)
您的$ query字符串更改为此查询 宽度。操作者附加2个字符串
include_once 'db.php';
if (isset($POST['submit'])) {
$username = $POST['username'];
$password = $POST['password'];
$query = "INSERT INTO users(username, password)";
$query .= 'VALUES("'.$username.'", "'.$password.'")';
$result = mysqli_query($connection,$query);
if (!$result) {
die('Query Failed'. mysqli_error());
}
}
答案 3 :(得分:0)
在查询串联中的VALUES之前添加一些空格
$connection = mysqli_connect('localhost', 'root', '', 'login-system');
if ($connection) {
echo "everything works fine";
} else {
echo "there is something wrong";
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO users(username, password)";
$query .= ' VALUES("$username", "$password")';// Here add space before VALUES
$result = mysqli_query($connection,$query);
if (!$result) {
die('Query Failed'. mysqli_error());
}
}
答案 4 :(得分:0)
我在我这边尝试过。我发现 $ _ POST 变量没有 submit ,因此它不会进入if块。如果条件允许,将其移除。新代码如下所示。
if ((is_array($_POST)) && (count($_POST) > 1)) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO users(username, password)";
$query .= " VALUES('$username', '$password')";
$result = mysqli_query($connection,$query);
if (!$result) {
die('Query Failed'. mysqli_error());
}
}
希望它会对您有所帮助。让我知道是否有任何问题。编码愉快:)