Trouble connecting to Database (php) - php

I am working on a user database and have it set up so that the dropdown menus in my registration form take their values from tables in the database. The problem is that when I tested it out, the dropdowns were empty. Naturally the first thing I did was to go and check my connection. To connect to the database, I have a file called BaseDAO.php which contains the following:
<?php
class BaseDAO {
const SQL_HOST = "localhost";
const SQL_USER = "user6538";
const SQL_PW = "sdWf234Fg";
const SQL_DB = "userDB";
protected $con = null;
function connect() {
$this->con = mysql_connect(self::SQL_HOST, self::SQL_USER, self::SQL_PW);
if(!$this->con) {die('Could not connect to MySQL host: ' . self::SQL_HOST . ' Error: ' . mysql_error()); }
echo "Connected!"; //NOTE: I only just added this to test it
mysql_select_db(self::SQL_DB);
}
function close() {
mysql_close($this->con);
}
}
?>
So to test it, I added echo "Hello World!"; outside of the class, just as a reference, then I added connect(); right below it. I opened my page and only saw the Hello World! ... So then I tried echo connect(); and again nothing. Then I tried this:
$baseDAO = new BaseDAO();
$baseDAO->connect();
And still there was nothing. Then I commented out the entire class and just added this:
<?php
//...
//Commented out class
//....
function connect() {
$con = mysql_connect("localhost", "user6538", "sdWf234Fg" );
if(!$con) { echo "3"; die('Could not connect: ' . mysql_error()); }
echo "Connected!";
}
echo "Hello World!";
connect();
?>
Lo and behold the output was this:
Hello World!Connected!
I don't understand why my class doesn't work... It explains why my dropdowns were not working, since their DAO files require my BaseDAO.
Would someone care to enlighten me on what's going on here? Why won't my class work?
NOTE: I am using a friend's old project as a guide, so theoretically my BaseDAO.php should work, since his worked.
EDIT: Corrected the arguments in the second connect() function

The return value of mysql_connect is FALSE in an error case. 0 is a positive value.
To be sure, make this change:
if(self::con === FALSE) {die('Could not connect to MySQL host: ' . self::SQL_HOST . ' Error: ' . mysql_error()); }
Your second SQL, where you did remove the CLASS parts, cannot work, but it strangely does.
$con = mysql_connect(self::SQL_HOST, self::SQL_USER, self::SQL_PW);
You do not have the self:: constants defined if you class does not exist. PHP should have produced an error message in this case. So your description is wrong and missing something.

class BaseDAO {
private static $SQL_HOST = "localhost";
private static $SQL_USER = "user6538";
private static $SQL_PW = "sdWf234Fg";
private static $SQL_DB = "userDB";
protected static $con = null;
public static function connect() {
self::con = mysql_connect(self::SQL_HOST, self::SQL_USER, self::SQL_PW);
if(!self::con) {die('Could not connect to MySQL host: ' . self::SQL_HOST . ' Error: ' . mysql_error()); }
echo "Connected!"; //NOTE: I only just added this to test it
mysql_select_db(self::SQL_DB);
}
public static function close() {
mysql_close(self::con);
}
}
To connect do the following no need to create an instance of the class because its static:
BaseDAO::connect();

Related

error on mysqli multiple connection via class

i have the following problem which costs me the last couple of hours...
i have a class for mysqli connections:
class database extends SplObjectStorage{
private $db_link;
public function __construct($MySQLi_DB){
if(!file_exists($_SERVER["HOME"].'/'.(substr($_SERVER['PHP_SELF'], 1, strpos(substr($_SERVER['PHP_SELF'], 1),'/'))).'/includes/mysqli.inc.php')){
echo "MySQLi Include Datei nicht vorhanden";
}else{
if (!$this->create_connection($MySQLi_DB) == true){
echo "Error creating Database. Parameter '".$MySQLi_DB."' unknown<br><br>";
}
}
}
public function query($query){
Return $this->db_link->query($query);
}
public function close(){
mysqli_close($this->db_link);
}
private function create_connection($MySQLi_DB){
include_once($_SERVER["HOME"].'/'.(substr($_SERVER['PHP_SELF'], 1, strpos(substr($_SERVER['PHP_SELF'], 1),'/'))).'/includes/mysqli.inc.php');
$this->db_link = new mysqli($MySQLi_Host, $MySQLi_User, $MySQLi_Passw, $MySQLi_Praefix.$MySQLi_DB);
$this->attach($this->db_link);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQLi: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
return false;
}else{
return true;
}
echo $mysqli->host_info . "\n";
}
The constructor initializes the class by looking for an include-file which contains all connectiondata like user, pwd, etc.
it although receive a parameter ($MySQLi_DB) which is similar to the databasename.
When i call this class with this command:
$SSO_DB = new database('SSO');
This class works fine.
Changing the parameter do another databasename is no problem.
e.g.: $Social_DB = new database('social');
This is even no problem until i call two instanzes of my class on the same page!
e.g.:
$SSO_DB = new database('SSO');
$Social_DB = new database('social');
Returns this error:
Warning: mysqli::mysqli(): (HY000/1044): Access denied for user ''#'localhost' to database 'social' in /volume1/web/portal/classes/database.class.php on line 41
Line 41 is:
$this->db_link = new mysqli($MySQLi_Host, $MySQLi_User, $MySQLi_Passw, $MySQLi_Praefix.$MySQLi_DB);
When i remove one of the classcalls no error.
No matter which call i remove...
Any idea?
changing include_once() into include() solved the problem! php seems to store how often the class is called on one page and did not included the file a second time.

