Database connection using php class and methods - php

Here is mycode dbclass.php i am new for oops concept,
<?php
class Database {
private $link;
private $hostname, $username, $password, $dbname;
public function __construct( $hostname, $username, $password, $dbname ) {
$this->link=mysql_connect($this->hostname,$this->username,$this->password) or die("Mysql Connection error!!");
mysql_select_db($this->dbname,$this->link) or die("error:".mysql_error());
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("Error:".mysql_error());
}
}
?>
<?php
include("dbclass.php");
$db = new Database("localhost", "root", "password", "test");
$result = $db->query("select * from messages");
while ( $row = mysql_fetch_array( $result ) ) {
echo $row['id'];
}
?>
if i run this code it showing database not connected. I don't know why?

The problem is here :
$this->link=mysql_connect($this->hostname,$this->username,$this->password)
You are not assigning the argument in function to your variables of class. Hence do this
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
and then give:
$this->link=mysql_connect($this->hostname,$this->username,$this->password);

Related

How to get database object out of function

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

function within a function returning an object not working

I have some code which works:
$user = 'xxx';
$pass = 'xxx';
$db='vive';
$host ='localhost';
$name = 'chris';
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.0 <br>';
return $mysqli;
}
}
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0) ...
I am able to connect to the database and pull the information that I want out of the database everytime. I wanted to clean up my code a little (all the details are not shown), so i made a new function register() out of the last part of the code. In this new function, i want to call on function test() to return me a database connection object which I can then use to perform queries:
<?php
$user = 'root';
$pass = 'root';
$db='vive';
$host ='localhost';
$name = 'chris';
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.0 <br>';
return $mysqli;
}
}
function register($name){
echo'test';
global $user;
global $pass;
global $db;
global $host;
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0)...
}
For some reason the function register() will never give me any values from the database. I am unable to get anything for $result. Any help is appreciated, I have been dancing around the problem for a few days now. Note that in my actual code I have these two functions in different php files.
The LIKE statement there in the query is missing %...% wrapper.
change the register to :
function register($name){
global $user;
global $pass;
global $db;
global $host;
$name = "%".$name."%"; // see here..
echo'test';
$mysqli2 = test($user, $pass, $db, $host);
$sql = "SELECT * FROM `vive_user` WHERE `username` LIKE"."'$name'";
$result = $mysqli2->query($sql);
$num_results = $result->num_rows;
if ($result->num_rows>0)...
}
and make sure the method is called
Why the where username like?
shouldn't it be where username = ?
also the quotes you used are redundant.
$sql = "SELECT * FROM vive_user WHERE username LIKE"."'$name'";
could just be
$sql = "SELECT * FROM vive_user WHERE username = '$name'";

Cannot echo database items

I am trying to echo out some database items in php but nothing seems to be coming out. The initialize php that is required calls out the database.php that stores all the configurations as show below.What am I doing wrong?
SQL statement:
<?php
require_once("includes/initialize.php");
$userName = $_POST["name"];
$userEmail = $_POST["email"];
$sqlName = "SELECT name FROM individual";
$sqlEmail = "SELECT email FROM individual";
if ($sqlEmail == $userEmail || $sqlName == $userName){
$message = "Hi " + $userName + "this is your new password.";
echo $message;
}
?>
The database configurations are in another php file called database.php.
database.php:
<?php
require_once ("config.php");
class MySQLDatabase {
private $connection;
function __construct() {
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME) or die
("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
$db_select = mysqli_select_db($this->connection, DB_NAME);
}
public function close_connection() {
if (isset($this->connection)) {
mysqli_close($this->connnection);
unset($this->connection);
}
}
public function query($sql) {
$result = mysqli_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result) {
if (!$result) {
die("Database query failed.");
}
}
public function escape_value($string) {
$escaped_string = mysqli_real_escape_string($this->connection, $string);
return $escaped_string;
}
public function fetch_array($id){
if (mysqli_fetch_array($id)) {
return true;
}
}
}
$database = new MySQLDatabase();
$db = & $database;
?>
Your not running your query.. ..or getting its results..
$sqlEmail = "SELECT email FROM individual";
$query = $db->query($sqlEmail);
$user = $db->fetch_array($query);
var_dumpr($user);
Hope this helps..

