Why is include('../myscript.php') causing an error? - php

I've been trying to debug my PHP script and I've narrowed down the problem to the line
include "../classes.php";
at the top of my file team_manager.php which is where you see it below.
themes
my_theme
js
management
team_manager.php
project_manager.php
classes.php
footer.php
functions.php
Am I not doing the path correctly? Or could it be something wrong with the contents of classes.php? If it could be a problem with the file being included, below is the file, and let me know if anything immediately stands out as wrong.
<?php
final class MySqlInfo
{
const DBNAME = 'somedb';
const USER = 'someuser';
const PSSWD = 'somepassword';
const TEAMTABLENAME = 'sometablename';
public function getUser ( )
{
return self::USER;
}
public function getPassword ( )
{
return self::PSSWD;
}
}
final class MethodResult
{
public $succeeded;
public $message;
public MethodResult ( $succeededInit = NULL, $messageInit = NULL )
{
this->$succeeded = $succeededInit;
this->$message = $messageInit;
}
}
final class MySite
{
const ROOTURL = 'http://asite.com/subsite';
function getRootUrl()
{
return self::ROOTURL;
}
}
final class TeamManager
{
private $dbcon;
public function TeamManager ( )
{
$dbcon = mysqli_connect('localhost', MySqlInfo.getUser(), MySqlInfo::getPassword());
$dbcon->select_db(MySqlInfo::DBNAME);
// need to add error handling here
}
final public class TeamMember
{
public $name; // team member name
public $title; // team member title
public $bio; // team member bio
public $sord; // team member sort order
public $picfn; // team member profile picture file name
}
public function addMember ( TeamMember $M )
{
if ($this->$dbcon->connect_error)
{
return new MethodResult(false, 'Not connected to database');
}
$q = "INSERT INTO " . MySqlInfo::TEAMTABLENAME . " (" . implode( ',' array($M->name, $M->title, $M->bio, $M->sord, $M->picfn) ) . ") VALUES ('" . implode('\',\'', array($_POST['fullname'], $_POST['title'], $_POST['bio'], $_POST['sord'], $targetFileName)) . "')";
// ^ query for inserting member M to the database
if (!mysqli_query(this->$dbcon, $q))
{
return new MethodResult(false, 'Query to insert new team member failed');
}
return new MethodResult(true, 'Successfully added new member' . $M->name);
}
}
?>

include() might cause an error in case it can't find a file to be included. It's that simple. So you have to make sure that file exists before you include it. Also, never use relative paths like ../script.php, as they introduce a number of issues. And one major issue is that, some hosting providers don't allow relative paths due to security reasons.
So to make sure the file can be included, simply do the check for its existence:
<?php
// dirname(__FILE__) returns an absolute path of the current script
// which is being executed
$file = dirname(__FILE__) . '/script.php';
if (is_file($file)) {
include($file);
} else {
echo 'File does not exist';
}
Also, I see that you write code as an old-school. You might want to take a look at PSR-FIG standards.

Related

PHP How do you define an array and reference it in a class?

I have written a php class to use in a small script to just run any query that I like from other scripts. This is NOT going to be used publicly or in production, and I'm aware of the huge security issue this poses!
I have done this as an excercise to see learn about classes etc... I seem to be having problems with one specific line in the code which is causing an error somewhere. I think it might be because I'm trying to return an array, and I think I haven't defined it properly in the class.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
This is the whole code.
<?php
class GetRandomRecord {
//Connection
public $CUDBName;
public $CUHost;
public $CUUser;
public $CUPassword;
public $in_SQL;
public $out_Resource;
public $CULink;
public $message;
public $errors = array(); // is this correct?
public $resultOfQuery = array(); // is this correct?
/****************************************************************/
public function setSQL($value){
$this->in_SQL = $value;
return $this->in_SQL;
}
/****************************************************************/
public function setConnectionString($db,$host,$user,$password){
$this->CUDBName = $db;
$this->CUHost = $host;
$this->CUUser = $user;
$this->CUPassword = $password;
}
/****************************************************************/
public function runSQL() {
$this->CULink = mysqli_connect( $this->CUHost , $this->CUUser , $this->CUPassword , $this->CUDBName);
if (mysqli_connect_errno()) {
$this->message = "Connection failed: ".mysqli_connect_error();
return $this->message;
}
$this->out_Resource = mysqli_query($this->in_SQL , $this->CULink);
if (!$this->out_Resource)
{
$this->errors['sql'] = $this->in_SQL;
$this->errors['eeDBName'] = $this->CUDBName;
$this->errors['eeLink'] = $this->CULink;
$this->errors['status'] = "false"; //There was a problem saving the data;
mysqli_close($this->CULink);
return json_encode($this->errors);
}
else
{
// success
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
mysql_close($this->CULink);
return $this->resultOfQuery;
} // if (!mysql_query( $CUDBName , $sql , $CULink))
}
/****************************************************************/
}//class
$recordGet = new getRandomRecord();
$recordGet->setConnectionString('databasename','localhost','username','password');
// select count from database
$tableName = "userList";
$countSQL = "select count(*) from $tableName";
$recordGet->setSQL($countSQL);
$result = $recordGet->runSQL();
print_r($result);
?>
Can you help me identify the problem?
EDIT: Actually I haven't got a specific error message. I have an HTTP Error 500 which usually means my code is duff, and I narrowed it down by commenting sections of code until I found the line that caused it.
You have an extra close-paren on line 64.
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC));
The line should be:
$this->resultOfQuery = mysqli_fetch_array($this->out_Resource, MYSQLI_ASSOC);

