Hi I am having some issues connecting to my DB using OO PHP. My script is below. I have been going at this for a while now. This is just a test script as I am fairly new to OOP. Please don't be harsh
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$mysqli = new mysqli($host, $username, $password, $db);
if (!$mysqli){
echo "error in connecting to database";
}
else{
echo "success in connecting to database";
}
}
public function query(){
$result = $mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
Usage...
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Your main problem is that you aren't storing a value into your class' $mysqli property. You need to use $this->mysqli in your constructor and query method instead of $mysqli.
Secondly, this class adds nothing that the mysqli class doesn't already have. You might as well simply use
$DB = new mysqli('localhost', 'root', 'xxxx', 'yyyy');
if ($DB->connect_error) {
throw new Exception($DB->connect_error, $DB->connect_errno);
}
The problem is, you are accessing the class property without $this. The $mysqli should be in $this->mysqli in constructor function.
You are using mysqli property as Object of mysqli class.
Then you can use the query function of mysqli property object(In Database class) by $this->mysqli->query("SELECT * FROM inventory") in query function.
Updated Code:
<?php
class Database{
public $mysqli,
$host,
$username,
$password,
$db;
public function __construct($host, $username, $password, $db){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->mysqli = new mysqli($host, $username, $password, $db);
/* check connection */
if ($this->mysqli->connect_errno) {
printf("Connect failed: %s\n", $this->mysqli->connect_error);
exit();
} else {
echo "success in connecting to database";
}
}
public function query(){
$result = $this->mysqli->query("SELECT * FROM inventory");
if ($result) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
}
else{
echo "there is an error in query";
$result->close();
}
//echo "in query function";
}
}
$DB = new Database('localhost', 'root', 'xxxx', 'yyyy');
$DB -> query();
Try this:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection succeeded
if(mysqli_connect_error()){
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
Related
i have config file for connection but when ever i use $this->con->prepare() or $this->con->query() are not working.
But when i make separate variable for connection its work fine below are example.
this code in not working
private function isEmailexist($email)
{
$stmt = $this->con->prepare("SELECT * FROM devices WHERE email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
echo "Rows : ".$rows;
}
This code work
private function isEmailexist($email)
{
$mysqli = new mysqli("localhost", "root", "", "demo1");
$stmt = $mysqli->prepare("SELECT * FROM devices WHERE email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
echo "Rows : ".$rows;
}
this is config file
class Config
{
private $con;
function __construct(){}
function connect()
{
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME','demo1');
define('DB_HOST','localhost');
$con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "Connection success...";
return $this->con;
}
}
Your issue is with setting $con inside of connect()
You are using
// $con is only visible within the scope of the connect function
$con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
but it should be
// this will set the config class's $con property so that it is re-usable
$this->con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
This is a database class which connects to the database taking in the host name, username, password and the databasename. The MembersModel class after the DatabaseConnect class, which also extends the DatabaseConnect, is supposed to retrieve information.
<?php
class DatabaseConnect
{
protected $conn;
protected $host, $username, $password, $database;
public function __construct($host, $username, $password, $database){
// Create connection
$this->conn = new mysqli($host, $username, $password,$database)
OR die("There was a problem connecting to the database");
return true;
}
public function query($sql) {
$result = $this->conn->query($sql);
if (!$result) {
die('Invalid query:');
}
return $result;
}
public function __destruct(){
$this->conn->close()
OR die("Problem disconnecting from the database");
}
}
class MemberModel extends DatabaseConnect
{
public function getAllMembers() {
$result = $this->query("SELECT * FROM members");
return $result;
}
}
To connect and retrieve from the database this is what I have been trying to do
$db = new DatabaseConnect("localhost", "root", "", "pcaframework");
$allMembers = $db->getAllMembers();
while ($row = mysqli_fetch_assoc($allMembers)) {
echo "First Name: " . $row['name'] ."<br />";
echo "Last Name: " . $row['email'] ."<br />";
echo "<hr />";
}
but this is what I get "Fatal error: Call to undefined method DatabaseConnect::getAllMembers()". Can you point out the problem here.
Your $db object should be an instance of MemberModel. The DatabaseConnect class does not contain the getAllMembers function.
Change
$db = new DatabaseConnect("localhost", "root", "", "pcaframework");
To
$db = new MemberModel("localhost", "root", "", "pcaframework");
I have a function that connects to a database. After I call the function, I want it to return the database/connection object so that I am able to then use that object and perform queries on the database. How can I return the object below $mysqli from the function test() so that I can use $mysqli outside the function, and even in different scripts. Or should I write a specific function for each query?
function test($user, $pass, $db, $host){
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else {
echo 'Checkpoint 1 <br>';
return $mysqli;
}
}
test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli->query($sql);
What I use for writing big projects is the following:
Class MySQL
{
protected $_conn;
public function __construct() {
$this->_DB_NAME = DB_NAME;
$this->_DB_USER = DB_USER;
$this->_DB_PASS = DB_PASSWORD;
$this->_DB_HOST = DB_HOST;
$this->_conn = mysqli_connect($this->_DB_HOST, $this->_DB_USER, $this->_DB_PASS);
if(!$this->_conn) {
die('A problem has occured');
}
}
public function connect() {
if(!mysqli_select_db($this->_conn, $this->_DB_NAME)) {
die("1st time failed<br>");
}
return $this->_conn;
}
}
Class Database
{
protected $_conn;
public function __construct() {
$db = new MySQL;
$this->_conn = $db->connect();
}
public function retrieve() {
$result = $this->_conn->query("SELECT * FROM mytable");
return $result;
}
}
$database = new Database();
$result = $database->retrieve();
You can simply use global variable
$mysqli = null;
function test($user, $pass, $db, $host){
// Here you define variable in function to global
global $mysqli;
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
else{
echo 'Checkpoint 1 <br>';
return $mysqli;
}
}
test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli->query($sql);
So I'm attempting to make a registration form. I've made a php MySQL class which uses the constructor to make the connection with new MySQLi() for verifyLogin function and mysql_connect() for my addElement function.
The error is with my addElement function, the SQL statement writes out properly but it doesn't seem to connect to the database. I've checked that all the names are correct. Any ideas?
<?php
class MySQL {
private $connection;
private $conn;
private $databaseName;
function __construct($dbServer, $dbUser, $dbPassword, $dbName) {
$this->connection = new MySQLi($dbServer, $dbUser, $dbPassword, $dbName)
or die('PROBLEM CONNECTING TO DATABASE');
$this->conn = mysql_connect($dbServer, $dbUser, $dbPassword);
echo $this->conn;
$databaseName = $dbName;
}
function verifyLogin($table, $email, $password) {
$query = "SELECT *
FROM ?
WHERE email = ?
AND password = ?
LIMIT 1";
if($statement = $this->connection->prepare($query)) {
$statement->bind_param('sss', $table, $email, $password);
$statement->execute();
if($statement->fetch()) {
$statement->close();
return true;
}
else {
return false;
}
}
}
function addElement($table, $firstName, $lastName, $email, $mobile, $password,
$faculty, $campus) {
$query = "INSERT INTO $table (first_name, last_name, email, mobile, password, faculty, campus_location)
VALUES('$firstName', '$lastName','$email','$mobile',
'$password','$faculty','$campus');";
echo $query;
mysql_select_db($this->databaseName, $this->conn);
if(!mysql_query($query)) {
die('Error: ' . mysql_error());
}
mysql_close($this->connection);
}
}
?>
To select a database in MySQLi, you need to select it like so:
$db = new mysqli("localhost", "my_user", "my_password", "database_name");
or
$db = new mysqli("localhost", "my_user", "my_password");
$db->select_db('database_name');
as opposed to MySQL:
$db = mysql_connect('localhost', 'my_user', 'my_password');
$db_selected = mysql_select_db('database_name', $db);
MySQLi : http://www.php.net/manual/en/mysqli.select-db.php
MySQL : http://www.php.net/manual/en/function.mysql-select-db.php
You are mixing the mysql and the mysqli php drivers.
Since the mysql driver is deprecated I would suggest going with the mysqli.
PHP Documentation:
http://www.php.net/manual/en/book.mysqli.php
Good Overview to get you started:
http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/
I have just started learning the concept of Object oriented programming and have put together a class for connecting to a database, selecting database and closing the database connection. So far everything seems to work out okay except closing the connection to the database.
class Database {
private $host, $username, $password;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
}
public function connectdb(){
mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
echo 'successfully connected to database<br />';
}
public function select($database){
mysql_select_db($database)
OR die("There was a problem selecting the database.");
echo 'successfully selected database<br />';
}
public function disconnectdb(){
mysql_close($this->connectdb())
OR die("There was a problem disconnecting from the database.");
}
}
$database = new database('localhost', 'root', 'usbw');
$database->connectdb();
$database->select('msm');
$database->disconnectdb();
When I attempt to disconnect from the database I get the following error message:
Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53
I'm guessing it isn't as simple as placing the connectdb method within the parenthesis of the mysql_close function but can't find the right way to do it.
Thanks
I would add a connection/link variable to your class, and use a destructor.
That will also save you from haveing to remember to close your connection, cause it's done automatically.
It is the $this->link that you need to pass to your mysql_close().
class Database {
private $link;
private $host, $username, $password, $database;
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->link = mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
mysql_select_db($this->database, $this->link)
OR die("There was a problem selecting the database.");
return true;
}
public function query($query) {
$result = mysql_query($query);
if (!$result) die('Invalid query: ' . mysql_error());
return $result;
}
public function __destruct() {
mysql_close($this->link)
OR die("There was a problem disconnecting from the database.");
}
}
Example Usage:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
while ($row = mysql_fetch_assoc($result)) {
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
?>
Edit:
So people can actually use the class, I added the missing properties/methods.
The next step would be to expand on the query method, to include protection against injection, and any other helper functions.
I made the following changes:
Added the missing private properties
Added __construct($host, $username, $password, $database)
Merged connectdb() and select() into __construct() saving an extra two lines of code.
Added query($query)
Example Usage
Please if I made a typo or mistake, leave a constructive comment, so I can fix it for others.
edit 23/06/2018
As pointed out mysql is quite outdated and as this question still receives regular visits I thought I'd post an updated solution.
class Database {
private $mysqli;
private $host, $username, $password, $database;
/**
* Creates the mysql connection.
* Kills the script on connection or database errors.
*
* #param string $host
* #param string $username
* #param string $password
* #param string $database
* #return boolean
*/
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->mysqli = new mysqli($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$this->mysqli->select_db($this->database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
/**
* Prints the currently selected database.
*/
public function print_database_name()
{
/* return name of current default database */
if ($result = $this->mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Selected database is %s.\n", $row[0]);
$result->close();
}
}
/**
* On error returns an array with the error code.
* On success returns an array with multiple mysql data.
*
* #param string $query
* #return array
*/
public function query($query) {
/* array returned, includes a success boolean */
$return = array();
if(!$result = $this->mysqli->query($query))
{
$return['success'] = false;
$return['error'] = $this->mysqli->error;
return $return;
}
$return['success'] = true;
$return['affected_rows'] = $this->mysqli->affected_rows;
$return['insert_id'] = $this->mysqli->insert_id;
if(0 == $this->mysqli->insert_id)
{
$return['count'] = $result->num_rows;
$return['rows'] = array();
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$return['rows'][] = $row;
}
/* free result set */
$result->close();
}
return $return;
}
/**
* Automatically closes the mysql connection
* at the end of the program.
*/
public function __destruct() {
$this->mysqli->close()
OR die("There was a problem disconnecting from the database.");
}
}
Example usage:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
if(true == $result['success'])
{
echo "Number of rows: " . $result['count'] ."<br />";
foreach($result['rows'] as $row)
{
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
}
if(false == $result['success'])
{
echo "An error has occurred: " . $result['error'] ."<br />";
}
?>
you're not returning anything from connectdb() yet you're passing this function's return to mysql_close().
You should be aware that mysql_* functions were introduced in PHP 4, which is more then 1 yours ago. This API is extremely old, and the process has begun to actually deprecating this extension.
You should not in 2012 write new code with mysql_* functions.
There exist two very good alternative : PDO and MySQLi. Both of which are already written with object oriented code in mind, and they also give you ability to use prepared statements.
That example you showed in the original post written with PDO would look like this:
//connect to the the database
$connection = new PDO('mysql:host=localhost;dbname=msm', 'username', 'password');
//disconnects
$connection = null;
Of course there are more complicated use-case, but the point stand - time to evolve.
mysql_close requires a parameter to disconnect but you are providing nothing.
class Database {
private $host, $username, $password, $con;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
$this->con = false;
}
public function connect() {
$connect = mysql_connect($this->host, $this->username, $this->password);
return $connect;
}
public function connectdb(){
$conn = $this->connect();
if($conn)
{
$this->con = true;
echo "Successsfully Connected. ";
return true;
}
else {
echo "Sorry Could Not Connect. ";
return false;
}
}
public function select($database){
if($this->con)
{
if(mysql_select_db($database))
{
echo "Successfully Connected Database. $database. ";
return true;
}
else
{
echo "Unknown database. ";
}
}
else {
echo "No active Connection. ";
return false;
}
}
public function disconnectdb(){
if($this->con)
{
if(mysql_close($this->connect()))
{
$this->con = false;
echo "Successfully disconnected. ";
return true;
}
}
else
{
echo "Could Not disconnect. ";
return false;
}
}
}
$database = new database('localhost', 'root', '');
$database->connectdb();
$database->select('databaseoffacebook');
$database->disconnectdb();
Object Oriented Programming works well with PDO and mysqli. Give it a try
<?php
class Database{
private $link;
//private $host,$username,$password,$database;
//private $status;
public function __construct(){
$this->host = 'localhost';
$this->username = 'root';
$this->password = '';
$this->database = 'workclass';
$this->link = mysqli_connect($this->host,$this->username,$this->password);
$this->status = mysqli_select_db($this->link,$this->database);
if (!$this->status) {
return $this->status="Failed to Connected with Database";
}else{
return $this->status="Database is connected";
}
}
}
$object = new Database();
echo $object->status;
?>