PHP - Help Writing My 1st Php Class
Hi everyone. Still new to PHP and to Object-Oriented Programming.
My goal for today is to write a few dummy Classes in PHP that do enough so that I can see something on my webpage. I am wondering if there is someone here who would be willing to help in either the forums or one-on-one. It may sound like a silly request, but this is all new to me as a Procedural Programmer who has actively programmed in about 10 years!! Thanks, TomTees Similar Tutorialsi made a little uploader class, its not refined but it works, here is the class <?php /* This is a simple file uploader class created by me: Hugo Johnson website: www.jwmstudios.com email: hugoj@hotmail.com Its my first real shot at creating a php class, i am still a todler to this. */ Class Uploader { // Declaring my variables needed for this class, it makes sense. public $input_field_name = "userfile"; // default input field name public $file_size =300000; // default file size public $path_directory = ""; // location to send the file public $action_path_and_file = "uploader.php"; // default form action function form() { // This form is optional used if no form is provided, only good for one file echo <<<END <form enctype="multipart/form-data" method="post" action="$this->action_path_and_file "> <input name="$this->input_field_name" type="file" /><br /><input type="hidden" name="max_size" value="$this->file_size" /> <input type="submit" value="Upload" /> </form> END; } function file_field($field_name) { // optional for adding more than one file echo "<br /><input name=\"$field_name\" type=\"file\" /><br />"; } function upload($input_field_name) { // this will upload a file that coresponds to a field name of type file $filename = $_FILES[$input_field_name]['name']; // coming from the form $filesize = $_FILES[$input_field_name]['size']; // " " $temp = $_FILES[$input_field_name]['tmp_name']; // " " // move Uploaded File function places the file from its temp directory and puts it into the desired directory, $path = $this->path_directory.$filename; // you can type a path directory structure between the quotes eg. ../ or /filestorage etc. $uploadfile = move_uploaded_file($temp, $path); // moving file from temp location to new chosen path echo $uploadfile === TRUE ? '<br />File uploaded<br />' : '<br />Awaiting File Upload<br />'; } } ?> Save the file as uploader_bk.php Here is the test form: <?php // This is the test upload form include_once("uploader_bk.php"); // importing the Uploader class $myupload = new Uploader(); // declaring a new uploader object $myupload->file_size = 400000; // setting a different file size $myupload->path_directory = "myfiles/"; // You can mod the path directory at any time, leave blank if is on the same path as the script $myupload->action_path_and_file = $_SERVER['PHP_SELF']; // use $_SERVER['PHP_SELF'] if its the same script that is doing the processing $fieldname = array("joe", "Mary"); // This can apply to one file you may need to prefix variable names to add more fields; this could also be an include $max_fields = count($fieldname); // getting the maximum number of fields that you need echo "<br />"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Handling File Uploads</title> </head> <body> <form enctype="multipart/form-data" method="post" action="<?php echo $myupload->action_path_and_file; ?>"> <?php for ($i=0 ; $i < $max_fields; $i++) { $myupload->file_field($fieldname[$i]); // input field. $myupload->upload($fieldname[$i]); // The uploading process. } ?> <input type="submit" value="Send File" /> </form> </body> </html> I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Hi Can you call Class A's methods or properties from Class B's methods? Thanks. I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. I have two classes: ## Admin.php <?php class Admin { public function __construct() { include("Config.php"); } /** * deletes a client * @returns true or false */ function deleteClient($id) { return mysql_query("DELETE FROM usernames WHERE id = '$id'"); } } ?> ## Projects.php <?php class Projects { public function __construct() { include("Config.php"); $this->admin = $admin; $this->dataFolder = $dataFolder; } /** * Deletes a project * @returns true or false */ function deleteProject($id) { $root = $_SERVER['DOCUMENT_ROOT']; $theDir = $root . $this->dataFolder; $sql = mysql_query("SELECT * FROM projectData WHERE proj_id = '$id'"); while ($row = mysql_fetch_array($sql)) { $mainFile = $row['path']; $thumb = $row['thumbnail']; if ($thumb != 'null') { unlink($theDir . "/" . substr($thumb,13)); } unlink($theDir . "/" . substr($mainFile,13)); } $delete = mysql_query("DELETE FROM projectData WHERE proj_id = '$id'"); $getDir = mysql_query("SELECT proj_path FROM projects WHERE id = '$id'"); $res = mysql_fetch_array($getDir); rmdir($theDir . "/" . $res['proj_path']); return mysql_query("DELETE FROM projects WHERE id = '$id'"); } } ?> How can I call deleteProject() from within Admin.php? Hi people! class FirstOne{ public function FunctionOne($FirstInput){ //do stuff and output value return $value1; } } Then:- class SecondOne{ public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } } What I want to know is this, if I want to use FunctionOne() in Class SecondOne do I do it like this:- (Assume as I have instantiated the first class using $Test = new FirstOne(); ) class SecondOne{ function SecondedFunction(){ global $Test; return $Test->FunctionOne(); } public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } public function FunctionThree(){ //some code here $this->Test->SecondedFunction();<--I think as I can omit the $this-> reference } } My point is: Do I have to do it this way or is there way of having this done through __construct() that would negate the need for a third party function? I have a version working, I just think that it is a little convoluted in the way as I have done it, so I thought I would ask you guys. Any help/advice is appreciated. Cheers Rw I do know how to do this but I am curious about whether or not there is a "preferred" way to do this. I know there are a couple ways to use a class (I'll call Alpha_Class) within another class (I'll class Beta_Class) Let's say we have this simple class (Beta_Class): class beta { function foo(){ } } If I wanted to use the Alpha Class within the Beta Class, I could any number of things. For example: class beta { function foo(){ $this->alpha = new alpha; //$this->alpha->bar(); } } Or you could simply use the $GLOBALS array to store instantiated objects in: $GLOBALS['alpha'] = new alpha; class beta { function foo(){ //GLOBALS['alpha']->bar(); } } You could even declare Alpha_Class as a static class and thus would not need to be instantiated: static class alpha { static function bar(){} } class beta { function foo(){ //alpha::bar(); } } Those are the only ways I can think of right now. Are there any other ways to accomplish this? I was wondering which way is the best in terms of readability and maintainability. I have a class in which I have a function called connection. I am now trying to call this function from another class, but it will not work. It works if I put the code in from the other function rather than calling it but that defeats the purpous. class locationbox { function location() { $databaseconnect = new databaseconnect(); $databaseconnect -> connection();{ $result = mysql_query("SELECT * FROM locations"); while($row = mysql_fetch_array($result)) // line that now gets the error, mysql_fetch_array() expects parameter 1 to be resource, boolean given //in { echo "<option>" . $row['location'] . "</option>"; } } }} Hi all, I have two classes. Registration and Connection. Inside a registration.php I include my header.php, which then includes my connection.php... So all the classes should be declared when the page is loaded. This is my code: registration.php: <?php include ('assets/header.php'); ?> <?php class registration{ public $fields = array("username", "email", "password"); public $data = array(); public $table = "users"; public $dateTime = ""; public $datePos = 0; public $dateEntryName = "date"; function timeStamp(){ return($this->dateTime = date("Y-m-d H:i:s")); } function insertRow($data, $table){ foreach($this->fields as $key => $value){ mysql_query("INSERT INTO graphs ($this->fields) VALUES ('$data[$key]')"); } mysql_close($connection->connect); } function validateFields(){ $connection = new connection(); $connection->connect(); foreach($this->fields as $key => $value){ array_push($this->data, $_POST[$this->fields[$key]]); } $this->dateTime = $this->timeStamp(); array_unshift($this->data, $this->dateTime); array_unshift($this->fields, $this->dateEntryName); foreach($this->data as $value){ echo "$value"; } $this->insertRow($this->data, $this->table); } } $registration = new registration(); $registration->validateFields(); ?> <?php include ('assets/footer.php'); ?> At this point I cannot find my connection class defined on another included/included page. $connection = new connection(); $connection->connect; config.php (included within header.php) <? class connection{ public $dbname = '**'; public $dbHost = '**'; public $dbUser = '**'; public $dbPass = '**'; public $connect; function connect(){ $this->connect = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die ('Error connecting to mysql'); mysql_select_db($this->dbname, $this->connect); } } ?> Any ideas how to call it properly? How does one go about using one class inside another? For example, building a class that does some series of functions, and uses a db abstraction layer class in the process? I don't think the start of my code is right?! Code: [Select] echo '<button onclick=\"gohere(viewpub.php?PubID='.$row['PubID'].')" id="button" type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">View Pub</span></button>'; Please help?! I need help! I cant get this to write the correct way! What i need is based on the value of what is posted to the script it has to write it in the config file and also make a folder! Please help Code: [Select] <?php $start = '$uploadpath=\''; $structure = '../banner/images/'.$_POST['FOLDER'].'\';\n'; $myFile = "PHP/confup.php"; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "<?\n"; fwrite($fh, $stringData); $stringData = "$start $structure"; fwrite($fh, $stringData); $stringData = "?>\n"; fwrite($fh, $stringData); fclose($fh); // Desired folder structure // To create the nested structure, the $recursive parameter // to mkdir() must be specified. if (!mkdir($structure, 0777, true)) { die('Failed to create folders...'); } // ... ?> im trying to make a program that changes some files from 0 to 1,but im having some trouble... heres my code, Code: [Select] $id = $_GET["id"]; $file1 = "http://mysite.co.cc/users/".$id."/file1.txt"; $fh = fopen($file1, 'w'); fwrite($fh, "1"); fclose($fh); I followed this tut: http://www.tizag.com/phpT/filewrite.php I cant find anything wrong with the code,but it will not make the file have 1 in it. Hey Guys. I am trying to write to the file depending on which condition is met. The code works fine on my local machiene but not on my remote server. I have also tried to output any error messages to see if it would output anything, and I don't get anyting on my browser. Can anyone help me with this issue? Thanks <?php if($_SERVER['REQUEST_METHOD'] == "POST") { isset($_POST['interfax']) ? $option= "interfax" : $option= ""; isset($_POST['metrofax']) ? $option= "metrofax" : $option= ""; switch ($option) { case 'interfax': $file = "fax.php"; $fax_client = "interfax"; if(file_put_contents($file, "<?php ".'$fax_client = "' . $fax_client . '"'." ?>")) { echo "Successful"; } else { die("Can't write file"); } break; // By defualt all the orders go to metrofax so by selecting the variable it resets it self case 'metrofax': $file = "fax.php"; $fax_client = "metrofax"; file_put_contents($file, "<?php ".'$fax_client = "' . NULL . '"'." ?>"); break; } } ?> <form action="#" method="POST"> <input type="radio" name="interfax" value="interfax">Switch To Interfax<br> <input type="radio" name="metrofax" value="metrofax">Switch To Metrofax<br> <input type='submit' name="submit" > I am using a script I adapted from a tutorial to print the contents of a text box to a txt file. Basically, it's a really simple way of seeing who has logged in. I only have a handful of users. The problem is, although the text file is being created in the proper folder, it isn't being written to and just remains blank. <div align="center"> <table width="300" border="2" bordercolor="#FFFFFF" style="-moz-border-radius: 18px; -webkit-border-radius: 18px;" height="120" cellpadding="0" cellspacing="0"> <tr> <form name="form1" method="post" action="checklogin.php"> <td> <table width="100%" border="0" cellpadding="3" cellspacing="1" background="images/loginbg.jpg" style="-moz-border-radius: 15px; -webkit-border-radius: 15px;"> <tr align="center"> <td colspan="3"><font color="#FFFFFF"><strong>Family Login </strong></font></td> </tr> <tr> <td width="78"><font color="#000000">Username</font></td> <td width="6">:</td> <td width="294"><input name="myusername" type="text" id="myusername"> <?php $myusername = $_POST['myusername']; $data = "$myusername\n"; //open the file and choose the mode $fh = fopen("logs/login.txt", "a"); fwrite($fh, $data); fclose($fh); ?></td> </tr> <tr> <td><font color="#000000">Password</font></td> <td>:</td> <td><input name="mypassword" type="password" id="mypassword"></td> </tr> <tr> <td> </td> <td> </td> <td><input type="submit" name="Submit" value="Login"> </td> </tr> </table> </td> </form> </tr> </table> </div> I'm not sure what's going wrong but I'm guessing it's the placing of the php, or at least some of it. I'd quite like to add the time they logged in as well. Any idea's anyone? I have a web app hosted on Just Host that I have nearly finished writing but still needs to have coded the ability to write a text file to user's computer. the user should be able to specify where on their computer they would like the file to be stored. Is this possible ? And can you tell me how it's done, or point me to a souce that can tell me I rarely ever ask for help regarding programming, but this has flumoxed me. If it is not possible to do this, then would I have to generate this file on the Host's server (Just Host in my case), then download it ? If this can be done then can you please tell me how, as any info I have found related to file downloads seems a bit obscure thanks in advance I have written some code to past information from one page to a diffrent page however all the variables are sent over but they are not writting to the database could anyone help me out please .... $ud_P_Id = $_POST['ud_P_Id']; $ud_LastName = $_POST['ud_LastName']; $ud_FirstName = $_POST['ud_FirstName']; $ud_GroupCode=$_POST['ud_GroupCode']; $ud_P_Unit1=$_POST['ud_P_Unit1']; $ud_P_Unit2=$_POST['ud_P_Unit2']; $ud_P_Unit3=$_POST['ud_P_Unit3']; $ud_P_Unit6=$_POST['ud_P_Unit6']; $ud_P_Unit14=$_POST['ud_P_Unit14']; $ud_P_Unit20=$_POST['ud_P_Unit20']; $ud_P_Unit27=$_POST['ud_P_Unit27']; $ud_P_Unit28=$_POST['ud_P_Unit28']; $ud_P_Unit42=$_POST['ud_P_Unit42']; $ud_P_Unit10=$_POST['ud_P_Unit10']; $ud_P_Unit11=$_POST['ud_P_Unit11']; $ud_P_Unit12=$_POST['ud_P_Unit12']; $ud_P_Unit13=$_POST['ud_P_Unit13']; $ud_P_Unit1454=$_POST['ud_P_Unit1454']; $ud_P_Unit15=$_POST['ud_P_Unit15']; $ud_P_Unit16=$_POST['ud_P_Unit16']; $ud_P_Unit17=$_POST['ud_P_Unit17']; $ud_P_Unit18=$_POST['ud_P_Unit18']; $con = mysql_connect('localhost', 'lccstude_progre', '********'); $db= "lccstude_pro"; if (! $con) die("Couldn't connect to MySQL"); mysql_select_db($db , $con) or die("Couldn't open $db: ".mysql_error()); mysql_query("UPDATE BTECL31113 SET FirstName='$ud_FirstName' , LastName='$ud_LastName' , GroupCode='$ud_GroupCode' , Unit1='$ud_P_Unit1' , Unit2='$ud_P_Unit2' , Unit3='$ud_P_Unit3' , Unit6='$ud_P_Unit6' , Unit14='$ud_P_Unit14' , Unit20='$ud_P_Unit20' , Unit27='$ud_P_Unit27' , Unit28='$ud_P_Unit28' , Unit42='$ud_P_Unit42' , Unit10='$ud_P_Unit10' , Unit11='$ud_P_Unit11' , Unit12='$ud_P_Unit12' , Unit13='$ud_P_Unit13' , Unit1454='$ud_P_Unit1454' , Unit15='$ud_P_Unit15' , Unit16= $ud_P_Unit16' , Unit17='$ud_P_Unit17' , Unit18='$ud_P_Unit18' WHERE P_Id='$ud_P_Id'"); echo "Record Updated"; mysql_close($con); Please any help would be great |