PDO query returning empty

I have a Connection class file which allows my other class "Functions" to connect to my MySQL database. However, when I execute a MySQL query, it returns with just Array (). The data I'm selecting is, in fact, there (I checked). What could the problem be?
Connection.php
<?php
class Connection extends PDO {
private $username;
private $password;
private $database;
private $hostname;
public function __construct($hostname, $username, $password, $database) {
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
$this->hostname = $hostname;
try {
parent::__construct("mysql:host=" . $this->hostname . ";dbname=" . $this->database, $this->username, $this->password);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
}
?>
Functions.php
<?php
require_once "Connection.php";
class Functions {
private $connection;
public function __construct() {
$this->connection = new Connection("127.0.0.1", "xxx", "xxx", "xxx");
}
public function sqlFetchAssoc($query) {
$sth = $this->connection->prepare($query);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
$functions = new Functions();
$row = $functions->sqlFetchAssoc("SELECT * FROM chatlogs WHERE id = 70");
print_r($row);
?>
I just spotted your bug in Connection.php:
$this->hostname = $hostname;
$this->username = $username;
$this->password = $password;
$this->hostname = $hostname;
$this->hostname is repeated while $this->database is not set. However, you can strip altogether setting the $this->something, since you are using those values in the same function. This will make it simpler:
try {
parent::__construct("mysql:host=" . $hostname . ";dbname=" . $database, $username, $password);
}
I'd recommend going a step further. You should test each class separately. You can write this script and debug it (if needed) in testfunction.php:
<?php
class Functions {
private $connection;
public function __construct() {
$this->connection = new PDO("mysql:host=127.0.0.1;dbname=xxx", "xxx", "xxx");
}
public function sqlFetchAssoc($query) {
$sth = $this->connection->prepare($query);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
echo "Test started <br><br>";
echo "Initialization: <br>";
$functions = new Functions();
echo "Correct<br><br>";
echo "Performing a select: <br>";
$row = $functions->sqlFetchAssoc("SELECT * FROM chatlogs WHERE id = 70");
print_r($row);
echo "Test finished.";
?>
Then do something similar for the first class. Then not only it will be easier to spot the bug, but should a bug happen, you can come to these tests to see what went wrong instead of writing them all again. Remember not to include them in production code.

Mysqli oop method call

I'm really new to implementing OOP using mysqli things, I have this Object(Class) named Database, my real problem is how would I call my select method in my index.php and how can I use it
Database Class.php is below:
Class Database{
private $host = null;
private $user = null;
private $pass = null;
private $db = null;
public $error = "Error Po Sir!";
public $con;
public function connect($host, $user, $pass, $db){
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->db = $db;
$this->con = mysqli_connect($this->host, $this->user, $this->pass);
if(mysqli_connect_errno()){
echo "Connection Failed %s\n!", mysqli_connect_error();
exit();
}
}
public function select($condition){
$query = "select os_user from users WHERE os_user = {$condition}";
$result = mysqli_query($this->con,$query);
return $result;
}
}
this is how did I implement it:
require 'templates/dbclass.php';
$db = new Database();
$db->connect("localhost", "root", "", "os_db");
$username = $_POST['username'];
if($result = $db->select($username)){
echo $username;
if($result->num_rows > 0){
while($row = $result->fetch_object()){
echo $row->os_id;
}
}
}
But it does not show any results. When I var_dump($result) I get bool(false).
I've enabled error reporting, but there is no errors displayed.
There are 3 issues with your select function
is is vulnerable to SQL injection
it does no error checking
it is useless
Here is how it have to be
public function query($sql, $bind)
{
$db = $this->con;
$stm = $db->prepare($sql) or trigger_error($db->error." [$sql]");
$types = str_repeat("s", count($values));
array_unshift($bind, $types);
call_user_func_array(array($stm, 'bind_param'), $bind);
$stm->execute() or trigger_error($db->error." [$sql]");
$stm->store_result();
return $stm->get_result();
}
used like this
$sql = "select os_user from users WHERE os_user = ?";
$res = $db->select($sql, $_POST['username']));
while($row = $result->fetch_object()){
echo $row->os_id;
}

Categories