php数据库连接功能

时间:2016-10-24 13:04:50

标签: php mysql

我正在尝试使用此代码连接到mySQL数据库,但我总是收到错误说

  

致命错误:未捕获错误:调用未定义函数mysql_connect()

这是我的代码;

<?php

        $servername = "";
        $user = "";
        $pwd = "";
        $dbname = "";


    function connexion()
        {
            global $servername, $user, $pwd, $dbname;
            $db=mysql_connect($servername,$user,$pwd) or die("Database connection failed: ".mysql_error());
            mysql_select_db($dbname,$db);
        }
?>

关键是在用户输入正确的输入后调用函数connecxion()。你能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:0)

使用PDO(PHP数据对象)安全

<?php
 try {
    $yourHandler = new PDO('mysql:dbhost=127.0.0.1;dbname=yourdbname;', 'user', 'pass'); //creates a new instance of the PDO database class and passes it to your handler and creates database connection 
    $yourHandler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //sets the error mode so you can catch any errors that may occur
}  catch (PDOException $e) {
     echo $e->getMessage(); //echoes the errors
     die(); //kills the page 
}
?>