PHP: Database Connection Class - Won't Connect - php

I'm having trouble with my DatabaseConnection class. I cannot seem to get $dbUser or $dbName variables to work for this connection class. I currently have to manually put the values in with quotes. Is there something I am doing wrong?
class DatabaseConnection {
private $dbHost = "localhost";
private $dbUser = "root";
private $dbPass = "";
private $dbName = "test";
function __construct() {
$connection = mysql_connect($dbHost, "root", $dbPass)
or die("Could not connect to the database:<br />" . mysql_error());
mysql_select_db("test", $connection)
or die("Database error:<br />" . mysql_error());
}
}
If you have suggestions for improving my current class, by all means, let me know!

Since this is a class, you have to access your class variables using $this->dbHost, $this->dbUser, etc instead of $dbHost, $dbUser. Php requires that you use $this->variableName for class variables.
EDIT:
Here's your code with the mysql_connect variables changed to access your class variables
class DatabaseConnection {
private $dbHost = "localhost";
private $dbUser = "root";
private $dbPass = "";
private $dbName = "test";
function __construct() {
$connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
or die("Could not connect to the database:<br />" . mysql_error());
mysql_select_db("test", $connection)
or die("Database error:<br />" . mysql_error());
}
}

Related

Switching all the mysql_* functions to mysqli_* functions results in warning errors

