Can't connect to database by calling function in class using PHP - php

I'm stuck in that situation that when I use $this->conn it returns:
Uncaught Error: Using $this when not in object context
but if I don't use it, then it said:
Undefined variable: conn
class save extends forma
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'world';
public $conn;
protected $table;
private function __construct()
{
if (!$this->table)
die('No table name provided');
}
function connect()
{
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($conn->connect_error) {
die($this->conn->connect_error);
}
return $this->conn;
}
public function saugoti($id,$pakeitimui=0, $kas=0)
{
$this->connect();
if(isset($_POST['saugoti']))
{
$table = "bmp_test";
$id = $_POST['id'];
$pav = $_POST['pav'];
$adr = $_POST['adr'];
$tel = $_POST['tel'];
if ($pakeitimui == 0)
{
$sql1 = "SHOW FIELDS FROM $table ";
$result = $conn->query($sql1);

You want to use the class variable $conn everywhere (this will be written as $this->conn) instead of $conn (which is a local variable).
Replacing all occurences of $conn by $this->conn in your code will solve that problem.

The main reason it was not working is you are using $this->conn->connect_error in connect function while storing connection in $conn which is local variable and not class variable
If you dont want to call $this->connect(); in every function then below code might work for you
class save extends forma
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'world';
public $conn;
protected $table = 'test_table';
public function __construct()
{
if (!$this->table)
die('No table name provided');
$this->connect();
}
function connect()
{
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die($this->conn->connect_error);
}
return $this->conn;
}
public function saugoti($id,$pakeitimui=0, $kas=0)
{
if(isset($_POST['saugoti']))
{
$table = "bmp_test";
$id = $_POST['id'];
$pav = $_POST['pav'];
$adr = $_POST['adr'];
$tel = $_POST['tel'];
if ($pakeitimui == 0)
{
$sql1 = "SHOW FIELDS FROM $table ";
$result = $this->conn->query($sql1);

Related

Setting PHP Class variable with a variable call

I am modifying a script that I bought and I am having trouble making the Database name variable that is set in the Database class be the result of the variable I construct above it. I need the $dbName variable to be set to the combination of "mmo_" appended to the variable $username that I get from my database. The name of the database should be "mmo_school" with school being the $username variable that is pulled from database. However, it fails unless I put the text of the variable in single quotes after $dbName = . But I need the database name to be dynamically set based on which user is using the script. I hope that this makes sense and I really appreciate your help!!
$username = "school";
$newname = "mmo_" . $username; **// the results of this would be "mmo_school"**
class Database
{
private static $dbName = $newname ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'username';
private static $dbUserPassword = 'password';
private static $cont = null;
public function __construct() {
exit('Init function is not allowed');
}
public static function connect() {
// One connection through whole application
if ( null == self::$cont ) {
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect() {
self::$cont = null;
}
}
if I type in $dbName = 'mmo_school' ; THIS WORKS.
if I try to use the variable I create as shown above...IT DOESN'T!!!
THANKS FOR YOUR HELP!!
Create a public static method to set the host, username, password, and etc. Also, i would change your constructor to private not public.
Database::setDB('mmo_' . $username);
// or
Database::setConnectInfo('mmo_' . $username, 'some host', $username, 'some password');
$db = Database::connect();
class Database
{
private static $dbName = $newname ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'username';
private static $dbUserPassword = 'password';
private static $cont = null;
private function __construct() {
exit('Init function is not allowed');
}
public static function setDB($dbName){
self::$dbName = $dbName;
}
// or use this function
public static function setConnectInfo($dbName, $dbHost, $dbUsername, $dbUserPassword){
self::$dbName = $dbName;
self::$dbHost = $dbHost;
self::$dbUsername = $dbUsername;
self::$dbUserPassword = $dbUserPassword;
}
public static function connect() {
// One connection through whole application
if ( null == self::$cont ) {
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect() {
self::$cont = null;
}
}
In your class you have to call $newname as a global variable. With this minor change your code should work.
$username = "school";
$newname = "mmo_" . $username; **// the results of this would be "mmo_school"**
class Database {
private static $dbName = "" ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'username';
private static $dbUserPassword = 'password';
private static $cont = null;
function __construct($init_parameter) {
global $newname;
$this->$dbName = $newname;
}
public static function connect() {
// One connection through whole application
if ( null == self::$cont ) {
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect() {
self::$cont = null;
}
}
because single quotes don't do variable expansion - use double quotes
$var = 'dingo';
$name = 'xyz_$var'; // result 'xyz_$var'
$name = "xyz_$var"; // result 'xyz_dingo'

Fatal error: Call to undefined method ConnectDatabase::query()

i have created an OOP-PHP Script and i get follow Message and i don't understand why???
Fatal error: Call to undefined method ConnectDatabase::query() in .... on line 73
My PHP Code
<?php
class ConnectDatabase {
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'database';
private $db_connection;
private $db_query;
//Connect Database.
function __construct() {
$this->open_db();
}
public function query($sql) {
$this->db_query = query($sql, $this->db_connection);
}
public function open_db() {
$this->db_connection = new mysqli($this->host, $this->username, $this->password);
if (is_resource($this->db_connection)) {
die("Error!");
} else {
$this->db_connection->select_db($this->database) or die('Error');
}
}
}
$dbConnection = new ConnectDatabase();
class GetContent {
public function newContent() {
global $dbConnection;
$sql = "SELECT * FROM mytable";
// ----- This Line make an Error ------
$query = $dbConnection->query($sql);
$found = $dbConnection->fetch_array($query);
return $found;
}
}
If you have any Idea please help.

OOP MySQLi Connect

Im newbie in OOP. I have class Database
class Database{
private $host;
private $user;
private $pass;
private $db;
public $mysqli;
function db_connect(){
$this->host = 'localhost';
$this->user = 'root';
$this->pass = '';
$this->db = 'db';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->mysqli;
}
Inside class Database i have function db_num
function db_num($sql){
$num = mysqli_num_rows(mysqli_query($this->mysqli,"{$sql}"));
return $num;
}
But it cant connect to database when im using in con argument $this->mysqli
It is bad practice to mix mysqli object style and procedural style.
Try this:
function db_num($sql){
$result = $this->mysqli->query($sql);
return $result->num_rows;
}
Be sure to connect to the database before you call db_num(), e.g.:
$db = new Database();
$db->db_connect();
$db->db_num("SELECT fields FROM YourTable");
A cleaner way in my opinion would be to call db_connect inside the constructor:
class Database{
private $host;
private $user;
private $pass;
private $db;
public $mysqli;
public function __construct() {
$this->db_connect();
}
private function db_connect(){
$this->host = 'localhost';
$this->user = 'root';
$this->pass = '';
$this->db = 'db';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->mysqli;
}
public function db_num($sql){
$result = $this->mysqli->query($sql);
return $result->num_rows;
}
}
$db = new Database();
$db->db_num("SELECT fields FROM YourTable");
<?php
/**
* Creating a class for the database connection
* To start using the database connection like this: $database = DatabaseFactory::getFactory()->getConnection();
*/
class DatabaseFactory {
protected $servername = "servername";
protected $username = "root";
protected $password = "root";
protected $dbname = "databasename";
private static $factory;
private $database;
public static function getFactory() {
if(!self::$factory) {
self::$factory = new DatabaseFactory();
}
return self::$factory;
}
public function getConnection() {
if(!$this->database) {
try {
$this->database = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
} catch (mysqli_sql_exception $e) {
$error = $e->getMessage();
echo "Error:" .$error;
exit;
}
}
return $this->database;
}
}

PHP code convert to PHP/MySQLi OOP

today i tried to convert my code to PHP/MySQLi OOP code.
class Database
{
private $host;
private $user;
private $password;
private $db;
private $mysqli;
function __construct()
{
$this->host = "*****";
$this->user = "*****";
$this->password = "******";
$this->db = "*****";
$this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
if (mysqli_connect_errno()):
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
endif;
}
}
This is a script for the query's:
include_once("WD_Config/database.php");
class Adressen_Db
{
function __construct()
{
$this->database = new Database();
}
public function selecteer()
{
$query = "SELECT * FROM wd_adressen WHERE verborgen = 0 ORDER BY naam ASC";
$result = $this->database->mysqli->query($query);
return $result;
}
}
And this is how i call it.
$adressen = new Adressen_Db;
$adressen_result = $adressen->selecteer();
echo "<p>";
while ($row = $adressen_result->fetch_assoc()):
echo "<a href='http://maps.google.com/?q=".$row['voladres']."' target='_blank'>".$row['naam']."</a> woonachtig op <i>".$row['voladres']."</i><br>";
endwhile;
echo "</p>";
I alway get a "Call to a member function query() on a non-object". Doesn't matter what i trie ...
Can somebody tell me why that is?
Thanks!
The $mysqli variable in class Database is declared private.
You can access it only through setters and getters.
I think while you definitely need to have $mysqli as public so it can be accessed in the other method, there might be something else, as the error would be something like
trying to access private property in database class
or something like that, whereas your script throws a non-object call error
I think your new Adressen_Db; lacks the parenthesis:
$adressen = new Adressen_Db();
You can replace your code with this:
Config.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "your_database_name");
Now include this file in your database file
require_once 'config.php';
Class Database {
public $host = DB_HOST;
public $user = DB_USER;
public $pass = DB_PASS;
public $dbname = DB_NAME;
public $link;
public $error;
public function __construct() {
$this->getConnection();
}
private function getConnection() {
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
if (!$this->link) {
$this->error = "Connection failed" . $this->link->connect_error;
return false;
}
}
// for only select query
public function select($query) {
$result = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($result->num_rows > 0) {
return $result;
} else {
return false;
}
}
// for insert, delete and update
public function myquery($query) {
$myquery = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($myquery) {
return $myquery;
} else {
return false;
}
}
}
Now, make your queries like this:
<?php
require_once './lib/Database.php';
?>
<?php
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function getData(){
$query = "SELECT * FROM admin";
$result = $this->db->select($query);
if($result != false){
while($row = $result->fetch_assoc()){
// do your thing
}
}
}
public function insert(){
$query = "INSERT INTO admin(admin_name) VALUES('$admin_name')";
$result = $this->db->myquery($query);
if($result){
$msg = "User has been added successfully.";
return $msg;
} else {
$msg = "Error while adding user. Please try again.";
return $msg;
}
}
}
Do this.

PHP Database Class Load Rows function (OOP)

I want to print out all content of the 'forum_question' table.
What am i doing wrong? No matter what, i will get the message "Nothing found!",
but i am sure the $db->connect DOES work, so it must be something with the query or loadRows functions.
This is my database class:
<?php
class Database {
private $host;
private $user;
private $password;
private $rows;
private $result;
private $dbName;
private $connection;
private $isReady;
public function __construct() {
$this->result = null;
$this->isReady = false;
}
/* setters */
public function setHost($host){ $this->host = $host; }
public function setUser($user){ $this->user = $user; }
public function setPassword($password){ $this->password = $password; }
public function setDbName($dbName){ $this->dbName = $dbName; }
/* Interface functions */
public function initiate($host=null,$user=null,$password=null,$dbName=null) {
if(isset($host,$user,$password,$dbName)==false) {
die("Please provide require settings.");
}
$this->setHost($host);
$this->setUser($user);
$this->setPassword($password);
$this->setDbName($dbName);
$this->isReady = true;
}
public function connect() {
if($this->isReady==false) {
die("Not ready to connect, please initiate connection");
}
$connection_string = "mysql:host=".$this->host.";dbname=".$this->dbName;
$this->connection = new PDO($connection_string, $this->user, $this->password);
$this->query("SET NAMES 'utf8'",$this->connection); // ensure character/language support
}
public function disconnect() {
$this->connection = null;
$this->isReady = false;
$this->setHost = null;
$this->setUser = null;
$this->setPassword = null;
$this->setDbName = null;
}
public function query($sql) {
$this->result = $this->connection->query($sql);
}
public function countRows() {
return $this->result->rowCount(); }
public function loadRows() {
if(!$this->result) die("Nothing found!");
$this->rows = array();
foreach ($this->result as $row) {
$this->rows[] = $row;
}
return $this->rows;
}
} // End of Database class
?>
This is my index file:
<?php
require_once 'class_database.php';
$db = new Database();
$db->initiate("localhost","USER","PASSWORD","DATABASE");
$db->connect();
$db->query("SELECT * FROM 'forum_question'");
$db->loadRows();
?>
Why don't you try with different connection script? For instance:
<?php
$mysql_server = "localhost";
$mysql_user = "USER";
$mysql_password = "PASSWORD";
$mysql_db = "DATABASE";
$mysqli = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($mysqli->connect_errno) {
printf("Connection failed: %s \n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
works fine, all you have to do is:
<?php
require_once "connection.php";
$query = "SELECT * FROM 'forum_question'";
$mysqli->query($query);
$mysqli->close();
Assuming that you saved the connection script in file "connection.php".

Categories