I'm experimenting with PHP and object oriented programming in PHP. When I try to run the following displayArray function, it does not display the line at all. Does anyone know what I'm doing wrong?
<?php
class Student
{
var $name;
var $arr;
function Student()
{
$this->name = "bob";
$this->addnametostring("Hello there ");
$this->arr = array();
for($i=0; $i<30; $i++) {
$arr[$i] = rand(0,100);
}
}
function addnametostring($s)
{
$s.= " " . $this->name;
echo "$s <br>";
}
function displayArray($amt)
{
foreach($this->arr as $key) {
//why is this not working
echo "<br>hello: ".$key;
}
}
}
$student = new Student;
echo "<br>";
$student->displayArray(20);
?>
Change this
for($i=0; $i<30; $i++){
$arr[$i] = rand(0,100);
}
to
for($i=0; $i<30; $i++){
$this->arr[$i] = rand(0,100);
}
EDIT: Did not notice you are missing your constructor, so your entire class should look like this
class Student(){
var $name;
var $arr;
public function __construct() {
$this->name = "bob";
$this->addnametostring("Hello there ");
$this->arr = array();
for($i=0; $i<30; $i++){
$this->arr[$i] = rand(0,100);
}
}
function addnametostring($s){
$s.= " " . $this->name;
echo "$s <br>";
}
function displayArray($amt){
foreach($this->arr as $key){
//why is this not working
echo "<br>hello: ".$key;
}
}
}
in php constructer is as follow
function __construct(){
//some code
}
so you are not calling student function.
You can use a constructor to easily assign the array when you first call the class.
<?php
class Student
{
public $name;
public $arr;
function __construct()
{
$this->name = "bob";
$this->addnametostring("Hello there ");
$this->arr = array();
for($i=0; $i<30; $i++) {
$this -> arr[$i] = rand(0,100);
}
}
function addnametostring($s)
{
$s.= " " . $this->name;
echo "$s <br>";
}
function displayArray()
{
foreach($this->arr as $key) {
//why is this not working
echo "<br>hello: ".$key;
}
}
}
Then,
$student = new Student;
echo "<br>";
$student-> displayArray();
I'm not sure why you had $amt variable.
Thanks.
Related
Here's a new file:
//Products.php
<h1>Products</h1>
<?php
$res = IA::printAll();
if (!empty($res))
{
$i = 0;
foreach ($res as $item)
{
echo $item[$i];
$i++;
}
}
if (User::isLogged())
{
$ids = IA::getIDs();
echo "<form name='productpf' method='POST' action='index.php'>
<select name='id'>";
if (!empty($ids))
{
$a = 0;
foreach ($ids as $item)
{
echo "<option value = $item[$a]>$item[$a]</option>";
$a++;
}
}
echo"</select>
<input type='submit' name='addcart' value='Add To Cart' size='30'>
</form>";
}
?>
OK, so the problem now, is that a Fatal error: Call to a member function query() on null in C:\xampp\htdocs\InternetApplications\Classes\IA.php on line 41 is happening. So here are the two functions called on IA.php:
//IA.php
public function get()
{
$db = MySQL::getDB();
$sql = "SELECT * FROM ia";
$res = $db->query($sql); //------------->LINE 41<--------------
return $res;
}
public static function printAll()
{
$p = new IA();
$res = $p->get();
$nrows = $res->num_rows;
$array = array();
for($i = 0;$i < $nrows; $i++)
{
$pdb = $res->fetch_object();
$array[] = array($i => "<div style='border-style:groove' style='border:5px solid gray'>
<p>id: '$pdb->id' </p>
<p>name: '$pdb->name' </p>
<p>type: '$pdb->type' </p>
<p>description: '$pdb->description' </p>
<p>price: '$pdb->price'</p>
</div>");
}
$res->free();
return $array;
}
public static function getIDs()
{
$p = new IA();
$res = $p->get();
$nrows = $res->num_rows;
$array = array();
for($i = 0;$i < $nrows; $i++)
{
$pdb = $res->fetch_object();
$array[] = array($i => $pdb->id);
}
$res->free();
return $array;
}
Now the weird thing, as you can see, both functions above call get() method, and only the second one being called gives the error. In this case the second one being called is getIDs(), so that is the function that doesn't send any output. IF I switch the order and put getIDs() in first, it works but the second one, printAll() does not, therefore, no output. Here are the last two methods from the MySQL class, both of them called by function get():
//MySQL.php
public static function getDB()
{
if (self::$db == NULL)
{
return self::$db = new self();
}
}
public function query($sql)
{
$res = $this->conn->query($sql);
if (!$res)
{
echo $this->conn->error;
}
return($res);
}
there is a huge problem with your getDB method : it returns nothing if the DB exists !
it should be :
public static function getDB()
{
if (self::$db == NULL)
{
self::$db = new self();
}
return self::$db;
}
I am getting undefined variable for periods and subPeriods on the last line of this program. not sure what the problem is. Could it be my instances?
This is my first proper attempt at oop in PHP so i am sure i am doing something wrong.
$global_periods = 5;
$global_subperiods = 2;
$questionslist = array("q_1_1", "q_1_2", "q_2_1", "q_2_2", "q_3_1", "q_4_1", "q_5_1");
class User {
public $userId;
public $periods = array();
public function __construct($number)
{
$this->userId = $number;
}
public function addPeriod($pno)
{
$periods[] = new Period($pno);
}
}
class Period {
public $periodNo;
public $subPeriods = array();
public function __construct($number)
{
$this->periodNo = $number;
}
public function addSubPeriod($spno)
{
$subPeriods[] = new SubPeriod($spno);
}
}
class SubPeriod {
public $SubPeriodNo;
public $answers = array();
public function __construct($number)
{
$this->SubPeriodNo = $number;
}
public function addAnswer($answer)
{
$answers[] = new Answer($answer);
}
}
class Question {
public $answer;
public function __construct($ans)
{
$this->answer = $ans;
}
public function getAnswer()
{
echo $answer;
}
}
$userlist = array();
$sql = 'SELECT user_ref FROM _survey_1_as GROUP BY user_ref ORDER BY user_ref ASC';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[] = new User($row['user_ref']);
}
for ($i = 0; $i >= count($userlist); $i++)
{
for ($x = 1; $x > $global_periods; $x++)
{
$userlist[i]->addPeriod($x);
for ($y = 1; $y > $global_subperiods; $y++)
{
$userlist[i]->$periods[x]->addSubPeriod($y);
foreach($questionslist as $aquestion)
{
$sql = 'SELECT ' . $questionNumber . ' FROM _survey_1_as WHERE user_ref = ' .
$i . ' AND answer_sub_period = ' . $y . ' AND answer_period = ' . $x .'';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$userlist[i]->$periods[x]->$subPeriods[y]->addAnswer($row[$questionNumber]);
}
}
}
}
}
$userlist[3]->$periods[2]->$subPeriods[2]->getAnswer();
Remove all the $ signs behind the $userlist, you only need to define the first variable. You can't use dollar signs like this, this way, it will try get the value of the word after the $ sign and call that, but that variable doesn't exist.
i have a basic form that loads 15 dropdown boxes with the same topics in each box. this is a voting page where the user can vote for his favorite topic or his least favorite topic. the problem i have is that the topics arent being loaded when i tell them to. Here is my code.
PHP
<?php
$Vote = new Vote();
class Vote {
public function GetTopic() {
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Query = 'SELECT * FROM Topics';
if($Gather = $Connect->query($Query))
{
while($Row = $Gather->fetch_assoc())
{
$Topic = $Row['Topic'];
echo '<option>'.$Topic.'</option>';
}
$Gather->free();
}
else
{
echo 'Error';
}
$Connect->close();
}
public function LoadTopic() {
for($I = 15; $I > 0; $I--)
{
echo '<select><option>'.$I.'</option>'.$this->GetTopic().'</select>';
}
}
}
?>
If you use your function like this you should return your html-data instead of outputting it:
public function GetTopic() {
$Connect = new mysqli("127.0.0.1", "root", "", "Data");
$Query = 'SELECT * FROM Topics';
if($Gather = $Connect->query($Query))
{
$html = "";
while($Row = $Gather->fetch_assoc())
{
$Topic = $Row['Topic'];
$html .= '<option>'.$Topic.'</option>';
}
$Gather->free();
return $html;
} else
{
//handle error
}
$Connect->close();
}
Let's try something a bit more appropriate for a class:
<?php
class Vote
{
private $connect;
public $topics = array();
public function __construct()
{
$this->connect = new mysqli( '127.0.0.1', 'root', '', 'Data' );
if( $this->connect->connect_errno )
{
echo "Error:(" . $this->connect->connect_errno . "): " . $this->connect->connect_error . ".";
}
}
public function GetTopics()
{
$Query = 'SELECT * FROM Topics';
if( $Gather = $this->connect->query( $Query ) )
{
while( $Row = $Gather->fetch_assoc() )
{
$this->topics[] = $Row['Topic'];
}
$Gather->free();
}
else
{
echo 'Error';
}
}
public function LoadTopics()
{
if( $max = count($this->topics) > 0 )
{
$html = "<select>\r\n";
for( $i = 0; $i < $max; ++$i )
{
$html .= "<option value=" . $i . ">" . $this->topics[$i] . "</option>";
}
$html .= "</select>\r\n";
return $html;
}
else
{
return false;
}
}
public function __destruct()
{
$this->connect->close();
}
}
?>
The __construct() / __destruct() methods are practically made to put your connection in. You could have also combined both functions and just have the GetTopics() method (I compulsively changed some method and property names) run the query, format the results and return the $html.
Also, I upgraded your for function, in case you decide to add another entry later to your topics, it will expand with it instead of it counting through 15 static rows.
You can call it with:
<?php
$vote = new Vote();
echo $vote->GetTopics()->LoadTopics();
?>
I saw the answer was already selected, didn't want my work to go to waste though ;D
Alternate GetTopics() function, all rolled into one.
public function GetTopics()
{
$Query = 'SELECT * FROM Topics';
if( $Gather = $this->connect->query( $Query ) )
{
$html = "<select>\r\n";
$i = 0;
while( $Row = $Gather->fetch_assoc() )
{
$html .= "<option value=" . $i . ">" . $Row['Topic'] . "</option>";
++i;
}
$html .= "</select>\r\n";
$Gather->free();
return $html;
}
else
{
return "Error: No Results Returned";
}
}
And now it's just called by:
<?php echo $vote->GetTopics(); ?>
<?
session_start();
/*
echo $_SESSION['SQLIP'];
echo "<br>";
echo $_SESSION['SQLDB'];
echo "<br>";
echo $_SESSION['SQLUSER'];
echo "<br>";
echo $_SESSION['SQLPASS'];
echo "<br>";
*/
class DB_MSSQL {
private $Host;
private $Database;
private $User;
private $Password;
public $Link_ID = 0;
public $Query_ID = 0;
public $Record = array();
public $Row = 0;
public $Errno = 0;
public $Error = "";
public $Halt_On_Error = "yes";
public $Auto_Free = 1;
public $PConnect = 0;
public function _construct(){
$this->Host = $_SESSION['SQLIP'];
$this->Database = $_SESSION['SQLDB'];
$this->User = $_SESSION['SQLUSER'];
$this->Password = $_SESSION['SQLPASS'];
}
function DB_MSSQL($query = "") {
if($query) {
$this->query($query);
}
}
function connect() {
if ( 0 == $this->Link_ID ) {
if(!$this->PConnect) {
$this->Link_ID = mssql_connect($this->Host, $this->User, $this->Password);
} else {
$this->Link_ID = mssql_pconnect($this->Host, $this->User, $this->Password);
}
if (!$this->Link_ID)
$this->connect_failed("connect ($this->Host, $this->User, \$Password) failed");
else
if (!mssql_select_db($this->Database, $this->Link_ID)) {
$this->connect_failed("cannot use database ".$this->Database);
}
}
}
function connect_failed($message) {
$this->Halt_On_Error = "yes";
$this->halt($message);
}
function free_result(){
mssql_free_result($this->Query_ID);
$this->Query_ID = 0;
}
function query($Query_String)
{
/* No empty queries, please, since PHP4 chokes on them. */
if ($Query_String == "")
/* The empty query string is passed on from the constructor,
* when calling the class without a query, e.g. in situations
* like these: '$db = new DB_Sql_Subclass;'
*/
return 0;
if (!$this->Link_ID)
$this->connect();
// printf("<br>Debug: query = %s<br>\n", $Query_String);
$this->Query_ID = mssql_query($Query_String, $this->Link_ID);
$this->Row = 0;
if (!$this->Query_ID) {
$this->Errno = 1;
$this->Error = "General Error (The MSSQL interface cannot return detailed error messages).";
$this->halt("Invalid SQL: ");
}
return $this->Query_ID;
}
function next_record() {
if ($this->Record = mssql_fetch_row($this->Query_ID)) {
// add to Record[<key>]
$count = mssql_num_fields($this->Query_ID);
for ($i=0; $i<$count; $i++){
$fieldinfo = mssql_fetch_field($this->Query_ID,$i);
$this->Record[strtolower($fieldinfo->name)] = $this->Record[$i];
}
$this->Row += 1;
$stat = 1;
} else {
if ($this->Auto_Free) {
$this->free_result();
}
$stat = 0;
}
return $stat;
}
function seek($pos) {
mssql_data_seek($this->Query_ID,$pos);
$this->Row = $pos;
}
function metadata($table) {
$count = 0;
$id = 0;
$res = array();
$this->connect();
$id = mssql_query("select * from $table", $this->Link_ID);
if (!$id) {
$this->Errno = 1;
$this->Error = "General Error (The MSSQL interface cannot return detailed error messages).";
$this->halt("Metadata query failed.");
}
$count = mssql_num_fields($id);
for ($i=0; $i<$count; $i++) {
$info = mssql_fetch_field($id, $i);
$res[$i]["table"] = $table;
$res[$i]["name"] = $info->name;
$res[$i]["len"] = $info->max_length;
$res[$i]["flags"] = $info->numeric;
}
$this->free_result();
return $res;
}
function affected_rows() {
// Not a supported function in PHP3/4. Chris Johnson, 16May2001.
// return mssql_affected_rows($this->Query_ID);
$rsRows = mssql_query("Select ##rowcount as rows", $this->Link_ID);
if ($rsRows) {
return mssql_result($rsRows, 0, "rows");
}
}
function num_rows() {
return mssql_num_rows($this->Query_ID);
}
function num_fields() {
return mssql_num_fields($this->Query_ID);
}
function nf() {
return $this->num_rows();
}
function np() {
print $this->num_rows();
}
function f($Field_Name) {
return $this->Record[strtolower($Field_Name)];
}
function p($Field_Name) {
print $this->f($Field_Name);
}
function halt($msg) {
if ("no" == $this->Halt_On_Error)
return;
$this->haltmsg($msg);
if ("report" != $this->Halt_On_Error)
die("Session halted.");
}
function haltmsg($msg) {
printf("<p>Server have a critical error!<br><br><br>We are very sorry for any inconvenience!<br><br>\n", $msg);
printf("<b>MSSQL Error</b>: %s (%s)</p>\n",
$this->Errno,
$this->Error);
}
}
$_php_major_version = substr(phpversion(), 0, 1);
if((4 > $_php_major_version) or !class_exists("DB_Sql"))
{
class DB_Sql extends DB_MSSQL
{
function DB_Sql($query = "")
{
$this->DB_MSSQL($query);
}
}
}
unset($_php_major_version);
?>
I have a question, why on DB_MSSQL my $Host,$Datebase,$User,$Password are empty?
If i test $_SESSIONS Between DB_MSSQL are OK.
Class don't have errors but this variables are empty... and i don't know why..
Can anybody help me?
Thank you verry much!
You have missed one underscore, you should have write :
public function __construct()
It should work like this.
Why can't initiate my object to an array[]?
This is my work: clothing_product.php
include('../database.php');
class Clothing_Product {
public $db;
public $procode;
public $probprice;
public $proprice;
public $prodes;
public $propath;
public $prostatus;
public $image;
public function __construct() {
$this->db = new MySqlDatabase();
}
public function get_all(){
return self::get_by_query('SELECT * FROM tblclothing_product;');
}
public function get_by_query($sql=""){
$result_set = $this->db->query($sql);
$object_array = array();
while($row = $this->db->fect_array($result_set)){
$object_array[] = $this->instantiate($row);
echo var_dump($object_array);
}
return $object_array;
}
private function instantiate($record){
//Dynamic control
$object = new self;
foreach($record as $attribute=>$value){
if($object->has_attribute($attribute)){
$object->attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute){
$object_vars = get_object_vars($this);
return array_key_exists($attribute,$object_vars);
}
public function add_new($a,$b,$c,$d,$e,$f){
$this->procode = $a;
$this->probprice = $b;
$this->proprice = $c;
$this->prodes = $d;
$this->propath = $e;
$this->prostatus = $f;
$sql="INSERT INTO `tblclothing_product`(`proCode`,`proBPrice`,`proPrice`,`proDes`,`proPath`,`proStatus`) VALUES(
'" . $a ."',
'" . $b ."',
'" . $c ."',
'" . $d ."',
'" . $e ."',
" . $f ."
)";
$this->db->query($sql);
}
public function image_string($a,$b,$c,$d,$e){
$this->image='';
if($a!=""){
$this->image = $this->image. $a .";";
}
if($b!=""){
$this->image = $this->image. $b .";";
}
if($c!=""){
$this->image = $this->image. $c .";";
}
if($d!=""){
$this->image = $this->image. $d .";";
}
if($e!=""){
$this->image = $this->image. $e;
}
return $this->image;
}
public function remove_by_id($id){
$this->db->query('DELETE FROM tblclothing_product WHERE proId={$id};');
}
public function get_by_id($id=0){
$result_array = self::get_by_query('SELECT * FROM tblclothing_product WHERE proId={$id} LIMIT 1;');
return !empty($result_array) ? array_shift($result_array) : FALSE;
}
public function image_exploit_string(){
$arr = array();
if($this->image != ""){
$arr = explode(";",$this->image);
}
return $arr;
}
}
I try to echo the above script var_dump($object_array) my array and it has shown null to every object. It looks like it can't initiate at all.
In clothing_view.php it is a script to view my array of object but it has shown null.
require_once("../include/function.php");
require_once("../include/database.php");
$buttonname = $_POST["submit"];
$image1 = '';
$image2 = '';
$image3 = '';
$image4 = '';
$image5 = '';
$image1 = $_FILES['image1']['name'];
$image2 = $_FILES["image2"]['name'];
$image3 = $_FILES["image3"]['name'];
$image4 = $_FILES["image4"]['name'];
$image5 = $_FILES["image5"]['name'];
$obj = new Clothing_Product();
$items = $obj->get_all();
foreach($items as $item){
echo "ProId:".$item->procode."<br />";
echo "ProPath:".$item->propath."<br />";
}
In database.php:
require_once('config.php');
class MySqlDatabase
{
private $connection;
private $last_query;
private $magic_quotes_active;
private $real_escape_string_exist;
function __construct(){
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exist = function_exists("mysql_real_escape_string");
}
private function open_connection()
{
$this->connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$this->connection){
die("Connection failed!". mysql_error());
}
else{
$db_select = mysql_select_db(DB_NAME);
if(!$db_select){
die("Select database failed". mysql_error());
}
}
}
public function query($sql){
$this->last_query = $sql;
$result = mysql_query($sql,$this->connection);
$this->confirm_query($result);
return $result;
}
public function confirm_query($result){
if(!$result){
$output = "Database query failed: " . mysql_error()."<br /><br />";
$output.= "Last query that fail is:" . $this->last_query;
die($output);
}
}
private function escape_value($value) {
if ($this->real_escape_string_exist) {
if($this->magic_quotes_active) {$value = stripslashes($value);}
$value = mysql_real_escape_string($value);
}
else {
if (!$this->magic_quotes_active) {$value = addslashes($value);}
}
return $value;
}
public function fect_array($result){
return mysql_fetch_array($result);
}
public function num_rows($result){
return mysql_num_rows($result);
}
public function last_id(){
return mysql_insert_id($this->connection);
}
public function affected_rows(){
return mysql_affected_rows($this->connection);
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
}
Is there problem with $item->? It always returns null.
Finally, I got what you trying to do.. If you need db result as object (ORM-like), you can use another class for this (just an advise).
Pseudo;
// Let's call another class as CProduct
class CProduct
{
public $procode, $probprice,
$proprice, $prodes,
$propath, $prostatus,
$image;
public function __construct($row) {
foreach ($row as $key => $val) {
if ($this->_hasAttr($key)) {
$this->$key = $val;
}
}
}
private function _hasAttr($key) {
return array_key_exists($key, get_class_vars($this));
}
// you can also extend your class here
// and use it anywhere
public function printCode() {
print $this->procode;
}
}
And using in your case;
while ($row = $this->db->fect_array($result_set)) {
$object_array[] = new CProduct($row);
}
Html part;
<p>Product Code: <?php $cp->printCode(); ?></p>
As far as I see, self::get_by_query will never work cos it is not defined as static function.
Opt. 1- You can define it so: public static function get_by_query
Opt. 2- You can call it so: $this->get_by_query
PS: var_dump doesn't need echo.
I think your problem is that you set the object properties in the instantiate function with
$object->attribute = $value;
instead of the likely more useful
$object->{$attribute} = $value;
Even if it does not solve your problem right away, this would likely make you pull your hair later...