php - MySQL 连接功能不起作用?

标签 php mysql mysql-connect

我正在尝试连接到我的数据库,但它显示 mysql_connect 函数出错。

错误是: fatal error :未捕获错误:调用 C:\xampp\htdocs\Connect.php:12 中的未定义函数 mysql_connect() 堆栈跟踪:#0 C:\xampp\htdocs\Test.php(3): require() #1 {main} 抛出在第 12 行的 C:\xampp\htdocs\Connect.php

连接文件:

<?php  

$db_host = "localhost"; 
// Place the username for the MySQL database here 
$db_username = "root";  
// Place the password for the MySQL database here 
$db_pass = "";  
// Place the name for the MySQL database here 
$db_name = "oscar"; 

// Run the connection here  
$con = mysql_connect("db_host","$db_username","$db_pass");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("$db_name", $con);
try 
{
 $conn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_username, $db_pass);
// set the PDO error mode to exception
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 echo "Connected successfully"; 
}
catch(PDOException $e)
{
 echo "Connection failed: " . $e->getMessage();
}

?>

文本文件:

<?php
// Connect to the MySQL database  
require "Connect.php"; 
echo "Success";
?>

最佳答案

为什么同时使用 mysql_connect 和 PDO?并且 mysql 已被弃用,因此容易受到 sql 注入(inject)的攻击。<​​/p>

只有这段代码会连接到你的数据库

<?php
$db_host = "localhost";
// Place the username for the MySQL database here
$db_username = "root";
// Place the password for the MySQL database here
$db_pass = "";
// Place the name for the MySQL database here
$db_name = "oscar";


try {
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_username, $db_pass);
// set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

关于php - MySQL 连接功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43931470/

相关文章:

php - Backbone.js 模型 urlRoot 错误

php - Magento A-Z 页面

php - CodeIgniter 模块化扩展在 CentOS 上损坏

mysql - 使用 Python 将字段插入 MySQL

php - 可以通过命令行远程连接 MySQL,但从 Web 浏览器使用 php 的 mysql_connect 时会失败

PHP - 如何让 mysqli_connect() 返回资源,以便它可以与 Define() 一起使用

PHP-解析当前URL

mysql - 未知数量输入的数据库设计

c++ - 如何知道库是调试库还是发布?

php - 可捕获的 fatal error : Object of class stdClass could not be converted to string in.。尝试插入数据库时