php constructor not working - php

I'm very new to php constructors I know of from java. But for some reason, this one is not running. I am following a tutorial and I can't seem to get a 1 only a 0. Here are the two scripts involved:
<?php
class dbConnection{
protected $db_conn;
public $db_name = 'todo';
public $db_user = 'root';
public $db_pass = '';
public $db_host = 'localhost';
function connect(){
try{
$this->db_conn = new PDO("mysql:host=$this->db_host;db_name=$this->db_name",$this->db_user,$this->db_pass);
return $this->db_conn;
}
catch(PDOException $e)
{
return $e->getMessage();
}
}
}
?>
<?php
include_once( 'class.database.php' );
class ManageUsers {
public $link;
public $constructed;
function ManageUsers(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
}
function registerUser($username,$password,$ip_address,$time,$date){
$query = $this->link->prepare("INSERT INTO users (username,password,ip_address,time,date) VALUES (?,?,?,?,?)");
$values = array($username,$password,$ip_address,$time,$date);
$query->execute($values);
$counts = $query->rowCount();
return $counts;
}
}
$users = new ManageUsers();
echo $users->registerUser('bob','bob','127.0.0.1','10:00','29-02-2012');
?>

You should try to use __construct() instead for ManageUsers().
Also, I'm not quite sure what you're trying to achieve in your constructor (see my markings below):
function ManageUsers(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link; //<--?
$constructed = 'Construct'; //<--?
}

Agreed - the method you are using is the old school PHP4 method - you should use the __construct() method as explained above.
http://www.php.net/manual/en/language.oop5.decon.php
This page explains construct() & destruct() in PHP 5

// constructor
function __construct() {
ManageUsers();
}
function ManageUsers(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
$constructed = 'Construct';
}
You cannot return from a constructor tho, maybe you can want to make link a public property and access it directly like this
$user = new ManageUsers();
$link = $user->$link;

Related

How to call a local property using OOP?

I'm a beginner looking to learn more about PHP OOP, so there are things I don't know, in the ShowUsers() method, I would like to display all users in the database, but I'm not getting it, because I don't know how to call the connection property. If I've been using encapsulation, it would be easy, but I'm using the connection property as local, and I really don't know how to call this property, how can I call it without using encapsulation?
db.php
<?php
class DbConnect {
private $host = 'localhost';
private $dbname = 'database';
private $username = 'root';
private $password = '';
public function __construct() {
try {
$conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception) {
throw new Exception($exception->getMessage());
}
}
}
main.php
<?php
require_once 'db.php';
class Main extends DbConnect {
public function __construct() {
parent::__construct();
}
public function ShowUsers() {
$sql = "SELECT * FROM users";
$result = parent::__construct()->prepare($sql); //Problem here
$result->execute();
}
}
$object = new Main();
$object->ShowUsers();
Note: I don't want to use encapsulation to make it work, I want to learn how to call the variable without using encapsulation, if possible.
Based on the code above and the comments, I recommend that you declare $conn as protected in your DbConnect class:
<?php
// db.php
class DbConnect {
private $host = 'localhost';
private $dbname = 'database';
private $username = 'root';
private $password = '';
protected $conn;
public function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception) {
throw new Exception($exception->getMessage());
}
}
}
Then in main.php, you can do:
<?php
// main.php
require_once 'db.php';
class Main extends DbConnect {
public function __construct() {
parent::__construct();
}
public function ShowUsers() {
$sql = "SELECT * FROM users";
$result = $this->conn->prepare($sql);
$result->execute();
}
}
$object = new Main();
$object->ShowUsers();
?>

PHP query class not returing values

