无法连接php和我的sql

时间:2017-12-15 10:47:38

标签: php mysql

当我使用邮递员尝试php脚本时,我收到此错误:Unable to connect

凭证是正确的。

这是我的代码:

dbDetails.php

<?php
 define('DB_HOST','localhost');
 define('DB_USER','root');
 define('DB_PASSWORD','root');
 define('DB_DATABASE','prova');

 $con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE) or die('Unable to Connect');

upload.php的:

<?php
     require_once 'dbDetails.php';

//response array
$response = array();


if($_SERVER['REQUEST_METHOD']=='POST'){

    if(isset($_POST['url']) and isset($_POST['name'])){

             $con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die('Unable to Connect...');

        //getting name from the request
        $url = $_POST['url'];
        $name = $_POST['name'];

        try{
             $sql = "INSERT INTO `pdfs` (`id`, `url`, `name`) VALUES (NULL, '$url', '$name');";

                if(mysqli_query($con,$sql)){

                //filling response array with values
                $response['error'] = false;
                $response['url'] = $url;
                $response['name'] = $name;
            }
            //if some error occurred
        }catch(Exception $e){
            $response['error']=true;
            $response['message']=$e->getMessage();
        } 
        //closing the connection
        mysqli_close($con);
    }else{
        $response['error']=true;
        $response['message']='Please choose a file';
    }

    //displaying the response
    echo json_encode($response);
}

有人可以帮助我吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

请使用如下: -

$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);