Database php class causes fatal error - php

I'm trying to create a php class that will connect me to the database more easily, but it seems to not work.
This is my function from the class:
class Database {
// host, username, password and db are defined
public function GetMySqlConnection()
{
return mysqli_connect($this->host, $this->username, $this->password, $this->db);
}
}
And I use it in another page like this:
$db = Database()->GetMySqlConnection();
$result = $db->query("SELECT name FROM users WHERE name='" . mysqli_real_escape_string($_POST['agname']) . "' AND password='" . mysqli_real_escape_string($_POST['agpass']) . "'");
For some reason it causes some error I can't manage to find. What am I doing wrong?

Database is class here, so you cannot use $db = Database()->GetMySqlConnection();
You should use:
$db = new Database();
$db = $db->GetMySqlConnection();
instead

Related

Storing mysqli connection in object

I am trying to contain my mysqli object within a class, that other objects/scripts can use. I initialize it like so:
$this->host = $Host;
$this->username = $UName;
$this->password = $PWord;
$this->database = $DBName;
$this->debugEmail = $debugEmail;
// Create sql handler
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->database);
// Check connection
if ($this->conn->connect_error) {
die("Connection Failed: " . $this->conn->connect_error());
}
The problem is when I use this object elsewhere, it seems to think that the conn object is null.
For example:
$sqlObj = new sqlObject();
$sqlObj->init();
// run query
$sql = "SELECT * FROM table";
$result = $sqlObj->getConn()->query($sql);
It returns:
Call to a member function query() on a non-object
Certainly $sqlObj->getConn() is returning null or false (or another object) that isn't the desired type.
I recommend you to throw a new error in getConn() and wrap with a try/catch block. In this throw, return the error coming from getConn and you'll be able to understand it better. BTW, Are the connection params ok ? It seems to be something related to this.

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 do I make $con available as a parameter of $Query?

I can get by with editing procedural PHP (just), but OOP is a different thing. So I'm not that experienced with what I'm doing here, but I'm trying my best...
I have a file called Quote.object.php containing the following:
$Query = new DbQuery( "INSERT", "quotes", $array );
$this->id = mysqli_insert_id();
mysqli_insert_id needs to be fed a DB connection parameter, but I'm not sure how to do it. There is another file called Mysql.handler.php containing the database connection variable - is there a way that I can make $con available as a parameter of $Query above?
class DbQuery extends DbConnectionInfo{
// file: includes/classes/MysqlQuery.php
// contains functions needed to perform queries on mysql database and functions for necessary data processing for application
// SELECT = new DbQuery("select", table,cols[$value] ,where[$col=$value],order[$value],limit);
// INSERT = new DbQuery("insert", table, data[$col=$value]);
// UPDATE = new DbQuery("update", table, data[$col=$value],where[$col=$value],limit);
// set testing as true for SQL reports in page
var $results;
var $sql;
function __construct($mode,$table = '',$var1 = '',$var2 = '',$var3 = '',$var4='')
//connects to database according to info in DbConnectInfo, runs query, closes connection
{
$temp = '';
$con = mysqli_connect($this->host, $this->user, $this->pass) or die ('There was a problem connecting to the database ' . (ENVIRONMENT == 'Development' ? mysqli_error() . "$this->user, $this->pass, $this->host" : ''));
mysqli_select_db($con,$this->db) or die ('There was a problem connecting to the database' . (ENVIRONMENT == 'Development' ? mysqli_error() : ''));
I'm trying to get $con from DbQuery so I can put it into mysqli_insert_id(). I assume that's what I need? Is there a way to get $con from DbQuery and put into mysqli_insert_id()? Or do you need more information to know this?
NB I've tried to be concise in trying to show just relevant information, apologies if I've missed other helpful info.
You're defining an object, so make $con a class variable, e.g.
function __construct() {
$this->con = mysqli_connect(...);
^^^^^^^----store in object
}
function foo() {
$result = mysqli_query($sql, $this->con);
^^^^^^^^---retrieve from object
}

Query after connecting to remote MySQL database using mysqli_real_connect

I can successfully connect to a remote MySQL database using mysqli_init(), mysqli_ssl_set and mysqlii_real_connect. I can't seem to find an example of a query being done after connecting. The result of mysqli_real_connect is a boolean value, whereas mysqli_connect returns an object representing the connection to the MySQL server. How do I refer to the connection after using mysqli_real_connect? Can anyone provide an example?
<?php error_reporting(E_ALL);
ini_set("display_errors", "1");
$obj = mysqli_init();
mysqli_options($obj, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
mysqli_ssl_set( $obj,
NULL,
NULL,
'ca-cert.pem',
NULL,
NULL);
$link = mysqli_real_connect($obj, 'xxxxxxxxxxxx.com', 'user', 'password, 'database_name');
if (!$link)
{
die('<br /><br />Connect Error (' . mysqli_connect_errno() . ') '.mysqli_connect_error());
} ?>
The way that you'd do it using your example is mysqli_query($obj, QUERY HERE);
However, you should consider using the OOP (Object Orientated Programming) style, as that would be easier for you to reference within the future.
<?php
Class Database {
private $obj;
public function __construct() {
$this->obj = new mysqli('xxxxxxxxxxxx.com', 'user', 'password', 'database_name');
if (!$this->obj) {
die('<br /><br />Connect Error (' . mysqli_connect_errno() . ') '.mysqli_connect_error());
}
}
public function query($query) {
return $this->obj->query($query);
}
}
?>
You would call this class by doing:
$db = new Database();
And from there on, you could simply call your function by using the following example.
$db->query("SELECT * FROM users"); // or whatever query you are parsing.

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?

Categories