gpt4 book ai didi

php - 在 PDO 连接字符串中使用常量并使用 PDO 连接调用函数

转载 作者:行者123 更新时间:2023-12-04 02:57:44 25 4
gpt4 key购买 nike

<分区>

我在 PDO 连接中使用常量以及调用包含 PDO 连接的函数时遇到问题。

我只在需要时才使用该功能连接数据库。在不需要 DB 工作的页面上,无需连接。

我已经尝试了很多,但无法弄清楚我哪里出错了。

<?php
/** The name of the database */
define('DB_NAME', 'dev-db');

/** MySQL database username */
define('DB_USER', 'root');

/** MySQL database password */
define('DB_PASSWORD', 'dxdb');

/** MySQL hostname */
define('DB_HOST', 'localhost');

function connect(){
try
{**//Here's where the first problem is**
$conn = new PDO('mysql:host=DB_HOST;dbname=DB_NAME',DB_USER,DB_PASSWORD);
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
}

connect();// Here's where it fails again

$sql = 'insert into names (names) values (:what)';
$what = "testValue";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':what', $what, PDO::PARAM_STR, 5);
$stmt->execute();

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com