Can't connect to the database with my class? - php

I'm trying to connect to my database but it won't connect. I tried but won't connect. the error I'm getting is Parse error: syntax error, unexpected 'connect' (T_STRING) in C:\htdocs\www\dating\index.php on line 3. I called the tried new Database connect(); and tried connect(); I get this message Fatal error: Call to undefined function connect() in C:\htdocs\www\dating\index.php on line 3. What's wrong?
class Database{
private $db_host = "localhost";
private $db_user = "123346";
private $db_pass = "12345";
private $db_name = "1234";
public $conn;
// Create connection
public function connect(){
if(!isset($this->conn)){
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
if($this->conn){
$this->conn = true;
return true;
}else{
$this->conn = false;
return false;
}
}
}
public function disconnect(){
if(isset($this->conn)){
if(mysqli_close($this->conn)){
$this->myconn = false;
echo "connection closed";
return true;
} else{
echo "failed to close connection";
return false;
}
}else{
echo "no connection prescent";
}
}
}
I'm trying to get use query now but it won't get the results. Here is the code
include("functions/connect.php");
$db = new Database("localhost", "12345", "1234", "123");
$db->connectdb();
$db->select('rpg');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT id, username FROM users ORDER by ID DESC ";
if ($result = $db->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
/* free result set */
$result->close();
}
/* close connection */
$db->close();`

Please change this line
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
to this
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
You will notice you used $this->pass but it should be $this->db_pass.
To call the function of Database class you have to write your code like this;
<?php
include("functions/connect.php");
$db_conn = new Database();
if($db_conn->connect()) {
echo "Database connected";
}

Related

I want to display table rows in same class and difference function in PHP

how to display rows in my users table in PHP
arr() function can't connect with database
class DB {
protected $db_server = 'localhost';
protected $db_username = 'root';
protected $db_password = 'root';
protected $db_name = 'dbname';
public function connect() {
$connect_db = new mysqli($this->db_server, $this->db_username, $this->db_password, $this->db_name);
if(mysqli_connect_errno()) {
printf("Connection failed!", mysqli_connect_error());
exit();
} else {
echo "connected";
}
return true;
}
function arr() {
$conn = $this->connect();
if($query = mysqli_query($conn, "SELECT * FROM users")) {
echo 'row is ' . mysqli_num_rows($query);
}
}
}
$db = new DB();
$db->arr();
result -> "connected row is " not count rows
In the connect() function, change
return true;
to
return $connect_db;
so that it returns the connection object. Then you can use it in your other functions.

Call to a member function query() on null with PDO

I just checked all of the answers are available on stackoverflow,they are similar but not my answer exactly. So please don't take this post as duplicate.
these are my codes when I'm executing it say's
Fatal error: Call to a member function query() on null in
C:\wamp64\www\ourCMS\index.php on line 12
Here is my snippet :
<?php
class DB
{
private $dbHost;
private $dbName;
private $dbUser;
private $dbPass;
protected $con;
function set_db($host, $db, $user, $pass)
{
$this->dbHost = $host;
$this->dbName = $db;
$this->dbUser = $user;
$this->dbPass = $pass;
}
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
}
}
// here is the place where i'm trying to use this actually
if (isset($_POST['submit']))
{
include('include/database.php');
$database = new DB;
$database->set_db("localhost", "ourcms", "root", "");
$conn = $database->connect();
$name = $_POST['nm'];
$query = "INSERT INTO testingpdo (name) VALUES ('$name')";
$data = $conn->query($query);
$result = $data->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
You don't return nothing from DB::connect ($conn = $database->connect();). Add return $this->con; at the end of the function.
function connect()
{
$info = 'mysql:host='.$this->dbHost.';dbname='.$this->dbName;
try
{
$this->con = new PDO($info, $this->dbUser, $this->dbPass);
}
catch(PDOException $e)
{
print "Error Founds: ".$e->getMessage().PHP_EOL;
die();
}
return $this->con;
}

'cannot access empty property' error in php

I am confused where i made mistake in my php code below. Although, i looked numerous time on my code but couldn't find why i am getting this error 'cannot access empty property' .
class DBTest{
//declare variables
private $servername = "localhost";
private $username = "root";
private $password = "";
private $database = "avn_test";
private static $conn;
private $results;
//constructor
public function __construct(){
self::$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
} //close constructor
public function executeQuery($query='') {
if(!empty($query)){
$query = self::$conn->real_escape_string($query);
Error on this line:
$this->results = self::$conn->query($query) or die("Error in database
connection".self::$conn->$error);
if( $this->results->num_rows > 0 ) {
$rowqry = array();
while($row = $this->results->fetch_object()) {
$rowqry[]= $row; } //close of while
$rarray['returnvar'] = $rowqry;
return $rarray;
} else {
return false; } // close of else
}//close of top if
else
return false;
} //close of function
function __destruct(){
self::$conn->close();}
} //close of class
//create an object of class DBTest
$test = new DBTest();
$q= "select * from test";
$tmp = $test->executeQuery($q);
if($tmp){
foreach($tmp as $key => $value){
echo $value;}
}
else
echo 'tmp var is empty';
In this line:
$this->results = self::$conn->query($query) or die("Error in database connection".self::$conn->$error);
Replace self::$conn->$error with self::$conn->error.
The $ is required when accessing a static property, but not needed for instance properties.
No need of $ in $conn function
self::$conn replace with self::conn
^^^^^^

How to get database in php using class & function oops concepts

I am new developer in php. I'm writing below code a class and functions to connect to the database. but code was not working how to create class and function oops concept help me.
code:
class database {
#code
var $host = "localhost";
var $username ="root";
var $password ="";
var $dbase ="blue";
var $myconnect;
function connectTodata()
{
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
die("Cannot Connect to the datagase");
}
else
{
$his->myconnect = $conn;
echo "Connect Established";
}
return $myconnect;
}
function selectDatabase() // selecting the database.
{
mysql_select_db($this->database); //use php inbuild functions for select database
if(mysql_error()) // if error occured display the error message
{
echo "Cannot find the database ".$this->database;
}
echo "Database selected..";
}
function closeConnection() // close the connection
{
mysql_close($this->myconn);
echo "Connection closed";
}
}
Just to make it work:
class database
{
#code
var $host = "localhost";
var $username ="root";
var $password ="";
var $dbase ="blue";
var $myconnect;
function connectTodata()
{
$this->myconnect = mysql_connect($this->host, $this->username, $this->password);
if(!$this->myconnect) die("Cannot Connect to the datagase");
echo "Connect Established";
return $this->myconnect;
}
function selectDatabase() // selecting the database.
{
mysql_select_db($this->database); //use php inbuild functions for select database
if(mysql_error()) // if error occured display the error message
{
echo "Cannot find the database ".$this->database;
}
echo "Database selected..";
}
function closeConnection() // close the connection
{
mysql_close($this->myconnect);
echo "Connection closed";
}
}
Fix the errors as described by the previous posters, then try this to start:
$database_connection=new database();
$database_handle=$database_connection->connectTodata();
$database_connection->selectDatabase();
$database_connection->closeConnection();
unset($database_connection);
exit();
and in the space between the chunks of code, you can add your mysql queries and use $database_handle as the second parameter.
you can use constructor so that you don't need to call class function everytime :
class database {
var $host = "localhost";
var $username ="root";
var $password ="";
var $dbase ="blue";
var $myconnect;
function __construct() {
$this->myconnect = mysql_connect($this->host, $this->username, $this->password);
if( !$this->myconnect ) {
$msg = "could not connect to mysql database <Br/>";
$msg .= mysql_error();
die($msg);
}
$db_connect = mysql_select_db($this->dbase, $this->myconnect);
if( !$db_connect ) {
die(" can not select database \n".mysql_error());
}
}
function __destruct() {
mysql_close($this->myconnect);
}
}
// call database
$con = new database();
You can do it with the help of Defining them something like
define("DB_SERVER_NAME","your host");
define("DB_USER_NAME","your user name");
define("DB_USER_PASSWORD","your password");
define("DB_DATABASE_NAME","your database");
now the connection file:
class DBClass{
public $DB_LINK;
public $DB_DATABASE_NAME;
function DBClass($Main_DB = FALSE){
$this->DB_LINK = #mysqli_connect(DB_SERVER_NAME,DB_USER_NAME,DB_USER_PASSWORD,DB_DATABASE_NAME);
if(! $this->DB_LINK){
die("<h2>Could not connect to Database.</h2>");
}
}
function __destruct(){
mysqli_close($this->DB_LINK);
}
}
This works perfectly for me

OOP database connect/disconnect class

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;
?>

Categories