2012-06-01 21 views
-3

以下是我嘗試創建數據庫連接的一段代碼。請在下面的代碼中看到我提到的問題發生的地方。此外,我還提到了一個工作正常的連接代碼。PHP中的數據庫連接 - 意外錯誤

請讓我知道我可以打電話給我的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

爲什麼你想混合PDO和'mysql_ *'???? – PeeHaa

+0

我不知道它,因爲我正在對別人項目 –

+0

這就是爲什麼我們有[文檔](http://www.php.net/manual/en/):-) – PeeHaa

回答

3

你混合mysql_ *函數與PDO功能 - 首先使用的mysql_connect連接到數據庫,然後用準備()來查詢數據庫。

你應該搬到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(); 
?> 
+0

我使用直接變量進入我的查詢感謝您的幫助.....我didnot知道PDO,因爲我在別人的項目工作。 –

-1

改變你數據庫選入此

mysql_select_db($database_dbconfig); 
3

嘗試這個

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