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();
?>
Related
I am building a login portal with mySQL and PHP
I have this file (dbc.php):
<?php
class db_connect {
protected $DB_SERVER = "localhost";
protected $DB_USERNAME = "root";
protected $DB_PASSWORD = "";
protected $DB_DATABASE = "mydb";
public function connect() {
$conn = new mysqli($this->DB_SERVER, $this->DB_USERNAME, $this->DB_PASSWORD, $this->DB_DATABASE);
if(mysqli_connect_errno()) {
die("Connection failed: ". mysqli_connect_errno());
}
return $conn;
}
}
?>
Then my actual PHP script (login.php) takes a POST from the login page:
<?php
//include database connection
include("dbc.php");
session_start();
//put post values into variables
$username = $_POST['username'];
$password = $_POST['password'];
//create db connector object
$db = new db_connect();
$conn = $db->connect();
//select correct db
mysqli_select_db($conn,”mydb”);
$username = mysqli_real_escape_string($conn,$username);
$query = "SELECT password FROM mydb.users WHERE username = '$username'";
$result = mysqli_query($conn,$query);
if(mysqli_num_rows($result) == 0)
{
header('Location: sorry.html');
}
$pwhash = $result;
if (password_verify($password, $pwhash)) {
header('Location: welcome.php');
} else {
header('Location: sorry.html');
}
?>
This never returns a value which is odd.
Any help appreciated!
$result holds a MySQLi response resource, not a string or array.
You need to change this line:
$pwhash = $result;
To this:
$pwhash = mysqli_fetch_assoc($result)['password'];
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.
I'm trying to change my queries from mysql to PDO because I need to query at the same time two different databases on different servers.
I've done these classes so far
class Db extends PDO {
public $db;
public function __construct($dbhost = 'host1', $dbname = 'db1', $dbuser = 'user1', $dbpass = 'user2', $dbtype = 'mysql') {
PDO::__construct($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
}
function sql_query($sql) {
$result = PDO::query($sql);
return $result;
}
function sql_fetcharray($result) {
$rs = $result->fetch(PDO::FETCH_ASSOC);
return $rs;
}
function sql_numrows($result) {
$rs = $result->rowCount();
return $rs;
}
}
class Db2 extends Db {
public $db;
public function __construct($dbhost = 'host2', $dbname = 'db2', $dbuser = 'user2', $dbpass = 'pass2', $dbtype = 'mysql') {
PDO::__construct($dbtype . ':host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
}
function sql_query($sql) {
parent::sql_query($sql);
$result = PDO::query($sql);
return $result;
}
function sql_fetcharray($result) {
$rs = $result->fetch(PDO::FETCH_ASSOC);
return $rs;
}
function sql_numrows($result) {
$rs = $result->rowCount();
return $rs;
}
}
and then
$db = new Db2;
$sql = "query";
$result = $db->sql_query($sql);
but the query affects only the second database.
Anyone can help?
Thanks a lot
you had to run your query twice against two databases. don't expect the inheritance to do that for you
$db = new Db2();
$sql = "query";
$result = $db->sql_query($sql);
$db1 = new Db();
$sql = "query";
$result1 = $db1->sql_query($sql);
I don't think you needed another child class, you can easily switch database using :
USE DATABASENAME
So for example you can do:
$db = new Db;
$sql = "query";
$result = $db->sql_query($sql);
$db->sql_query('USE DB2');
$sql2 = "query2";
$result2 = $db->sql_query($sql2);
or perhaps create a function to select db:
function select_db($db) {
$result = PDO::query('USE $db');
return $result;
}
then use it:
$db = new Db;
$sql = "query";
$result = $db->sql_query($sql);
$db->select_db('DB2');
$sql2 = "query2";
$result2 = $db->sql_query($sql2);
What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();
Im new to php so im sure this is an easy one. Im getting this error
Notice: Undefined variable: conn in C:\Dev\Webserver\Apache2.2\htdocs\EclipsePHP\thecock\php\db.php on line 23
for this code
<?php
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
$conn = new mysqli($host, $username, $password, $database);
if (! $conn) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo("all ok!");
}
function getContent($id) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) { # line 23
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
?>
How do I fix the notice?
Change your function to:
function getContent($id, $conn) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
You don't declare the "original" $conn in the scope of the function. Inside the function you only have access to variables declared inside the function or provided via parameters.
Another way would be to declare the variable as global in your function:
function getContent($id) {
global $conn;
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
But you should only do this, if there is no other way. Globals make it hard to debug and maintain the code.
See also Variable scope and why global variables are bad.
Edit:
Yes e.g. you can have a DB class:
class DB {
private static $conn = null;
public static function getConnection() {
if (is_null(DB::$conn)) {
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
DB::$conn = new mysqli($host, $username, $password, $database);
}
return DB::$conn;
}
}
Of course this is not the best implementation ;) But it should give you the right idea. Then you can get the the connection:
DB::getConnection()
conn is a global variable. To access it within a function:
function getContent($id) {
global $conn;
...
}
Otherwise the function can't see it.