Cannot call MySQL when including class in PHP

I've got a problem with include. I'm doing some kind of blog, and at this moment it looks like this:
index.php
article.php
class/art.class.php
Let's focus on article.php, which looks like this:
<?php
$mysqli = new mysqli("","","",""); // here are my connection details
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'");
require("class/art.class.php");
$art = new Article();
print_r($art->get_art(trim($_GET['id'])));
$mysqli->close();
?>
And art.class.php is like this:
<?php
class Article {
function get_art($id) {
if(!is_numeric($id)) {
header("Location: index.php");
die("<h2>ID isn't numeric, cannot go on.</h2>'");
}
if($result = $mysqli->query("SELECT * FROM `articles` WHERE id='$id';")) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$art = $row;
}
$result->close();
}
return $art;
}
}
?>
The problem is a response from MySQL. Sorry, I mean no response. And no errors. I figured out that I need to add mysql connection code to class code. But why? How I can connect once to database and call it from anywhere, even from included class?
And sorry if my english is bad..
The get_art function within the Article class does not have access to variables outside of it's scope: please see the answer here.
In order to fix your issue, you may provide access to the $mysqli object by passing it to the constructor of the Article class when you instantiate it:
Article.php:
$mysqli = new mysqli("","","",""); // your connection details
$art = new Article($mysqli);
art.class.php:
class Article {
protected $mysqli;
public function __construct($mysqli) {
$this->$mysqli = $mysqli;
}
function get_art($id) {
// Replace $mysqli with $this->mysqli everywhere you need to
// make database calls
}
}
Although some would recommend that you avoid doing so, you could use PHP's $GLOBALS variable to store your database connection:
$mysqli = new mysqli("","","",""); // here are my connection details
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$GLOBALS['mysql'] = $mysqli;
This way you would have access to it within your class:
class Article
{
function get_art($id)
{
$mysqli = $GLOBALS['mysqli'];
...
}
}

How to use PHP classes between other classes [duplicate]

This question already has answers here:
What is dependency injection?
(37 answers)
Closed 9 years ago.
I know the basics of PHP and have only ever used it to debug WordPress code generally, but now I want to write my own little program to download an email and process an attachment and I have decided to try using classes as I have a basic understanding of OO programming.
SO PLEASE READ: I am a novice! I don't know what on earth dependency injection is or means...
My issue is that I have created a function called printStatus(), so I can toggle on/off output of comments. I was looking at this, and I'm not sure how or if it would fit into a class structure or if I need to include this function in every other class I create?
Basically - If I created a class, I would need to make it available to all other classes (i.e. a global class) but I'm not sure if that is achievable.
My questions are:
Do I have to pass a reference to the printOutput class to and from every class I use to have it available to me OR can I declare it globally to make it available to all classes OR do I need to include the same function in every class I create?
I've created a MySQL Connection class and I am passing that into each object for use - should (can I) declare it globally and just make it available to all classes?
Thanks for the 101.
Here is my code, am I going down the right path?: (see specifically, references to printStatus())
PS - $formatoutput->printStatus() does not work within other classes - I'm looking to understand what structure is required to make it work.
class.formatoutput.php:
class formatOutput {
var $debug = true;
function printStatus($text, $html = true) {
if ($debug) {
echo $text;
echo $html?"<br/>\n":"\n";
}
}
function printObjectStatus($object, $html = true) {
if ($debug) {
echo '<pre>';
echo $text;
echo $html?"</pre><br/>\n":"</pre>\n";
}
}
}
class.connection.php:
class Connection
{
var $db_host = "host";
var $db_name = "name";
var $db_user = "user";
var $db_pass = "pass";
var $db_conn;
function connectToDatabase() {
$db_conn = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
if (!$db_conn) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
else
{
$this->db_conn = $db_conn;
$formatoutput->printStatus( "Connection established");
}
return $this->db_conn;
}
function closeConnection() {
mysqli_close($this->db_conn);
$formatoutput->printStatus( "Connection closed");
}
}
class.customer.php:
class Customer {
var $customer_id;
var $customer_name;
function getCustomer($connection, $user_id) {
$query = "SELECT id, name FROM customer WHERE user_id=$user_id";
$result = mysqli_query($connection, $query);
if($result === FALSE) {
die('Connect Error (' . mysqli_errno() . ') ' . mysqli_error());
}
$row_count = mysqli_field_count($connection);
$formatoutput->printStatus( "COUNT: (".$count.")");
}
}
index.php:
include 'class.formatoutput.php';
include 'class.connection.php';
include 'class.customer.php';
$formatoutput = new formatOutput();
$formatoutput->printStatus('Start new Connection()');
$connection = new Connection();
$connection->connectToDatabase();
$customer = new Customer();
$customer->getCustomer($connection->db_conn, "1");
$connection->closeConnection();
Declare the function printStatus as static:
static function printStatus($text, $html = true)
You can call this function by using "::",
formatOutput::printStatus("hello");

