我尝试通过以下方式连接数据库以创建聊天记录:
我想知道我需要在此代码中进行哪些更改才能将其连接到数据库:
<?php
include 'dbh.php';
$uname= $_POST['username'];
$email=$_POST['email'];
$pass=$_POST['password'];
$sql="insert into signup(username,email,password)
values ('$username','$email','$password')";
$result=$conn->query($sql);
header("Location:index.php");
?>
谢谢。
答案 0 :(得分:0)
这是连接代码。
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
答案 1 :(得分:0)
您是否在“ values()”中检查了变量名称。 我认为应该是: 值(“ $ uname”,“ $ email”,“ $ pass”)”;
答案 2 :(得分:0)
如果您尝试从另一个文件连接数据库,则必须执行以下步骤
步骤1: db.php
(将提供两种连接方法)
$host="localhost";
$user="phpmyadmin1";
$password="123456";// This can be empty in some cases
$db="XXX"; // XXX - DB Name
// This is First type of connection with returning
$con_1 = mysqli_connect($host,$user,$password,$db); // Here the $con will be acting as the connection variable
// This is Second type of connection with returing
$con_2 = new mysqli($host,$user, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $con_2; // This will return the connection variable to necessary pages that are needed.
第2步: signup.php
在此,我们必须包含db.php文件,然后继续进行连接。
<?php
include('db.php');
$uname= $_POST['username'];
$email=$_POST['email'];
$pass=mysqli_real_escape_string($con,$_POST['password']);
$sql="INSERT INTO `signup`(username,email,password) VALUES ('".$uname."','".$email."','".$pass."')";
$result=mysqli_query($con,$sql); // Here we have to add the connection variable
header("Location:index.php"); // Used for Header Relocation
?>
在insert语句中,某些变量,例如
$uname
,$pass
是错误的。因此,查询将失败,并且插入操作将不会完成。因此,请仔细检查变量,然后进行编码。
希望这可能对您有所帮助。谢谢。
答案 3 :(得分:0)
尝试以下代码:
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
return $conn;