PHP call to undefined method, but method is defined... (not the same as other 2 similar questions)

I am going through a tutorial to build up a mock Flickr site in PHP. I am getting to the point where we are adding in all the user CRUD. The user class has already been defined and has methods that are being used and work. But once I added the methods for create, update, delete and save it says it can't find any of them... I have tried modifying the methods that do work, and they don't change. So to me it seems like there is a cached version of the user class, because changes in the user.php file aren't being recognized. I have used ctrl+F5 to refresh the cache, but that doesn't change anything...
This is my directory set up
wamp
www
photo_gallery
includes
config.php
constants.php
database.php
database_object.php
functions.php
initialize.php
session.php
user.php
public
admin
index,php
login.php
logout.php
logfile.php
test.php
images
javascript
layouts
stylesheets
index.php
This is my initialize.php file that sets up the directory paths and loads all the files needed
<?php
// Define the core paths
// Define them as absolute paths to make sure that require_once works as expected
//DIRECTORY_SEPARATOR is a php pre-defined constant
// ( \ for Windows, / for Unix)
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
// checks if lib path exists if not defines the site root with the directory specified below
// ***** needs to be updated when switched directories, servers or computers
defined('SITE_ROOT') ? null :
define('SITE_ROOT', DS.'Users'.DS.'Alan D'.DS.'Desktop'.DS.'wamp'.DS.'www'.DS.'photo_gallery');
// Checks if lib path has been defined, if not it defines it using site path above
defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes');
// first load config
require_once(LIB_PATH.DS.'config.php');
// load basic functions that are available for all other files
require_once(LIB_PATH.DS.'functions.php');
// load core object classes for application
require_once(LIB_PATH.DS.'session.php');
require_once(LIB_PATH.DS.'database.php');
require_once(LIB_PATH.DS.'database_object.php');
// load database-related object classes
require_once(LIB_PATH.DS.'user.php');
?>
This is the user class, it was simpler then this when I was testing, but I continued to follow through the steps to make the methods able to be dropped into my other classes when I create them.
<?php
require_once('database.php');
class User extends DatabaseObject{
protected static $db_fields = array('id', 'user_name', 'password',
'first_name', 'last_name');
protected static $table_name="users";
public $id;
public $user_name;
public $password;
public $first_name;
public $last_name;
public function full_name(){
if(isset($this->first_name) && isset($this->last_name)){
return $this->first_name . " " . $this->last_name;
} else {
return "";
}
}
// authenticates user by checking if there is a row with the
// input user name and password, then returns the object if found
// if not it returns false
public static function authenticate($user_name="", $password=""){
global $database;
$user_name = $database->escape_values($user_name);
$password = $database->escape_values($password);
$sql = "SELECT * FROM users ";
$sql .= "WHERE user_name = '{$user_name}' ";
$sql .= "AND password = '{$password}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
// checks to see if the given attribute exsits for the current object
private function has_attribute($attribute){
// associative array with all attributes key and value pairs
$object_vars = $this->attributes();
// just check if the key exists and return true or false
return array_key_exists($attribute, $object_vars);
}
// returns a key value hash of the objects variables and values
protected function attributes(){
// get_object_vars returns an associative array with all attributes
// (incl private) as the keys and their current values as value
// return get_object_vars($this);
// this goes through the db fields and populates the hash
$attributes = array();
foreach(self::$db_fields as $field){
if(property_exists($this, $field)){
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
// returns a sanitized (sql escaped) array of all the attributes
protected function sanitized_attributes(){
global $database;
$clean_attributes = array();
// sanitize the values before submitting
// Note: does not alter the actual value of each attribute
foreach($this->attributes() as $key => $value){
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
// this function check to see if the record is already there
// and determines whether to create or update.
public function save(){
return isset($this->id) ? $this->update() : $this->create();
}
public function create(){
global $database;
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)){
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
public function update(){
global $database;
$attributes = $this->sanitized_attributes();
// set up the key, value string needed for the update statement
foreach ($attributes as $key => $value){
$attribute_pairs[] = "{$key}='{$value}'";
}
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE id='". $database->escape_value($this->id);
$database->query($sql);
return($database->affected_rows() == 1) ? true : false;
}
public function delete(){
global $database;
$sql = "DELETE FROM ".self::$table_name." ";
$sql .= "WHERE id=". $database->escape_value($this->id);
$sql .= " LIMIT 1";
$database->query($sql);
return($database->affected_rows() == 1) ? true : false;
}
}
?>
In the admin/test.php file it is set up like this
<?php
require_once('../../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php include_layout_template('admin_header.php'); ?>
<?php
$user = new User();
$user->user_name = "jDoe";
$user->password = "pass";
$user->first_name = "Jamie";
$user->last_name = "Doe";
echo $user->full_name();
$user->save();
//$user = User::find_by_id(1);
//$user->password = "pass1";
//$user->update();
?>
<?php include_layout_template('admin_footer.php'); ?>
When I run that page I get the admin header layout to load, the full name is printed on the screen and directly below it says:
Fatal error: Call to undefined method User::save() in C:\wamp\www\photo_gallery\public\admin\test.php on line 17
The same was happening with create and update... but these functions do exist in the user.php file, I even emptied everything out of the methods to makes sure there was no bug in the php code inside of them.
Then I tried the test from the public folder, through public/index.php
<?php
require_once('../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("login.php"); }
?>
<?php include_layout_template('admin_header.php'); ?>
<?php
$user = new User();
$user->user_name = "jDoe";
$user->password = "pass";
$user->first_name = "Jamie";
$user->last_name = "Doe";
$user->full_name();
$user->create();
?>
<?php include_layout_template('admin_footer.php'); ?>
But this doesn't even load the admin header layout... and just gives me the same error as the other test file did. I am pretty positive that I am navigating to the correct path based on the directory set up.
For the life of me I cannot understand why/how the user object isn't being updated when I add things to the user class inside user.php. Or how I could use other methods I had previously defined in user, but they don't change when I modify them... Does php do any caching of objects that I am unaware of? I even pulled the user.php out of the includes directory... and everything still runs as explained above...
Any insight would be greatly appreciated. I have been searching around for a while now trying to find someone with a similar issue but I can't find one. Thanks for reading.
It seems in your initialize.php you have an additional directory in the SITE_ROOT definition compared to what you show in your directory structure. Do you still have another copy of this code perhaps in photo_gallery directory that this is actually including files from?
This is where all your includes are pointing to:
/Users/Alan D/Desktop/wamp/www/photo_gallery/includes

Error When Calling Function

I searched forever trying to find an answer, but was ultimately stumped. I've been writing code to allow multiple bots to connect to a chat box. I wrote all the main code and checked it over to make sure it was all okay. Then when I got to calling the function needed to make it work, it gave me an error saying:
Notice: Undefined variable: ip in C:\wamp\www\BotRaid.php on line 40
And also an error saying:
Fatal Error: Cannot access empty property in C:\wamp\www\BotRaid.php
on line 40
( Also a screenshot here: http://prntscr.com/ckz55 )
<?php
date_default_timezone_set("UCT");
declare(ticks=1);
set_time_limit(0);
class BotRaid
{
public $ip="174.36.242.26";
public $port=10038;
public $soc = null;
public $packet = array();
##############################
# You can edit below this #
##############################
public $roomid="155470742";
public $userid = "606657406";
public $k = "2485599605";
public $name="";
public $avatar=;
public $homepage="";
##############################
# Stop editing #
##############################
public function retry()
{
$this->connect($this->$ip,$this->$port); //Line 40, where I'm getting the error now.
$this->join($this->$roomid);
while($this->read()!="DIED");
}
public function connect($ip, $port)
{
if($this->$soc!=null) socket_close($this->$soc);
$soc = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(!$this->$soc)$this->port();
if(!socket_connect($this->$soc,$this->$ip,$this->$port))$this->port();
}
public function port()
{
$this->$port++;
if($this->$port>10038) $this->$port=10038;
$this->retry();
}
public function join($roomid)
{
$this->send('<y m="1" />');
$this->read();
$this->send('<j2 q="1" y="'.$this->$packet['y']['i'].'" k="'.$this->$k.'" k3="0" z="12" p="0" c"'.$roomid.'" f="0" u="'.$this->$userid.'" d0="0" n="'.$this->$name.'" a="'.$this->$avatar.'" h="'.$this->$homepage.'" v="0" />');
$this->port();
$this->$roomid;
}
public function send($msg)
{
echo "\n Successfully connected.";
socket_write($this->$soc, $this->$msg."\0", strlen($this->$msg)+1);
}
public function read($parse=true)
{
$res = rtrim(socket_read($this->$soc, 4096));
echo "\nSuccessfully connected.";
if(strpos(strtolower($res), "Failed"))$this->port();
if(!$res) return "DIED";
$this->lastPacket = $res;
if($res{strlen($res)-1}!='>') {$res.=$this->read(false);}
if($parse)$this->parse($res);
return $res;
}
public function parse($packer)
{
$packet=str_replace('+','#più#',str_replace(' ="',' #=#"',$packet));
if(substr_count($packet,'>')>1) $packet = explode('/>',$packet);
foreach((Array)$packet as $p) {
$p = trim($p);
if(strlen($p)<5) return;
$type = trim(strtolower(substr($p,1,strpos($p.' ',' '))));
$p = trim(str_replace("<$type",'',str_replace('/>','',$p)));
parse_str(str_replace('"','',str_replace('" ','&',str_replace('="','=',str_replace('&','__38',$p)))),$this->packet[$type]);
foreach($this->packet[$type] as $k=>$v) {
$this->packet[$type][$k] = str_replace('#più#','+',str_replace('#=#','=',str_replace('__38','&',$v)));
}
}
}
}
$bot = new BotRaid; //This is where I had the error originally
$bot->retry();
?>
Line 40 is below the "Stop Editing" line. Anyone have any suggestions? Or perhaps need me to clear some things up?
You are accessing the properties of the class incorrectly.
The line:
$this->connect($this->$ip,$this->$port);
Should be:
$this->connect($this->ip, $this->port);
Since there was no local variable called $ip, your expression was evaluating to $this-> when trying to access the property since PHP lets you access properties and functions using variables.
For example, this would work:
$ip = 'ip';
$theIp = $this->$ip; // evaluates to $this->ip
// or a function call
$method = 'someFunction';
$value = $this->$method(); // evaluates to $this->someFunction();
You will have to change all the occurrences of $this->$foo with $this->foo since you used that notation throughout the class.
As noted in the comment by #Aatch, see the docs on variable variables for further explanation. But that is what you were running into accidentally.

PHP including external files which use class fields from base file

Let's say I have a class...
class A {
private $action;
private $includes;
public function __construct($action, $file) {
//assign fields
}
public function includeFile()
include_once($this->file);
}
$a = new A('foo.process.php', 'somefile.php');
$a->includeFile();
As you can see, includeFile() calls the include from within the function, therefore once the external file is included, it should technically be inside of the function from my understanding.
After I've done that, let's look at the file included, which is somefile.php, which calls the field like so.
<form action=<?=$this->action;?> method="post" name="someForm">
<!--moar markup here-->
</form>
When I try to do this, I receive an error. Yet, in a CMS like Joomla I see this accomplished all the time. How is this possible?
Update
Here's the error I get.
Fatal error: Using $this when not in object context in /var/www/form/form.process.php on line 8
Update 2
Here's my code:
class EditForm implements ISave{
private $formName;
private $adData;
private $photoData;
private $urlData;
private $includes;
public function __construct(AdData $adData, PhotoData $photoData, UrlData $urlData, $includes) {
$this->formName = 'pageOne';
$this->adData = $adData;
$this->photoData = $photoData;
$this->urlData = $urlData;
$this->includes = $includes;
}
public function saveData() {
$this->adData->saveData();
$this->photoData->saveData();
}
public function includeFiles() {
if (is_array($this->includes)) {
foreach($this->includes as $file) {
include_once($file);
}
} else {
include_once($this->includes);
}
}
public function populateCategories($parent) {
$categories = $this->getCategories($parent);
$this->printCategories($categories);
}
public function populateCountries() {
$countries = $this->getCountries();
$this->printCountries($countries);
}
public function populateSubCategories() {
//TODO
}
private function getCategories($parent) {
$db = patentionConnect();
$query =
"SELECT * FROM `jos_adsmanager_categories`
WHERE `parent` = :parent";
$result = $db->fetchAll(
$query,
array(
new PQO(':parent', $parent)
)
);
return $result;
}
private function getCountries() {
$db = patentionConnect();
$query =
"SELECT `fieldtitle` FROM `jos_adsmanager_field_values`
WHERE fieldid = :id";
$result = $db->fetchAll(
$query,
array(
new PQO(':id', 29)
)
);
return $result;
}
private function printCountries(array $countries) {
foreach($countries as $row) {
?>
<option value=<?=$row['fieldtitle'];?> >
<?=$row['fieldtitle'];?>
</option>
<?php
}
}
private function printCategories(array $categories) {
foreach($categories as $key => $row){
?>
<option value=<?=$row['id'];?>>
<?=$row['name'];?>
</option>
<?php
}
}
}
And the include call (which exists in the same file):
$template = new EditForm(
new AdData(),
new PhotoData(),
new UrlData($Itemid),
array(
'form.php',
'form.process.php'
)
);
$template->includeFiles();
And the main file which is included...
if ($this->formName == "pageOne") {
$this->adData->addData('category', $_POST['category']);
$this->adData->addData('subcategory', $_POST['subcategory']);
} else if ($this->formName == "pageTwo") {
$this->adData->addData('ad_Website', $_POST['ad_Website']);
$this->adData->addData('ad_Patent', $_POST['ad_Patent']);
$this->adData->addData('ad_Address', $_POST['ad_Address']);
$this->adData->addData('email', $_POST['email']);
$this->adData->addData('hide_email', $_POST['hide_email']);
$this->adData->addData('ad_phone', $_POST['ad_phone']);
$this->adData->addData('ad_Protection', $_POST['ad_Protection']);
$this->adData->addData('ad_Number', $_POST['ad_Number']);
$this->adData->addData('ad_Country', $_POST['ad_Country']);
$this->adData->addData('ad_issuedate', $_POST['issuedate'] . '/' . $_POST['issuemonth'] . '/' . $_POST['issueyear']);
} else if ($this->formName == "pageThree") {
$this->adData->addData('name', $_POST['name']);
$this->adData->addData('ad_Background', $_POST['ad_Background']);
$this->adData->addData('ad_opeartion', $_POST['ad_operation']);
$this->adData->addData('ad_advlimit', $_POST['ad_advlimit']);
$this->adData->addData('ad_status', $_POST['ad_status']);
$this->adData->addData('ad_addinfo', $_POST['ad_addinfo']);
$this->adData->addData('ad_description', $_POST['ad_description']);
$this->adData->addData('tags', $_POST['tags']);
$this->adData->addData('videolink', $_POST['videolink']);
} else if ($this->formName == "pageFour") {
foreach($_POST['jos_photos'] as $photo) {
$this->photoData->addData(
array(
'title' => $photo['title'],
'url' => $photo['url'],
'ad_id' => $this->photoData->__get('ad_id'),
'userid' => $this->photoData->__get('userid')
)
);
}
}
Update
Strange: while the error itself hadn't been quite related to what the problem was, I found that it was simply an undefined field which I hadn't implemented.
Consider this thread solved. To those who replied, I certainly appreciate it regardless.
This should work. Are you sure you're doing the include from a non-static method that's part of the class (class A in your example)? Can you post the exact code you're using?
Edit: As general advice for problems like this, see if you can trim down the code so the problem is reproducible in a short, simple example that anyone could easily copy/paste to reproduce the exact error. The majority of the time, you'll figure out the answer yourself in the process of trying to simplify. And if you don't, it will make it much easier for others to help you debug.

How to create an instance of a class in another class

I might be missing something here, I'm not sure. A Google search didn't really help either.
What I'm wanting to do is call the databaseServer class and use its methods within my userControl class. Here is my lib_class.php file:
<?php
include('definitions.php');
class databaseServer {
var $con;
var $db;
var $close;
var $qry;
var $sql;
function connect($host,$user,$pw,$db) {
$this->con = mysql_connect($host,$user,$pw);
if (!$this->con) {
die('Could not connect: ' . mysql_error());
}
else {
echo "Database Connected";
}
$this->selectDb($db);
}
function selectDb($database) {
$this->db = mysql_select_db($database,$this->con);
if (!$this->db) {
echo "Could not Select database";
}
else {
echo "Database Selected";
}
}
function disconnect() {
$this->close = mysql_close($this->con);
if ($this->close) {
echo "Disconnected";
}
}
function query($test) {
if (!mysql_query($test)) {
die("Error: " . mysql_error());
}
}
} // databaseServer
class cookie {
var $expireTime;
function set($name,$value,$expiry) {
$this->expireTime = time()+60*60*24*$expiry;
setcookie($name,$value,$expireTime);
}
function delete($name) {
setcookie($name,"",time()-3600);
}
function check($name) {
if (isset($_COOKIE["$name"]))
echo "Cookie Set";
else
echo "Cookie failed";
}
} //cookie
class userControl {
public function __construct(databaseServer $server) {
$this->server = new databaseServer();
}
function createUser($uname,$pword) {
$this->server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $this->server->query("SELECT * FROM user_list WHERE uname='" . $this->server->real_escape_string($uname) . "'");
if ($this->result->num_rows() === 0) {
if ($this->server->query("INSERT INTO user_list (uname, pword)
VALUES ('" . $this->server->real_escape_string($uname) . "','" . $this->server->real_escape_string($pword) . "')") {
echo "User Added Successfully!";
}
else {
echo "Error Adding User!";
}
}
else {
echo "User Already Exists!";
}
} // createUser
} // userControl
?>
However, this isn't working and I can't see why. My databaseServer and cookie classes work fine when I omit the userControl class from the file, so I know the error must be in that class somewhere. OOP is something I'm trying to learn and I keep stumbling.
The echoes in the databaseServer class are there only for me to test it. I am implementing the classes in an index.php file as follows:
<?php
include('definitions.php');
include('class_lib.php');
$bmazed = new databaseServer();
$bmazed->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$sql = "INSERT INTO blah
VALUES ('testing 92')";
$bmazed->query($sql);
$bmazed->disconnect();
// $control = new userControl();
// $uname = "Test1";
// $pword = "test1";
// $control->createUser($uname,$pword);
echo "<br />";
echo "<br />";
?>
Lines have been commented out for testing purposes, so I don't have to keep re-writing code.
I really have no idea where the problem lies, I've checked syntax and everything seems fine.
You cannot assign class or instance properties that depend on runtime information when you declare the classes. See the chapter on Class Properties in the PHP Manual.
Change the class to read:
class userControl
{
protected $_server;
public function __construct ()
{
$this->_server = new databaseServer();
}
}
Also, to access class/instance members, you have to to use the $this keyword, e.g.
$this->_server->connect();
On a sidenote, while composition is fine, aggregation is better. It helps your code staying maintainable and loosely coupled, which means it will be much easier to replace components, for instance when writing UnitTests. So consider changing the constructor to use Dependency Injection.
Initialize $server in the constructor:
class userControl {
private $server;
function __construct() {
$this->server = new databaseServer();
}
function createUser($uname,$pword) {
$this->server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $this->server->query("SELECT * FROM user_list WHERE uname='" . $this->server->real_escape_string($uname) . "'");
if ($this->result->num_rows() === 0) {
if ($this->server->query("INSERT INTO user_list (uname, pword) VALUES ( '" . $this->server->real_escape_string($uname) . "','" . $this->server->real_escape_string($pword) . "')") {
echo "User added Succesfully";
}
else {
echo "Error Adding User";
}
else {
echo "User already exists";
}
}
}
For one, $server won't be accessible from within createUser() because it's in a different scope. PHP scope works a bit differently than one would expect from a C-style language.
Try either passing the $server to createUser(), or initializing the server in createUser(), in which case you should probably have a getServer() function so that you're not initializing it needlessly.
The third option is by far the worst, which is doing "global $server" at the top, inside the function. But it's very bad practice. You have been warned.
Last but not least, you should probably look for COUNT(*) than * in the SQL query, because otherwise you're selecting all the users. :)
If you want further information on PHP's scope, see here (highly recommended):
http://php.net/manual/en/language.variables.scope.php
Hope it helps!
The syntactical stuff certainly was a problem. But even more fundamentally wrong with my code was the fact that the databaseServer->query method doesn't return a value. Making it return a value fixed the problem.
I think, sometimes, it's not possible to see the wood for the trees. :)

Categories