This question already has an answer here:
PHP simple DB connection class for MVC
(1 answer)
Closed 1 year ago.
dbconnect.php
class dbconnect
{
public function connect()
{
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host, $user, $pass, $db);
return $connection;
}
}
dao.php
include 'dbconnect.php';
class dao extends dbconnect
{
private $conn;
function __construct()
{
$dbcon = new dbconnect();
$conn = $dbcon->connect();
}
function select($table, $where = '', $other = '')
{
if (!$where = '') {
$where = 'where' . $where;
}
$sele = mysqli_query($this->conn, "SELECT * FROM $table $where $other") or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
controller.php
include 'dao.php';
$d = new dao();
if (isset($_POST['btn_login'])) {
extract($_POST);
$username = $_POST['user_name'];
$pswd = $_POST['pswd'];
$sel = $d->select("users", "email_id = '" . $username . "'AND password='" . $pswd . "'") or die('error from here');
$result = mysqli_fetch_array($sel);
if ($result['email_id'] == $username && $result['password'] == $pswd) {
SESSION_START();
$_SESSION['user_name'] = $result['email_id'];
$_SESSION['message'] = 'Invalid Username Or Password';
header("location:index.php");
} else {
$_SESSION['error'] = 'Invalid Username Or Password';
}
}
I got an error
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/ankit_demo/dao.php on line 13
Warning: mysqli_error() expects parameter 1 to be mysqli, null given in /opt/lampp/htdocs/ankit_demo/dao.php on line 13
Please help me to solve this.
Try this out, there was issues with if condition as well as the where condition. and we can't echo a object or can't convert object to string.
dbconnect.php:
<?php
class dbconnect{
public function connect(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host,$user,$pass,$db);
return $connection;
}
}
dao.php:
<?php
include 'dbconnect.php';
class dao extends dbconnect {
private $conn;
public function __construct() {
$dbcon = new parent();
// this is not needed in your case
// you can use $this->conn = $this->connect(); without calling parent()
$this->conn = $dbcon->connect();
}
public function select( $table , $where='' , $other='' ){
if($where != '' ){ // condition was wrong
$where = 'where ' . $where; // Added space
}
$sql = "SELECT * FROM ".$table." " .$where. " " .$other;
$sele = mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
// echo $sele; // don't use echo statement because - Object of class mysqli_result could not be converted to string
return $sele;
}
}
?>
controller.php:
<?php
include 'dao.php';
$d = new dao();
if(isset($_POST['btn_login'])){
extract($_POST);
$username = $_POST['user_name'];
$pswd = $_POST['pswd'];
$sel = $d->select("users" , "email_id = '" . $username . "' AND password='" . $pswd . "'" ) or die('error from here');
$result = mysqli_fetch_array($sel) ;
if($result['email_id'] == $username && $result['password'] == $pswd){
SESSION_START();
$_SESSION['user_name'] = $result['email_id'];
$_SESSION['message'] = 'Invalid Username Or Password';
header("location:index.php");
}
else{
$_SESSION['error'] = 'Invalid Username Or Password';
// header("Location:login.php");
}
}
?>
Change name of your constructor from __dao() to __construct().
Replace your line 6-th line of code by:
$this->conn = $dbcon->connect();
try this :
include 'dbconnect.php';
class dao extends dbconnect{
private $conn;
function __construct(){
$dbcon = new dbconnect();
$this->conn = $dbcon->connect();
}
function select( $table , $where='' , $other='' ){
if(!$where = '' ){
$where = 'where' . $where;
}
$sql = "SELECT * FROM ".$table." " .$where. " " .$other";
$sele = mysqli_query($this->conn, $sql) or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
Connection file:
class dbconnect{
public function connect(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'demo';
$connection = mysqli_connect($host,$user,$pass,$db);
return $connection;
}
}
dao file:
include 'dbconnect.php';
class dao extends dbconnect {
private $conn;
public function __construct() {
$dbcon = new parent(); // this is not needed in your case
// you can use $this->conn = $this->connect(); without calling parent()
$this->conn = $dbcon->connect();
}
public function select( $table , $where='' , $other='' ){
if(!$where = '' ){
$where = 'where' . $where;
}
$sele = mysqli_query($this->conn,"SELECT * FROM $table $where $other") or die(mysqli_error($this->conn));
echo $sele;
return $sele;
}
}
But I think it would be better to use PDO or much better a ORM system like laravel eloquent.
Related
Here is my code:
<?php
class Db
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'emp';
function __construct()
{
$this->db = new mysqli(
$this->servername,
$this->username,
$this->password,
$this->dbname
);
if ($this->db->connect_error) {
die("Connection failed: " . $this->db->connect_error);
}
}
public function insert_record($table, $fields)
{
$sql = "";
$sql .= "INSERT INTO " . $table;
$sql .= " (" . implode(",", array_keys($fields)) . ")values";
$sql .= " ('" . implode("','", array_values($fields)) . "')";
$query = mysqli_query($this->db, $sql);
if ($query) {
return true;
}
}
}
//making object of the class
$crudobj = new Db;
//insert code for adding data in to the db
if (isset($_POST['submit'])) {
$myArray = array(
"username" => $_POST["unm"],
"email" => $_POST["eid"],
"password" => $_POST["pass"]
);
//inserting data
if($crudobj->insert_record("users", $myArray))
{
header("location: login.pho")
}
}
?>
Call it with your input email.
if($crudobj->is_email_exists($_POST["eid"]))
{
echo "Email Already Exist";
}
Add below function in your DB class:
public function is_email_exists($email)
{
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$email = mysqli_real_escape_string($this->db, $email);;
$sql = "SELECT email FROM users WHERE email='".$email."';";
if($result = mysqli_query($this->db, $sql))
{
return mysqli_num_rows($result);
}
}
return true;
}
<?php
require_once("../include/connClass.php");
// $conn = new mysqli("localhost", "root", "", "hrms");
$db = new dbObj();
// var_dump($db);
$connString = $db->getConnstring();
// var_dump($connString);
$params = $_REQUEST;
$action = isset($params['action']) != '' ? $params['action'] : '';
$objDesignationMaster = new DesignationMaster($connString);
switch($action) {
case 'add':
$objDesignationMaster->insertDesignationMaster($params);
break;
case 'edit':
$objDesignationMaster->updateDesignationMaster($params);
break;
case 'delete':
$objDesignationMaster->deleteDesignationMaster($params);
break;
default:
$objDesignationMaster->getDesignationMaster($params);
return;
}
class DesignationMaster {
protected $conn;
protected $data = array();
function __construct($connString) {
$this->conn = $connString;
}
// public function getDesignationMaster($params) {
// $this->data = $this->getRecords($params);
// echo json_encode($this->data);
// }
function insertDesignationMaster($params){
$data = array();
$sql = "INSERT INTO department_master (dm_department)
VALUES(
'" . $params["txtDepartment"] . "'); ";
// echo $sql;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
function getDesignationMaster($params){
}
function deleteDesignationMaster($params){
}
function updateDesignationMaster($params){
}
}
?>
I am Getting Error on this code I am Including Connection File From another file any idea about this. the object is created successfully connection object is not.
And here is my connection class
<?php
Class dbObj{
var $servername = "localhost";
var $username = "root";
var $password = "";
var $db = "hrms";
var $conn;
Public function getConnstring() {
// Create connection
$con = new mysqli($this->servername, $this->username, $this->password,
$this->db);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
} else {
$this->conn = $con;
}
return $this->conn;
}
}
?>
Use
if($this->conn->query($sql) === TRUE){ //$conn is not defined
}
$this->conn contains the connection itself. You defined it in the construct function
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..
I'm beginning php/MySql and have been asked to use a class to access my database. I can get the display to work when I have all my code in one file but when I try to call the class from another file, I get nothing.
This is the one that works:
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';
$myNewConnection = mysqli_connect($host,$username,$password,$dbname);
$query = "SELECT user_name FROM users" or die ("Error..." . mysqli_error($myNewConnection));
// execute the query
$result = $myNewConnection->query($query);
// display output
while($row = mysqli_fetch_array($result)) {
echo $row["user_name"] . "<br>";
}
?>
This is my code to call the class:
<?php
include("users.php");
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';
//initiate the class
$myDB = new MyDB('localhost', 'root', '', 'testdb');
//$myDB = new MyDB($host,$username,$password,$dbname);
?>
This is my class:
<?php
class MyDB {
public $query;
public $myConnection;
public function _construct($host,$username,$password,$dbname){
// establish the connection
$this->myConnection = mysqli_connect($host,$username,$password,$dbname);
}
public function list_users() {
// create query to list all users
$this->query = "SELECT user_name FROM users" or die ("Error..." . mysqli_error($this->$myNewConnection));
// execute the query
$result = $this->$myConnection->query($this->$query);
// display output
while($row = mysqli_fetch_array($result)) {
echo $row["user_name"] . "<br>";
}
}
}
?>
Any help appreciated
Change this line as below (remove the dollar sign from query and myConnection):
$result = $this->myConnection->query($this->query);
Plus you might need to call your list_users function using the code below (right after instantiating your class! Pass your defined variables to constructor instead of their actual values):
$myDB = new MyDB($host,$username,$password,$dbname);
$myDB->list_users();
Also constructors are written with two underscores like this:
public function __construct
function __construct with two "_". Delete all "$" after "->":
<?php
class MyDB {
public $query;
public $myConnection;
public function __construct($host,$username,$password,$dbname){
$this->myConnection = mysqli_connect($host,$username,$password,$dbname);
}
public function list_users() {
$this->query = "SELECT user_name FROM users";
if($result = $this->myConnection->query($this->query)) {
while($row = mysqli_fetch_array($result)) {
echo $row["user_name"] . "<br>";
}
}
}
}
And you have to run list_users():
<?php
include("users.php");
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'testdb';
$myDB = new MyDB($host, $username, $password, $dbname);
$myDB->list_users();
?>
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;
}