MySQL Connect功能不起作用?

时间:2017-05-12 07:08:46

标签: php mysql mysql-connect

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

错误是: 致命错误:未捕获错误:在C:\ xampp \ htdocs \ Connect.php中调用未定义函数mysql_connect():12堆栈跟踪:#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";
?>

4 个答案:

答案 0 :(得分:3)

为什么你同时使用mysql_connect甚至是PDO?并且不推荐使用mysql,因此容易受到sql注入。

只有此代码才能连接到您的数据库

delimiter $$
CREATE  TRIGGER  updateIsChanged
BEFORE UPDATE  ON manage_product
FOR EACH ROW
BEGIN
    IF NEW.`status` <> OLD.`status` || NEW.sale_profit <> OLD.sale_profit THEN
        SET NEW.is_changed = 1;
END IF;
END$$

答案 1 :(得分:0)

函数mysql_connect是不推荐使用的函数。相反,您应该使用mysqli_connect详细了解此here

以下代码应该有效:

<?php
/**
 * Created by PhpStorm.
 * User: ...
 * Date: 5-12-2017
 * Time: 09:47
 * Database connection.
 */
?>
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'admin');
define('DB_PASSWORD', 'admin');
define('DB_DATABASE', 'your_database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

答案 2 :(得分:0)

在PHP 5.5.0中不推荐使用mysql函数。我已经更改了代码中的一些更改。在mysqli connect语句中添加了$符号。

$con = mysqli_connect("$db_host","$db_username","$db_pass");
if (!$con)
{
  die('Could not connect: ' . mysqli_error());
}
mysqli_select_db("$db_name", $con);

答案 3 :(得分:0)

尝试使用mysqli

<?php
$db_host = "localhost"; 
$db_username = "root"; // Place the username for the MySQL database here 
$db_pass = "";// Place the password for the MySQL database here  
$db_name = "test";// Place the name for the MySQL database here 
$conn = new mysqli($db_host, $db_username, $db_pass,$db_name);

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

这很有效。