-3

以下は、データベース接続を作成しようとしている私のコードです。問題が発生している場所を正確に説明したコードの以下のコメントを参照してください。さらに、正常に機能している1つの接続コードについても説明しました。

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

3 に答える 3

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();
?>
于 2012-06-01T11:04:43.637 に答える
3

これを試して

$connection = mysql_connect("localhost","root","") or die(mysql_error());
$db = mysql_select_db("database_name") or die(mysql_error());
于 2016-09-19T06:30:03.210 に答える
-1

データベースの選択をこれに変更します

mysql_select_db($database_dbconfig);
于 2012-06-01T11:04:56.680 に答える