无法使用PHP将数据插入MySQL数据库

时间:2017-11-20 05:19:13

标签: php mysql

我无法将数据插入MySQL数据库。我不知道原因,因为没有触发错误。我在Windows上使用XAMPP来运行本地服务器。这是代码。如果有人可以帮忙的话会很棒。

我总是得到“未插入值”输出。当我通过SQL查询的VALUES('$ email',...)部分中的表单输入的确切值时,我也尝试打印$ query。

<?php


$dbconnect = mysqli_connect("localhost","root","","id3626001_login_details");

if (!$dbconnect) 
{
    die("Connection Failed" .mysqli_connect_error());
}

if (!mysqli_select_db($dbconnect, "id3626001_login_details"))
{
    echo "Could not connect to Database";
}

if (isset($_REQUEST['username']) && ($_SERVER["REQUEST_METHOD"] == "POST")){

$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];

// Inserting values into the database through a query
$query = "INSERT INTO user_registration (ID, email, username, password) VALUES ('$email', $username', '".md5($password)."')";

if (!mysqli_query($dbconnect, $query))
{   
    echo "Values not inserted";     
}

$result = mysqli_query($dbconnect, $query);

if($result){
    echo "Registration Successful";
    }
}
?>

2 个答案:

答案 0 :(得分:5)

您的查询存在问题,

1)您要传递的列数和值必须相同

2)您忘了放'(引用$username'

将您的查询更改为

// Inserting values into the database through a query

$query = "INSERT INTO user_registration ( email, username, password) VALUES ('$email', '$username', '".md5($password)."')";

在测试时,您不仅应该只打印查询,还应该复制该查询并通过[(localhost / phpmyadmin)&gt;直接将其运行到数据库中;选择你的数据库&gt; SQL]并查看触发查询时显示的错误。

更新

@Akintunde的建议

出于安全考虑,您不应该使用对SQL injections完全开放的这种插入方法,您必须遵循一些规则以避免让您的脚本成为sql注入的目标

使用Prepared Statements代替数据库操作

答案 1 :(得分:1)

在您的查询中,您忘记提出引号' - &gt; $username'

$query = "INSERT INTO user_registration (email, username, password) VALUES ('$email', '$username', '".md5($password)."')";

这里我们没有将Id作为参数传递,因此您需要在该数据库中为该表进行id自动增量。

为什么要将查询两次传递给mysqli_query(),你可以检查一次,

$result = mysqli_query($dbconnect, $query);
if ($result)
{   
  echo "Registration Successful";
}
else{
  echo "Values not inserted"; 
}
相关问题