Reputation: 57
I am trying to code an ajax chat application using php and my sql. I have a file called connect.php that looks like this:
mysql_connect("host", "username", "password");
mysql_select_db("database name");
I have another file called Core.php that needs this same connection to the database in order to get the chat messages from my database. Core.php looks like this:
class Core {
protected $db, $result;
private $rows;
public function __construct() {
$this->db = new mysqli('host', 'username', 'password','database name') or die('Connection Failure');
}
}
How do I set $this->db to the same connection I already have open?
As it is right now connect.php is called in my init.php file before Core.php and results in the chat messages not showing up in the box. If I comment out the call for connect.php then the chat messages display but all of the users login data can't be accessed and the user gets logged out. Can anyone help me with this? It's driving me crazy
EDIT: This is my init.php file where core.php and connect.php are called
ob_start();
session_start();
error_reporting(0);
$current_file = explode('/',$_SERVER['SCRIPT_NAME']);
$current_file = end($current_file);
require 'core/database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
require 'classes/Core.php';
Upvotes: 3
Views: 399
Reputation: 3972
I'm not 100% sure what you're doing so this is best guess answer... For one, how are you assigning the already open connection?
//connect.php
<?php
$conn = mysql_connect("$host", "$u", "$p");
mysql_select_db("$db");
?>
<?php
include 'connect.php';
class Core
{
private $conn;
function __construct()
{
global $conn;
$this->conn =& $conn;
}
}
?>
Upvotes: 1
Reputation: 21
public function __construct() {
$this->db = new mysqli('$host', '$u', '$p','$db') or die('Connection Failure');
}
this code will not run, be sure u have used "$host"/"$u"..etc instead of '$host' or '$u'
php parser will parse it as a string not a variable inside the quotation.
Upvotes: 0