无法将数据连接到 MySQL [英] Trouble connecting data to MySQL

查看:50
本文介绍了无法将数据连接到 MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击提交按钮时,我似乎无法找出为什么我的 PHP 代码不允许我将信息存储在 MySQL 中.有人可以告诉我下面的代码有什么问题吗?

I can't seem to find out why my PHP code won't allow me to store the info in MySQL when I click the submit button. Can someone tell me whats wrong with the code below?

我想让用户提交他们的注册表并且他们的信息可以转移到 MySQL 数据库.然后,我希望将用户带到我的 index.html 文件.

I want to get it to the point where users submit their registration form and their info can get moved over to a MySQL database. Then, I want the users to be taken to my index.html file.

感谢任何帮助.谢谢

<?php 

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
        mysqli_select_db($conn, $mysql_database) or die("Could not select database");

$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];

if ($password == $password2)    {
        $sql = "INSERT INTO members (username, email, password) VALUES ('$userrname','$email','$password')";
} else  {
    echo "Your passwords must match";
}
?>

推荐答案

尝试使用 mysqli_query 实际运行查询.当您设置 $sql 时,所做的只是为查询设置了一个名为 $sql 的变量.另请注意,您在查询中设置了变量 $userrname,而它应该是 $username,正如上面的 $_POST 所设置的那样.我调整后的代码版本如下:

Try this using mysqli_query to actually run the query. When you set $sql all that did was set a variable named $sql to the query. Also note you set the variable $userrname in the query when it should be $username as set from the $_POST directly above. My adjusted version of your code below:

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$mysql_database = "21st";

$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Could not connect database");
mysqli_select_db($conn, $mysql_database) or die("Could not select database");

$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];

if ($password === $password2) {

  // Set the query.
  $sql = "INSERT INTO members (username, email, password)"
       . " VALUES (?, ?, ?)"
       ;

  // Bind the values to the query.
  mysqli_stmt_bind_param($sql, 'sss', $username, $email, $password);

  // Run the query.
  mysqli_query($conn, $sql);

  // Free the result set.
  mysqli_free_result($sql);

  // Close the connection.
  mysqli_close($conn);

}
else {
  echo "Your passwords must match";
}

这篇关于无法将数据连接到 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