Jump to content

[SOLVED] PHP 5 Classes


rizla_za

Recommended Posts

Hi guys/girls

 

I'm a newbie in php 5 and classes so I hope someone would be able to help me with this 1. I'm busy learning php 5 and classes and have written a simple class to help me and if someone can explain to me why the one class works and the other not I will be very grateful.

 

Working Code:

<?php

class OpenRead

{

var $name;

function OpenDB($localhost,$username,$password,$database)

{

$mysqli = new mysqli($localhost, $username, $password, $database);

$query = "select * from test where id='1'";

$result = $mysqli->query($query);

$row = $result->fetch_assoc();

$this->name = $row["name"]; 

}

}

?>

 

<?php

    $a = new OpenRead();

    $a->OpenDB('localhost','user_psi','pass_psi_3375','psimation_inv');

 

    echo $a->name;

?>

 

This code is working fine and display the name in my db, but when I use the code witch follow it's not working.

 

<?php

class OpenRead

{

var $name;

function OpenDB($localhost,$username,$password,$database)

{

$mysqli = new mysqli($localhost, $username, $password, $database); 

}

  function GetName()

  { 

  $query = "select * from test where id='1'";

  $result = $mysqli->query($query);

  $row = $result->fetch_assoc();

  $this->name = $row["name"]; 

  }

}

?>

 

<?php

    $a = new OpenRead();

    $a->OpenDB('localhost','user_psi','pass_psi_3375','psimation_inv');

    $a->GetName();

    echo $a->name;

?>

 

Like I said I'm a noob to php 5 and this might be a very stupid question...

Link to comment
https://forums.phpfreaks.com/topic/86024-solved-php-5-classes/
Share on other sites

You need to assign $mysqli to a class variable.

 

var $_mysqli;

 

and assign $mysqli to that when you connect...

 

$mysql = new mysqli();

$this->mysqli = $mysql;

 

then in your function use $this->mysqli->query(); etc etc;

 

I believe in the other functions you can also just do

 

global $mysqli;

 

 

You should learn the newer and PHP5 way of classes using Private, Protection public etc etc.

 

<?php
class OpenRead
{
var $name;
private $_mysqli;

function OpenDB($localhost,$username,$password,$database) 
{
$mysqli = new mysqli($localhost, $username, $password, $database); 
$this->mysqli = $mysqli;
}
  function GetName()
  {  
  $query = "select * from test where id='1'"; 
  $result = $this->mysqli->query($query);
  $row = $result->fetch_assoc();
  $this->name = $row["name"];  
  }
}
?>

Link to comment
https://forums.phpfreaks.com/topic/86024-solved-php-5-classes/#findComment-439275
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.