如何连接到数据库?

r3i60tvu  于 2021-06-18  发布在  Mysql
关注(0)|答案(4)|浏览(366)

我尝试连接数据库,以便通过以下方式创建聊天:
https://youtu.be/k8dhwcdkanm
我想知道我需要在这段代码中更改什么才能将其连接到db:

<?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");

?>

谢谢您。

fgw7neuy

fgw7neuy1#

如果您试图从另一个文件连接数据库,则必须遵循以下步骤
第一步: 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.

第二步: 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 你错了。因此,查询将失败,插入操作将不会完成。所以请仔细检查变量,然后继续编码。
希望这对你有帮助。谢谢。

krcsximq

krcsximq2#

这是连接代码。

$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
gfttwv5a

gfttwv5a3#

你检查过“values()”里面的变量名了吗。我认为应该是:值('$uname'、'$email'、'$pass');

s6fujrry

s6fujrry4#

请尝试以下代码:

$conn = new mysqli($servername, $username, $password, $dbName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";

return $conn;

相关问题