I am writing a query class for my php project, But i have a problem the query does not return any values from my DB.
PHP code:
<?php
class DatabaseConnect{
protected $host = 'localhost';
protected $user = 'root';
protected $pass = 'root';
protected $db = 'test';
public function __construct(){
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db) or die('Cannot Connect to DB');
return $con;
}
}
class ExecuteQuery{
public $connection;
public $result;
public function __construct(){
$this->connection = new DatabaseConnect();
}
public function getQueryAction($sql){
$this->result = mysqli_query($this->connection, $sql);
}
public function setStringAction($string){
$file = file_get_contents('queryFile.json');
$json = json_decode($file, true);
foreach($json['Queries'] as $this->result){
return $this->result[$string];
}
}
}
$execute = new ExecuteQuery();
Jason file ('it will contain all the queries') :
{
"Queries": [
{"query1":"SELECT * FROM tbl_user"},
{"query2":"SELECT * FROM tbl_users WHERE status=1"}
]
}
Index file:
<?php
require_once('query.php');
?>
<html>
<head>
<title>
</title>
</head>
<body>
<h1>Welcome</h1>
<h3><?php
$execute->getQueryAction($execute->setStringAction('query1'));
foreach($execute->result as $item){
echo $item['id']. ' ' . $item['user_name'] .'<br />';
}
?></h3>
</body>
</html>
So what I do is create a class to process jason file extract a query and then class to run a query. Jason file as I mentioned holds all the queries, In index and in any file where I include query.php i can run all the queries like this:
$execute->getQueryAction($execute->setStringAction('query name'));
after some debugging I realised that the code fails in getQueryAction method, I think mysqli_query dont like $this->connection.
My questions are :
Why
and how to fix it
A constructor cannot return anything, a constructor only purpose is to create an instance of a class
private $con;
public function __construct(){
$this->con = mysqli_connect($this->host, $this->user, $this->pass, $this->db)
or die('Cannot Connect to DB');
}
public function get_connection(){
return $this->con;
}
so in ExecuteQuery class you can do:
public function __construct(){
$db = new DatabaseConnect();
$this->connection = $db->get_connection();
}
mysqli->query does not return results. It only returns a handle with which you could request the results. Look up mysqli->fetch_assoc
http://php.net/manual/en/mysqli-result.fetch-assoc.php
if ($result = mysqli_query($this->connection, $sql)) {
/* fetch associative array */
while ($item = mysqli_fetch_array($result)) {
echo $item['id']. ' ' . $item['user_name'] .'<br />';
}
/* free result set */
mysqli_free_result($result);
}
Thx for trying to help me guys, But I just managed to fixe it with minor changes here they are:
changed the method namd from __construct to DBcon under DatabaseConnection class,
then i did this in get getQueryAction:
$this->result = mysqli_query($this->connection->DBcon(), $sql);
the whole class:
class DatabaseConnect{
protected $host = 'localhost';
protected $user = 'root';
protected $pass = 'root';
protected $db = 'test';
public function DBcon(){
$con = mysqli_connect($this->host, $this->user, $this->pass, $this->db) or die('Cannot Connect to DB');
return $con;
}
}
class ExecuteQuery{
public $connection;
public $result;
public function __construct(){
$this->connection = new DatabaseConnect();
}
public function getQueryAction($sql){
$this->result = mysqli_query($this->connection->DBcon(), $sql);
}
public function setStringAction($string){
$file = file_get_contents('queryFile.json');
$json = json_decode($file, true);
foreach($json['Queries'] as $this->result){
return $this->result[$string];
}
}
}
$execute = new ExecuteQuery();
Now everything works perfect still not sure why the previous method (present in inital question) but this works xD

How to properly use dependency injection with PHP?

