PHP中的数据库连接-意外错误

PHP中的数据库连接-意外错误,php,sql,connection,database-connection,connection-string,Php,Sql,Connection,Database Connection,Connection String,下面是我试图创建数据库连接的代码片段。请参阅下面代码中的注释,我在其中提到了问题发生的确切位置。此外,我还提到了一个工作正常的连接代码 请让我知道如何调用我的dbconfig.php,这样它的行为就像导致成功连接的那段代码一样 谢谢 <?php //Including Header file for the connectivity to the database require_once('Connections/dbconfig.php'); mysql_select_db($

下面是我试图创建数据库连接的代码片段。请参阅下面代码中的注释,我在其中提到了问题发生的确切位置。此外,我还提到了一个工作正常的连接代码

请让我知道如何调用我的
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); 
?>

您正在混合使用mysql_*函数和PDO函数-首先使用mysql_*连接到数据库,然后使用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();
?>

将数据库选择更改为

mysql_select_db($database_dbconfig);

试试这个

$connection = mysql_connect("localhost","root","") or die(mysql_error());
$db = mysql_select_db("database_name") or die(mysql_error());

为什么你要尝试将PDO和mysql混合使用?我不知道,因为我正在处理其他项目,这就是为什么我们有:-)好的,我会调查的谢谢…我在查询中使用了直接变量谢谢你的帮助。。。。。我不知道PDO,因为我正在另一个项目中工作。