Mysql& Php数据库连接错误

时间:2017-12-18 21:07:02

标签: php mysql

当我使用php连接到我的数据库时,我得到一个突然的错误,说"数据库连接失败"无论如何要修复它的登录和注册屏幕。感谢任何帮助过的人......

<?php
$connection = mysqli_connect('localhost', 'root','','test');
if (!$connection){
    die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
    die("Database Selection Failed" . mysqli_error($connection));
}


<?php
    //
    require('database.php');
    $connection = mysqli_connect('localhost', 'root','','test');
    // If the values are posted, insert them into the database.
    if (isset($_POST['Register'])){
        $username = $_POST['username'];
    $email = $_POST['email'];
        $password = $_POST['password'];

        $query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
         //echo $query;
        $result=mysqli_query($connection,$query);
        if($result){
            $smsg = "User Created Successfully.";
        }else{
            $fmsg ="User Registration Failed";
        }
    }
    ?>

1 个答案:

答案 0 :(得分:-1)

使用php连接数据库需要4个参数(主机,数据库用户,密码,数据库名称,passwd),现在使用db对象而不是程序性的“旧”行为更好:

function connection(){
    try{
        //host, user, passwd, DB name)
        $mysqli = new mysqli("localhost", $dbUser, $passwd, $dbName);
        if (!$mysqli->set_charset("utf8")) $msg = "error charset mySQLi"; else $msg = "Set UTF-8 ok";
        return $mysqli;
    }
    catch (Exception $mysqlin){
        echo "Error stablishing connection with database ".$mysqlin->getMessage();  
    }
}

然后您可以轻松连接如下:

$sql = "SELECT * FROM users;";
        if(!$result = connection()->query($sql)) echo "db query error"; else "query ok";
        $rs = mysqli_fetch_assoc($result);
//do whatever and, to get next line of results:
if($rs!=''){
    $rs = mysqli_fetch_assoc($result);
}

所以你在$ rs []数组上得到了一行结果。

编辑:您需要应用安全性,这是一个简单的连接,而不需要考虑。在php官方网页上查看mysqli bind params: http://php.net/manual/en/mysqli-stmt.bind-param.php

希望有所帮助