以下是我正在尝试创建数据库连接的代码段。请在我提到的代码中查看下面的注释,问题恰好发生在哪里。此外,我还提到了一个工作正常的连接代码。
请告诉我如何拨打我的dbconfig.php
,以便它的行为类似于导致连接成功的代码。
由于
<?php
//Including Header file for the connectivity to the database
require_once('Connections/dbconfig.php');
mysql_select_db($database_dbconfig, $dbconfig);
// If I use the following line of code for connectivity then it works perfectly fine:
//$dbh = new PDO('mysql:host=localhost;dbname=rare','root','');
$dbh= $dbconfig;
$q = 'select resident_id,u_first,u_last from z_events group by resident_id';
/*
The following error will occur when I try to make a connection from the header file:
Fatal error: Call to a member function prepare() on a non-object in C:\Users\QAD\Downloads\CAR\index12 - Copy.php on line 200
*/
$user = $dbh->prepare($q);
$user->execute();
?>
dbconfig.php
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_dbconfig = "localhost";
$database_dbconfig = "rare";
$username_dbconfig = "root";
$password_dbconfig = "";
$dbconfig = mysql_pconnect($hostname_dbconfig, $username_dbconfig, $password_dbconfig) or trigger_error(mysql_error(),E_USER_ERROR);
?>
答案 0 :(得分:3)
您正在将mysql_ *函数与PDO函数混合使用 - 首先使用mysql_connect连接到数据库,然后使用prepare()查询数据库。
您应该完全转移到PDO,替换此行:
$dbconfig = mysql_pconnect($hostname_dbconfig, $username_dbconfig, $password_dbconfig) or trigger_error(mysql_error(),E_USER_ERROR);
有了这个:
$dbconfig = new PDO('mysql:dbname=' . $database_dbconfig . ';host=127.0.0.1', $username_dbconfig, $password_dbconfig);
并将其放在您的其他文件中:
<?php
//Including Header file for the conectivity to the database
require_once('Connections/dbconfig.php');
$dbh = $dbconfig;
$q = 'select resident_id,u_first,u_last from z_events group by resident_id';
$user = $dbh->prepare($q);
$user->execute();
?>
答案 1 :(得分:3)
试一下
$connection = mysql_connect("localhost","root","") or die(mysql_error());
$db = mysql_select_db("database_name") or die(mysql_error());
答案 2 :(得分:-1)
将您的数据库选择更改为此
mysql_select_db($database_dbconfig);