I'm currently switching all the mysql_* functions to mysqli_* functions and i am getting the following errors .
PHP Warning: mysqli_connect(): (HY000/1040): Too many connections in
PHP Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in
PHP Warning: mysqli_error() expects parameter 1 to be mysqli, boolean
In config.php :
$dbuser = "xxx";
$dbpass = "xxx";
$dbhost = "xxxx";
$dbname = "xxxxxx";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass) or die("could not connect to mysql");
if($connection){
echo "\n Database connected ....\n\n";
}
mysqli_select_db($connection,$dbname) or die(mysqli_error($connection));
In other.php
require_once 'Lib/config.php';
class Mutex {
protected $connection;
public function __construct()
{
global $dbuser,$dbpass,$dbname,$dbhost; // globally declaring the config variables
$this->connection = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
//you need to exit the script, if there is an error
exit();
}
}
public function Prog($pack = null) {
if(isset($pack) && $pack != "") {
$sql_qry = "SELECT id from xxxx WHERE package like '" . addslashes($pack) . "'";
showSqlQuery($sql_qry);
$result = mysqli_query($this->connection,$sql_qry)or die(mysqli_error($this->connection));
if($result && mysqli_num_rows($result)>0) {
$row = mysqli_fetch_assoc($result);
if(!empty($row)) {
return "Exists";
}
}
return "NotExists";
}
return "InvalidProcess";
}
}
Tried many solutions, but none of them worked for me
Getting errors as shown above.
Please help me to solve this..
Thanks in advance.
I think your DB configuration has some issue.
Replace the following code of config.php file to bellow.
$dbuser = "xxx";
$dbpass = "xxx";
$dbhost = "xxxx";
$dbname = "xxxxxx";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Rather than duplicating ( nearly ) the connection you could try the approach where you pass a reference to the db connection as a parameter to the Mutex constructor
<?php
/* lib/config.php */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpass, $dbname );
?>
<?php
include 'lib/config.php';
class Mutex{
private $connection;
public function __construct( $dbo=object ){
$this->connection=$dbo;
}
public function Prog($pack = null) {
$result='InvalidProcess';
if( !empty( $pack ) ) {
$sql='select `id` from `xxxx` where `package` like ?';
$stmt=$this->connection->prepare( $sql );
if( $stmt ){
$var = '%'.$pack.'%';
$stmt->bind_param('s', $var );
$result=$stmt->execute();
if( $result && $stmt->num_rows > 0 ){
$stmt->store_result();
$stmt->bind_result( $id );
while( $stmt->fetch() ){/* do stuff perhaps */
echo $id;
}
$stmt->free_result();
$stmt->close();
$result='Exists';
}
}
}
return $result;
}
$pack='banana';
$mutex=new Mutex( $db );
$mutex->Prog( $pack );
?>

php mysql connection get error message

this is my first php code , i am trying to connect to a database with user name = "root" and password = "root"
i have a connection file called dbConnection.php
as following :
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysql_select_db($db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
and i call it in a file called what.php :
<?php
echo "Hello";
include "dbConnection.php";
echo "ohhhh";
?>
this returns status code 500 which is internal server error
but i want to know what is the error to fix it how can i get the error message ?
i tried
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
but it is not returning any thing.
can any one help me please ?
if you are having password on localhost then use password otherwise leave it blank
$con = mysqli_connect("localhost","root","yourpassword","yourdb");
You mysqli_connect() method.
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysqli_select_db($conn,$db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
First Thing is to Change your connection method to mysqli or my personal favorite PDO.
PDO Example:
class db extends pdo{
//Website Variables
public $sitedb = '';
public $siteconfig;
public $sitesettings = array(
'host' => 'localhost',
'database' => 'yourdb',
'username' => 'youruser',
'password' => 'yourpass',
);
public function __construct(){
$this->sitedb = new PDO(
"mysql:host={$this->sitesettings['host']};" .
"dbname={$this->sitesettings['database']};" .
"charset=utf8",
"{$this->sitesettings['username']}",
"{$this->sitesettings['password']}"
);
$this->sitedb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
}
$db = new db();
Then you can extend your PDO class to new classes after including the db.php page.
Example Select:
class yourclass extends db {
public function SelectUsers() {
global $db;
$query = <<<SQL
SELECT email
FROM users
WHERE active = :active
SQL;
$resource = $db->sitedb->prepare( $query );
$resource->execute( array (
':active' => 1,
));
$count = $resource->rowCount();
foreach($resource as $user){
$this->email = $user['email'];
}
}
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// make the current db
$db_selected = mysqli_select_db ( $conn , $dbname );
if (!$db_selected) {
die ('Can\'t connect to Database : ' . mysql_error());
}
?>

mysql_select_db returns false while mysql_error returns nothing

I'm trying to connect to a database, but mysql_select_db always returns false. If I just use the first parameter of mysql_select I get the error: Access denied for user ''#'localhost' to database 'newboston', if I enter the connection link as the second parameter mysql_error returns nothing. Anyone knows what's going on?
<?php
$dbServer = 'localhost';
$dbUserName = 'root';
$dbPassword = 'password';
$database = 'newboston';
$db = mysqli_connect($dbServer, $dbUserName, $dbPassword);
$connectFailed = 'Could not connect to ' . $dbServer . '.';
if($db)
{
if(mysql_select_db($database, $db))
{
echo 'Connected to ' . $database;
}
else
{
echo 'Could not connect to ' . $database;
die(mysql_error());
}
}
else
{
echo $connectFailed;
}
?>
You're mixing mysql and mysqli:
$db = mysqli_connect($dbServer, $dbUserName, $dbPassword);
should be:
$db = mysql_connect($dbServer, $dbUserName, $dbPassword);
(actually you should be using mysqli as mysql is deprecated).
You're mixing mysqli_* functions with mysql_* functions.
May I suggest learning PDO MySQL instead?

Multiple database connection using php userdefined function

This is the code for config.php I am including this file in all php files:
<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
global $db_name, $db_user, $db_pass;
$conn = mysql_connect($db_name, $db_user, $db_pass);
mysql_select_db('test1', $conn) or die('Could not select database.');
return $conn;
}
db_connect1();
?>
Here i need to connect with another one database test2.
You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for another connection
<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
global $db_name, $db_user, $db_pass;
$conn1 = mysql_connect($db_name, $db_user, $db_pass);
$conn2 = mysql_connect($db_name, $db_user, $db_pass,true);
mysql_select_db('test1', $conn1) or die('Could not select database test1.');
mysql_select_db('test2', $conn2) or die('Could not select database test2.');
$conn = new stdClass();
$conn->conn1 = $conn1;
$conn->conn2 = $conn2;
return $conn;
}
$conn = db_connect1();
Then to query database test1, do this:
mysql_query('select * from tablename', $conn->conn1);
and for database test2:
mysql_query('select * from tablename', $conn->conn2);
?>
try this
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1($dbname) {
global $db_name, $db_user, $db_pass;
$conn = mysql_connect($db_name, $db_user, $db_pass);
if($conn) {
mysql_select_db($dbname, $conn) or die('Could not select database.');
return $conn;
} else {
die("Error occurred while connect to the server.");
}
}
Every time you call the function and set argument.
echo db_connect1('test1');
echo db_connect1('test2');
Echo the function because you are using return keyword and checked that if it returns 1 its means your server connection is ok.

php scope of Global variables in a loop

This code connects to a first database, loops and picks up a field called 'id' and use the id as a connection[database name] to another database in a function. All seemed to work except that in the function, the value of id does not change so cannot connect to db, even though it changes in the local variable. I suspect i need to unsett and set. Any help? Thanks
<?
$dbhost = "***";
$dbname = "users";
$dbuser = "****";
$dbpass = "***";
function myRecordHandler($record)
{
global $dbhost;
global $dbuser;
global $dbpass;
global $id;
global $conn2;
$db = mysql_select_db($id,$conn2) ;
$quantity = $record["QUANTITY"];
$price = $record["PRICE"];
$mytotal ="INSERT into `mytotal`(`quantity`,`price`) VALUES ($quantity,$price)";
mysql_query($mytotal,$conn2);
}
$conn1 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE) or die("MySQL Error: " .mysql_error());
$conn2 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname,$conn1) or die("MySQL Error: " . mysql_error());
$query = "SELECT id,url FROM table userdata";
$result = mysql_query($query,$conn1);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$id =$row['id'];
$url=$row['url'];
MagicParser_parse($url,"myRecordHandler","xml|PRODUCTS/PRODUCT/");
}
?>
I suspect the problem is that myRecordHandler() is being called from within MagicParser_parse(). It's probably being called within a separate execution context that doesn't share the same global name space. This is just a hunch based on the fact that you're passing in "myRecordHandler" as a string.

Categories