I'm very new at PHP. I have two classes: Database and RetrieveItem. Because RetrieveItem needs a connection, I've just been extending the Database class to use its constructor. Apparently this is wrong, because RetrieveItem is not a database?
Here is my current code:
class Database {
public $host = '127.0.0.1';
public $username = 'root';
public $password = '';
public $dbname = 'example';
function __construct(){
$this->connect = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
}
class RetrieveItem extends Database {
function retrieve_item(){
$query = $this->connect->prepare("SELECT * FROM posts");
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
}
And on a separate page, to use this, I have:
include 'db.php';
$retrieve = new RetrieveItem();
print_r($retrieve->retrieve_item());
Rather than extend the class, how can I access the Database constructor in the cleanest possible way?
Any help or guidance would be much appreciated.
This amended code is still not working:
Argument 1 passed to RetrieveItem::__construct() must be an instance of Database, none given:
class Database {
public $host = '127.0.0.1';
public $username = 'root';
public $password = '';
public $dbname = 'example';
function __construct(){
$this->connect = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
}
class RetrieveItem {
private $_db;
public function __construct(Database $database){
$this->_db = $database;
}
public function retrieve_item(){
$query = $this->connect->prepare("SELECT * FROM posts");
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
}
In use:
include 'db.php';
$database = new Database();
$retrieve = new RetrieveItem($database);
print_r($retrieve->retrieve_item());
As you said, with plain dependency injection
class RetrieveItem {
private $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
}
For easier use, you can abstract the injection in container, or, at least, has one super class that recieves the injection.
A dependency injection is so easy but it sounds complicated.
$class1 = new firstclass();
$class2 = new secondclass($class1); //This is a dependency injection.
class firstclass{
private $var1;
private $var2;
public function __construct(){
$this->var1 = "hello";
$this->var2 = "world";
}
public function getvar1(){
return $this->var1;
} //imagine a second one like this for var2;
}
class secondclass{
private $fc; //will hold first class object or the dependency.
public function __construct($firstclassobject){
$this->fc = $firstclassobject;
echo $this->fc->getvar1(); //call dependency methods like this.
echo $this->fc->getvar2();
} //echoes helloworld
}
So you pretty much put an object of one class and asign it to a field in your other class.
for your edit
set this line in your database class at the top.
public connect; //add to dbclass
Then do this in your function
public function retrieve_item(){
$connect = $this->db->connect; //added this
$query = $connect->prepare("SELECT * FROM posts"); //changed this
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
class Database {
public $host = '127.0.0.1';
public $username = 'root';
public $password = '';
public $dbname = 'example';
public $connect;
function __construct(){
$this->connect = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
}
class RetrieveItem {
private $connect;
public function __construct(&$db){
$this -> connect = $db -> connect;
}
function retrieve_item(){
$query = $this->connect->prepare("SELECT * FROM posts");
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
}
// Usage
$db = new Database();
$retrieve_item = new RetrieveItem($db);
Here in Retrieve Item we tried to send the database object as a refereneced variable rather sending a copy of its, which happens to be a good way of passing connection to your operable classes

Data Base Connection Class with PDO statement

I've just started to learn OOP PHP and i'm trying create class that will do connection to my data base.
The code:
class DB_CONNECT
{
private $host ;
private $dbName ;
private $userName ;
private $password;
private $db;
public function __construct($host,$dbName,$userName,$password){
$this->host = $host;
$this->dbName = $dbName;
$this->userName = $userName;
$this->password = $password;
try {
$this->db = new PDO('mysql:host='.$this->host.';dbname='.$this->dbName.';charset=utf8',$this->userName,$this->password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->db;
} catch (Exception $e) {
ECHO $e->getMessage();
}
}
}
$db = new DB_CONNECT("localhost", "oopcms","viktor","viktor");
function select($db){
$query = $db->prepare("SELECT * FROM `test`");
$query->execute();
$row = $query->fetchAll(PDO::FETCH_ASSOC);
return $row;
}
$x = select($db);
var_dump($x);
But I am getting this error:
Fatal error: Call to undefined method DB_CONNECT::prepare();
What I understand is that the PDO object couldn't be created. Can you give some guidance please?
Learning OOP is not the reason for creating pointless classes.
Unfortunately, you created one. PDO don't need a class to be built on top of it. Just leave it as is.
So, instead of
$db = new DB_CONNECT("localhost", "oopcms","viktor","viktor");
make it
$db = new PDO("localhost", "oopcms","viktor","viktor");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
that would be way clearer and useful
who interested here is the solution of this and Pekka and Your Common Sense thank you for a tip:)
class Select
{
private $query;
private $dbh;
private $row;
public function __construct(){
$this->dbh = new DB_CONNECT("localhost", "oopcms","viktor","viktor");
}
public function select(){
$this->query = $this->dbh->db->prepare("SELECT * FROM `test`");
$this->query->execute();
$this->row = $this->query->fetchAll(PDO::FETCH_ASSOC);
return $this->row;
}
}
$sel = new Select();
$s = $sel->select();
var_dump($s);

Class is not inheriting DB correctly

So I have a DB class that looks like this
class db{
private $hostname = 'localhost';
private $username = 'root';
private $password = 'root';
private $con;
public function db(){
try {
$dbh = new PDO("mysql:host=$this->hostname;dbname=myDB", $this->username, $this->password);
}catch(PDOException $e){
echo $e->getMessage();
exit();
}
$this->con = $dbh;
echo 'Connected to database<br />';
}
And my index.php
include('db.class.php');
include('todo.class.php');
include('dressTemplate.inc.php');
$db = new db;
$todo = new todo($db);
And my todo.class.php start like this
class todo{
function todo(db $db){
$this->db = $db;
}
public function render($post) {
$db &= $this->db;
But then I get this notice
Notice: Undefined variable: db in todo.class.php on line 11
Notice: Object of class db could not be converted to int in todo.class.php on line 11
How do I get db to be defined correctly in todo.class.php?
You are using &=. That is equal to $db = $db & $this->db. And first notice is there because PHP knows nothing of $db (it's undeclared yet). Second notice is because you're trying to do (null) & (object). First will be converted to int first and then 'object could not be converted' will appear, obviously (since PHP will try to treat whole expression as int)
That's it: your object variable is set correctly, but your $db variable is local and has nothing to do with it. And you're doing something strange with object via & (bitwise AND)
Tip: do not use old PHP4 way to define class constructors - unless you're using PHP4. In PHP5 there's __construct() magic method for that.
Try this:
class todo {
var $db;
__construct(&$db) {
$this->db = $db;
}
public function render($post) {
$db = &$this->db;
}
}
Your todo class should either use the __construct or a public function with the class name, e.g.
class todo {
var $db;
__construct (db $db) {
$this->db = $db;
}
// OR
public function todo(db $db){
$this->db = $db;
}
...
}
You should use a public constructor: __construct()
This works fine for me:
class db{
private $hostname = 'localhost';
private $username = 'root';
private $password = 'root';
private $con;
public function __construct(){
try {
$dbh = new PDO("mysql:host=$this->hostname;dbname=myDB", $this->username, $this->password);
}catch(PDOException $e){
echo $e->getMessage();
exit();
}
$this->con = $dbh;
echo 'Connected to database<br />';
}
}
class todo{
public function __construct(db $db){
$this->db = $db;
}
}

Categories