Including php file with database connection error

I want a generic php file with all the database info (dbname,host,username,password)
But when I include the page, in like index.php I get this error:
Access denied for user 'apache'#'localhost' (using password: NO)
connect.php
<?php
class dbconnect{
private $host = '**';
private $user = '**';
private $pass = '**';
public $con;
function Connect($db = '**') {
if($db=='**'){
$this->host="localhost";
$this->user="**";
$this->pass="**";
$db="**";
}else{
$this->host="**";
$this->user="**";
$this->pass="**";
}
$this->con = mysql_connect($this->host,$this->user,$this->pass);
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
$blaa = mysql_select_db($db, $this->con);
mysql_query("SET NAMES UTF8");
return $blaa;
}
function Disconnect() {
//$this->con = mysql_connect($this->host,$this->user,$this->pass);
mysql_close();
}
}
?>
I am sure the ** information is correct because when I specify it as:
$con=mysqli_connect("example.com","example","password","my_db");
In index.php it works
It's important to note, your test case doesn't actually prove it works.
What does this output:
$conn = mysql_connect("example.com", "user", "password");
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
As you won't necessarily get the information that's failing it without that.
To top that off, let's simplify your class a little bit for debugging purposes:
class dbconnect
{
private $host = '**';
private $user = '**';
private $pass = '**';
public $con;
public function Connect($host = "localhost", $user = "root", $pass = "")
{
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->con = mysql_connect($this->host, $this->user, $this->pass);
if (!$this->con) {
die('Could not connect: ' . mysql_error());
}
$blaa = mysql_select_db($db, $this->con);
mysql_query("SET NAMES UTF8");
return $blaa;
}
public function Disconnect()
{
mysql_close($this->con);
}
}
Now what do you get when you do
$db = new dbconnect("example.com", "user", "password");
Be sure you're using credentials that work, and that you're not running into issues such as default values or incorrect variable assignment through these methods.
Now, if you don't want to provide the values, you can simply:
$db = new dbconnect();
Public Service Announcement
Check out PHP's PDO or at minimum (but really, just use PDO) the mysqli alternative. PHP's mysql extension is NOT secure, and you should not be using it in any environment, ever.
If the connection information are correct, check your MySQL User's host access permission:
SELECT user, host FROM mysql.user
If "localhost" is set, then the user can only access the database locally, otherwise "%" will open access.
Usually it is an issue with the connection credentials.
Check that you can log into your mysql using the details you have set for that website.
mysql -u apache -p
It will then ask you for the password.
If that login does not work, then you have a problem with that user's mysql account.
You use incorrect parameters for accessing. Just dump variables which at the line $this->con = mysql_connect($this->host,$this->user,$this->pass);. You can use debugger or echo, print instructions.
Furthermore use PDO extension for accessing to databases. It's better!
Why shouldn't I use mysql_* functions in PHP?

My DB class wont connect, throws exception "No database selected"

I have my 'dbinterface' class with a connect function. When i run this i get a statement saying "Query didn't work. No database selected"
class dbinterface {
private $_dbLink;
private $dbHost = 'host';
private $dbUser = 'user';
private $dbName = 'name';
private $dbPass = 'pass';
private $dbUserTable = 'table';
public function connect ()
{
$this->_dbLink = mysql_connect($this->_dbHost, $this->_dbUser, $this->_dbPass);
if(!$this->_dbLink)
throw new Exception ("Could not connect to database. " . mysql_error());
}
I made a change to the public connect function.
public function connect ()
{
$this->dbLink = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass);
mysql_select_db($this->dbUserTable);
if(!$this->dbLink)
throw new Exception ("Could not connect to database. " . mysql_error());
}
Unfortunately it output the same result. I am new to PHP and still learning, i have tried everything i know so ANY help is very much appreciated.
Unless you use an absolute schema.table type reference in your queries, you HAVE to specify a default database with mysql_select_db(). Without that,
SELECT somefield FROM sometable
fails with "no database selected" because MySQL doesn't know WHICH database it should look in for that table.
This would work, however:
SELECT somefield FROM name_of_db.name_of_table
without a default database, as you've explicitly stated you're using the "name_of_db" database.

Categories