soft genic soft genic - 2 months ago 19
SQL Question

Database Connectivity in PHP - unexpected error

Following is my piece of code in which I am trying to create database connectivity. Please see the comments below in the code in which I mentioned where exactly the problem is occurring. Moreover, I also mentioned one connectivity code that is working fine.

Please let me know how I can call my

dbconfig.php
so it'll behave like that piece of code that results to successful connection.

Thanks

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

Answer

You are mixing mysql_* functions with PDO functions - first connecting to your database using mysql_connect and then using prepare() to query your database.

You should move to PDO completely, replace this line:

$dbconfig = mysql_pconnect($hostname_dbconfig, $username_dbconfig, $password_dbconfig) or trigger_error(mysql_error(),E_USER_ERROR); 

With this one:

$dbconfig = new PDO('mysql:dbname=' . $database_dbconfig . ';host=127.0.0.1', $username_dbconfig, $password_dbconfig);

And put this in your other file:

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