在PDO连接字符串中使用常量并通过PDO连接调用函数 [英] Using constants in a PDO connection string and calling a function with a PDO connection

查看:84
本文介绍了在PDO连接字符串中使用常量并通过PDO连接调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having problems with using constants in a PDO connection and when calling a function containing a PDO connection.

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

I'm using the function to connect the the DB only when needed. On pages where no DB work is needed, there's no need to connect.

我已经尝试了很多,但是无法弄清楚我要去哪里.

I've tried a lot, but can't figure where I'm going wrong.

<?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();

推荐答案

事实上,这个问题与PDO无关,而与PHP strings 无关.

As a matter of fact, this question has nothing to do with PDO, but rather with PHP strings.

所以,问题是,如何在字符串中使用常量?".

So, the question is, "How to use a constant in a string?".

答案很简单-将它们与字符串连接起来.

And the answer is fairly simple - concatenate them with strings.

此外,您的连接方式也是错误的.请参阅标签Wiki 以获得正确的方法

Also, the way you are connecting is wrong. Refer to the tag wiki for the proper way

第二个问题与PDO无关,只是变量范围问题.只需让您的函数返回$conn变量,然后调用

Your second issue has nothing to do with PDO again, being just variable scope problem. Just make your function return $conn variable, and then call it

$conn = connect();

此外,在使用PDO的情况下,没有必要为主机和数据库定义单独的常量-DSN是一个独立的实体,类似于其他驱动程序中的HOST.

Also, there is no point in defining separate constants for host and database in case of using PDO - DSN is a distinct entity, similar to HOST in other drivers.

因此,代码可能是(尽管我不确定dev-db是否为有效的数据库名称):

So, the code could be (though I am not sure if dev-db being valid database name):

define('DB_DSN', 'mysql:host=localhost;dbname=dev-db;charset=utf8');
define('DB_USER', 'root');
define('DB_PASSWORD', 'dxdb');

function connect() 
{
    $opt = array(
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    );
    return new PDO(DB_DSN,DB_USER,DB_PASSWORD, $opt);
}
$conn = connect();

这篇关于在PDO连接字符串中使用常量并通过PDO连接调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