PHP - Php Forms / Php Form Builder Class
Hi guys,
I'm having a bit of PHP problems trying to combine two bits of code which is definitely possible as it's simple if statements, but I'm a bit confused. Not sure if you guys are familiar, but there's a PHP Form Builder Class part of the Google Code Hosting Project. There's two forms I'm playing with one 'Google Spreadsheets' form which allows the data submitted via a form to be entered in a Google Spreadsheet, and one which sends the data to an email address. http://www.imavex.com/php-form-builder-class/examples/email.php http://www.imavex.com/php-form-builder-class/examples/google-spreadsheets.php I have these working separately, but ideally want I need is to be able to combine them both, per se, and allow the data submitted to go to both the spreadsheet and the email address defined. The code for the email is: Code: [Select] <?php error_reporting(E_ALL); session_start(); include("../class.form.php"); if(isset($_POST["cmd"]) && in_array($_POST["cmd"], array("submit_0"))) { $form = new form("email_" . substr($_POST["cmd"], -1)); if($form->validate()) { $result = $form->email("my_username", "my_password", array( "to" => "my_recipient(s)", "subject" => "my_subject", "from" => "my_from", "replyto" => "replyto", "cc" => "my_cc", "bcc" => "my_bcc", "preHTML" => "my_prehtml", "postHTML" => "my_posthtml", "css" => '<style type="text/css">...</style>', "cssFile" => "my_css.css or http://www.my_domain.com/my_css.css", "textonly" => "true/false" )); if($result) header("Location: email.php?errormsg_" . substr($_POST["cmd"], -1) . "=" . urlencode("Congratulations! The information you enter has been emailed from your Google Gmail account.")); else header("Location: email.php?errormsg_" . substr($_POST["cmd"], -1) . "=" . urlencode("Oops! The following error has occurred while sending information from your Google Gmail account. " . $form->getEmailError())); } else header("Location: email.php"); exit(); } elseif(!isset($_GET["cmd"]) && !isset($_POST["cmd"])) { $title = "Email w/PHPMailer + Google's Gmail Service"; include("../header.php"); ?> <p><b>Email w/Google's Gmail Service</b> - This project's email function provides the ability to email a form's submitted data using PHPMailer and Google's Gmail service. This function has four parameters as seen below.</p> <ul style="margin: 0;"> <li>Google Account Email Address - Email address (including domain) of your Google Gmail account.</li> <li>Google Account Password - Password of your Google Gmail account.</li> <li>Additional Parameters (optional) - This parameter allows you to set various email settings through an associative array of key/value pairs. Available settings are provided below. <ul style="margin: 0;"> <li>to - Sets the email's to address. If blank, this parameter will be set to the Google Gmail account email address used in the first parameter.</li> <li>subject - Sets the email's subject.</li> <li>from - Sets the email's from address. If blank, this parameter will be set to the Google Gmail account email address used in the first parameter.</li> <li>replyto - Sets the email's reply to address. If empty, the from address will be used.</li> <li>cc - Sets the email's CC address.</li> <li>bcc - Sets the email's BCC address.</li> <li>preHTML - Allows you to prepend html content above the form's submitted data.</li> <li>postHTML - Allows you to append html content below the form's submitted data.</li> <li>textonly - Sends text-only version of the form's submitted data. By default, the email function will send an email containing both an html and text version.</li> <li>css - Gives you the ability to style the html email as needed. This parameter should be passed as a string beginning with <style type="text/css"> and ending with </style></li> <li>cssFile - Gives you the ability to style the html email as needed by specifying a css include file.</li> </ul> </li> </ul> <p>Before getting started, you'll want to review the checklist of information provided below to ensure you have a good understanding on how this functionality works.</p> <ol style="margin: 0;"> <li>You'll need a Google Gmail account. If you don't have one, you can create one by clicking the "Create an account" link at <a href="http://mail.google.com">http://mail.google.com</a>.</li> <li>to, replyto, cc, and bcc can contain multiple email addresses - just separate them with commas.</li> <li>to, from, replyto, cc, bcc can contain email addresses formatted as either "my@email.com" or "My Email <my@email.com>"</li> <li>Within the email function, a call is made to another public function - getEmail - to get the email's html/text content. If you already have an existing system in place for sending email, you can use this function instead of the project's email function to build a string containing an html/text representation of the form's submitted data. By default, this function will return html, but you can pass true as the first and only parameter to return text.</li> </ol> <p>In the php source code of this example file, you'll see that the email function call currently contains demo authentication/email settings ("my_email", "my_password", etc). You'll want to replace these with your information. Another important thing to note is that the various email settings that can be applied through the email function's fourth parameter are optional. In the php source code of this example file, you'll find all of them listed for reference in the email function call. Feel free to include as many or few as needed.</p> <?php $form = new form("email_0"); $form->setAttributes(array( "map" => array(2, 2, 1, 3), "width" => 500 )); if(!empty($_GET["errormsg_0"])) $form->errorMsg = filter_var(stripslashes($_GET["errormsg_0"]), FILTER_SANITIZE_SPECIAL_CHARS); $form->addHidden("cmd", "submit_0"); $form->addTextbox("First Name:", "FName"); $form->addTextbox("Last Name:", "LName"); $form->addEmail("Email Address:", "Email"); $form->addTextbox("Phone Number:", "Phone"); $form->addTextbox("Address:", "Address"); $form->addTextbox("City:", "City"); $form->addState("State:", "State"); $form->addTextbox("Zip Code:", "Zip"); $form->addButton(); $form->render(); include("../footer.php"); } ?> And for the spreadsheet: Code: [Select] <?php error_reporting(E_ALL); session_start(); include("../class.form.php"); if(isset($_POST["cmd"]) && in_array($_POST["cmd"], array("submit_0"))) { $form = new form("googlespreadsheets_" . substr($_POST["cmd"], -1)); if($form->validate()) { if($form->sendToGoogleSpreadsheet("my_email", "my_password", "my_spreadsheet_title", "(optional) my_worksheet_title")) header("Location: google-spreadsheets.php?errormsg_" . substr($_POST["cmd"], -1) . "=" . urlencode("Congratulations! The information you enter has been sent your Google Docs spreadsheet.")); else header("Location: google-spreadsheets.php?errormsg_" . substr($_POST["cmd"], -1) . "=" . urlencode("Oops! The following error has occurred while sending information to your Google Docs spreadsheet. " . $form->getGoogleSpreadsheetError())); } else header("Location: google-spreadsheets.php"); exit(); } elseif(!isset($_GET["cmd"]) && !isset($_POST["cmd"])) { $title = "Google Spreadsheets"; include("../header.php"); ?> <p><b>Google Spreadsheets</b> - This project's sendToGoogleSpreadsheet function provides the ability to send a form's submitted data direclty to a Google Docs spreadsheet using the Google Spreadsheet API. This function has four parameters as seen below.</p> <ul style="margin: 0;"> <li>Google Account Email Address - Email address (including domain) of your Google account.</li> <li>Google Account Password - Password of your Google account.</li> <li>Google Docs Spreadsheet - The title of the spreadsheet where you'd like the form's submitted data to be sent.</li> <li>Worksheet (optional) - The title of the worksheet to be used within the specified spreadsheet. This parameter will default to the the spreadsheet's first worksheet.</li> </ul> <p>Before getting started, you'll want to review the checklist of information provided below to ensure you have a good understanding on how this functionality works.</p> <ol style="margin: 0;"> <li>You'll need a Google account. If you don't have one, you can create one by clicking the "Create an account now" link at <a href="http://docs.google.com">http://docs.google.com</a>.</li> <li>If the spreadsheet title you specify in the sendToGoogleSpreadsheet function does not exist, a new spreadsheet will be created for you with the appropriate title and column headers.</li> <li>If you're creating your spreadsheet manually through the Google Docs GUI, an important thing to keep in mind is that Google will treat the initial row of cells as column identifiers. These column identifiers must match an element's label used in your form ("First Name:", "Last Name:", etc), which enables the form's submitted data to be correctly placed within the appropriate column. If the spreadsheet you specify in the sendToGoogleSpreadsheet function exists but has no inital row of column headers, your form's data will not populated upon submission. Your spreadsheet does not need to contain a column for every element used in the form - data for those elements that are not included will just not be collected. Likewise, your spreadsheet can contain column identifiers that don't match an element's label used in the form - data for those columns will be left blank.</li> <li>Elements of type hidden, captcha, button, html, and htmlexternal will not be included in the information that is sent to your Google spreadsheet.</li> <li>The "ignoreGSSend" element attribute can be applied to form elements that you do not want to be send to your Google Docs spreadsheet. The hidden field "cmd" has this attribute set in the form below.</li> <li>If you're populating an existing spreadsheet in your Google Docs account, you can store the web server's date/time at the moment the form's data is submitted by adding "Timestamp" as a column header.</li> </ol> <p>In the php source code of this example file, you'll see that the sendToGoogleSpreadsheet function call currently contains demo authentication/spreadshet settings ("my_email", "my_password", etc). You'll want to replace these with your information.</p> <?php $form = new form("googlespreadsheets_0"); $form->setAttributes(array( "map" => array(2, 2, 1, 3), "width" => 500 )); if(!empty($_GET["errormsg_0"])) $form->errorMsg = filter_var(stripslashes($_GET["errormsg_0"]), FILTER_SANITIZE_SPECIAL_CHARS); $form->addHidden("cmd", "submit_0"); $form->addTextbox("First Name:", "FName"); $form->addTextbox("Last Name:", "LName"); $form->addEmail("Email Address:", "Email"); $form->addTextbox("Phone Number:", "Phone"); $form->addTextbox("Address:", "Address"); $form->addTextbox("City:", "City"); $form->addState("State:", "State"); $form->addTextbox("Zip Code:", "Zip"); $form->addButton(); $form->render(); include("../footer.php"); } ?> I have managed to speak to one of the admins, who can't help me further, but states: 'My recommendation would be to use both the $form->email() and $form->sendToGoogleSpreadsheet() methods after your form has been submitted. It's not a "one or the other" type of scenario.' Could you help me out and show me how this would be possible which in turn I can learn from? Thanks, and sorry for the long post but felt it was better as a code include rather than an attachment? Richard Similar TutorialsI am setting up a site that is using MODx 2.2 Revolution. I had been using ValidForm Builder as my contact form generator and have used it for a while and really like it. One of the things I liked about MODx is that I was not tied to strictly using their plugins and so forth and that its generally pretty easy to integrate php code into the site via what they call snippets. Anyway, Im sure many here are familiar with MODx. However, the issue I am having is getting ValidForm to work in MODx. When you make a 'snippet' in MODx, it has to have a return. I have posted the code for a sample form below from the ValidForm Builder website. I created a snippet and added the below code to it to test things out. Knowing that the snipped had to have a return, I tried return ($strOutput);. That generates the form on the page, but it doesnt actuall process and send the form. The validation all works, but nothing else. So Im not sure if Im doing things wrong or what. On static pages you simply use: Code: [Select] <?php echo $strOutput; ?> If I do that only, the form doesnt show up. So ultimately I guess Im trying to figure out how one would write a 'return' into the code so that it works. I tried putting the return after the closing bracket, but Im not sure that is the correct way to do it. Does anyone have any ideas or input? I know MODx has the FormIt extension, but I really like ValidForm and would love to get it to work since, at least on static pages, it is easy to work with and set up. I need to redirect, back to the home page, after the form is submitted, but MODx handles that a little differently and I will have to figure that out after I get the form working. Thanks in advance for any help. Code: [Select] <?php //*** Include the library. require_once("libraries/ValidForm/class.validform.php"); //*** Create an instance of the form. $objForm = new ValidForm("contactForm", "Required fields are printed in bold."); //*** Add the Name field. $objForm->addField("name", "Your name", VFORM_STRING, array( "maxLength" => 255, "required" => TRUE ), array( "maxLength" => "Your input is too long. A maximum of %s characters is OK.", "required" => "This field is required.", "type" => "Enter only letters and spaces." ) ); //*** Add the Email field. $objForm->addField("email", "Email address", VFORM_EMAIL, array( "maxLength" => 255, "required" => TRUE ), array( "maxLength" => "Your input is too long. A maximum of %s characters is OK.", "required" => "This field is required.", "type" => "Use the format name@domain.com" ), array( "tip" => "name@domain.com" ) ); //*** Add the Remarks field. $objForm->addField("remarks", "Remarks", VFORM_TEXT, array( "maxLength" => 2000 ), array( "maxLength" => "Your input is too long. A maximum of %s characters is OK.", "type" => "Enter only characters, punctuation, numbers and spaces" ) ); //*** Set the general alert. $objForm->setMainAlert("One or more errors occurred. Check the marked fields and try again."); //*** Set the label of the submit button. $objForm->setSubmitLabel("Send"); //*** Default output. $strOutput = ""; //*** Check the form. if ($objForm->isSubmitted() && $objForm->isValid()) { //*** HTML body of the email. $strMessage = "<html><head><title></title></head><body>"; $strMessage .= $objForm->valuesAsHtml(); $strMessage .= "</body></html>"; //*** Mail headers. $strHeaders = "MIME-Version: 1.0\r\n"; $strHeaders .= "Content-type: text/html; charset=utf-8\r\n"; $strHeaders .= "From: Awesome website <form@awesomesite.com>\r\n"; //*** Send the email. mail("owner@awesomesite.com", "Contact form submitted", $strMessage, $strHeaders); //*** Set the output to a friendly thank you note. $strOutput = "Thank you for your interest. We will contact you as soon as possible."; } else { //*** The form has not been submitted or is not valid. $strOutput = $objForm->toHtml(); } ?> Have you guys ever build a smart queries for users too generate reports basically on anything they may want. I am looking on making something very user friendly. I do not have any ideas where to start
In attachment is the code I generated from Flex Builder: My issue is that the UTF8 (coding of the MySQL database) isn't correctly interpreted, the solution is to use : $stmt = mysqli_prepare($this->connection, "SET NAMES UTF8;"); But I don't know how to enter it in this syntax? It is I think the: $stmt = mysqli_prepare($this->connection, "SELECT * from $this->tablename"); that has to be modified, but how? Really searching a long time on the correct syntax, but without any result... Please help, thanks a lot Wimmerke Which one is better for standards practices in PHP. 1. Using the same form for everything. (Add and edit). Meaning setting up one form to handle adding new records, as well as editing existing records. Or 2. Using two different forms for both actions. Use one form/area to handle Adding, and one form/area to handle editing. Which one of these are better from a standards/practice point of a view. Which one better fits into the MVC platform (a framework like Codeignitor, or Cake). Should their be separate controller functions/views for add and edit or should they all be in the same controller function/form. Thanks for the feedback. I have two (2) forms on the same pages, each with 3 buttons. When a button is clicked, it will include the desired page. Since I have 2 of these forms, clicking one of them will refresh the page thus "delete" the info former retrieved from the other form. Is there a way to make the page "remember" the last form action? I am creating a user inbox system. I am retrieving all the unread messages. Each message row contains a "reply" form. So say I have 10 messages showing on a single page. That's 10 forms. What I would like to know is how can I submit any one of the 10 forms and not have it affect the remaining 9 forms? Here is the basic code. if(isset($_POST['submit'])) { $post_message = trim($_POST['message']); $errors = array(); $db->beginTransaction(); if(empty($post_message)) { $errors[] = 'The message field can not be empty!'; } if(empty($errors)) { $db->commit(); echo 'success'; } else { $db->rollBack(); } } <form action="" method="post"> <fieldset> <textarea name="message" maxlength="10000" placeholder="What would you like to say?"></textarea> </fieldset> <fieldset> <input type="submit" name="submit" value="Submit" /> </fieldset> </form>
Hi Guys, I am attempting to create a program for a local auction house. I arrived at a stand still on a certain issue which is creating a sticky form. On the "enter auction details page" the user will be entering data as the auction is in session. 1. item Description 2. Item Price 3. Bidders Id 4. Qty Of course it would be repetitive to require the user to keep entering the same data for every bidder, so I want to stick the obvious fields which are "item description" & "Item Price" as these don't change until a new item comes up for sale. As of know I am processing the input on a separate page which records all input to the database with a redirect back to the "enter auction details page". I have tried many times to get the item description and item price fields to stick. These would need to change as the user moves onto the next item in which the description and price would change as well. Here is my current code for this part: Code: [Select] <?php session_start(); $field_itemDescription = ""; //iyem description, default as blank if (isset($_SESSION['itemDescription'])) $itemDescription = $_SESSION['itemDescription']; ?> <form action="record_trans.php" method="post"> <font face= "calibri" size= "4"> <table> <tr> <td><b>Item Description:</b></td> <td><input type= "text" name= "itemDescription" size= "30" value="<?php echo $itemDescription;?>"></td> </tr> <tr> <td><b>Item Price:</b></td> <td><input type= "text" name= "itemPrice" size= "5" value="<?php echo $itemPrice;?>"> </td> </tr> </tr> <td><b>Winning Bidders:</b></td> <td><input type="text" name= "bidderId" size= "5" /> </td> </tr> <tr> <td><b>How many deals?:</b></td> <td><input type="text" name= "itemQty" size= "3" value= "1" /></td> </tr> </table> <center><input type="submit" name="submit" value= "Save & Cont." " /></center> </form></font> hey guys ive been trying to design this form validation class for my framework but im having a problem with the line Code: [Select] public static function is_valid($method = $_POST) if anyone can help please Code: [Select] <?php class Form extends Form_Exception { protected $_fields = array(); protected $_validation_messages = array(); protected $_form_errors = 0; public function add_validation($field_name, $valiidation_type, $validation_message = null) { $this->_fields[$field_name]['name'] = $field_name; $this->_fields[$field_name]['validation_type'] = $validation_type; $this->_fields[$field_name]['validation_message'] = $validation_message; } public static function is_valid($method = $_POST) { $fields = $this->_fields; foreach ($fields as $field) { $field_value = $method[$field['name']]; $validation_type = $field['validation_type']; $validation_message = $field['validation_message']; $validation = $validation_type. '_validation'; if ($this->$validation($field_value)) { $this->set_validation_message($validation_message); } } $validation_messages_count = count(get_validation_messages()); $this->set_form_errors($validation_messages_count); } public static function display_errors() { $validation_messages = $this->_validation_message; foreach ($validation_messages as $validation_message) { echo $validation_message; } } protected function set_validation_message($validation_message) { $this->_validation_messages[] = $validation_message return $this; } protected function set_form_errors($form_errors) { $this->_form_errors = $form_errors return $this; } protected function get_fields() { return $this->_fields; } protected function get_validation_messages() { return $this->_validation_messages; } } I am doing some practice with classes. MY class below echoes out input and radio fields based on the instantiation of the Form class (the code below is working!), but I am trying to resolve how to get my form radio fields so they are not in between every other form field as they are supposed to be next to eachother. If you run the below, you will see what I mean. And also is my approach at all sensible? I am only doing this for learning experience, so any advice please. <?php class Form { private $fields = array(); private $radios = array(); private $actionValue; private $submit = "Submit Form"; private $Nradios = 0; private $Nfields = 0; function __construct($actionValue, $submit) { $this->actionValue = $actionValue; $this->submit = $submit; } function displayForm() { echo "<form action='{$this->actionValue}' method='post'>\n\n"; for ($j = 1, $i = 1; $j <= sizeof($this->fields), $i <= sizeof($this->radios); $j++, $i++) { echo "<p>\n<label>{$this->fields[$j-1]['label']} : </label>\n"; echo "<input type='text' name='{$this->fields[$j-1]['name']}'>\n</p>\n\n"; echo "<p>\n<label>{$this->radios[$i-1]['rlabel']} : </label>\n"; echo "\n<input type='radio' name='{$this->radios[$i-1]['rname']}' value='{$this->radios[$i-1]['rvalue']}'>\n</p>\n\n"; } echo "\n\n<input type='submit' value='{$this->submit}'>\n</form>"; } function addField($name, $label) { $this->fields[$this->Nfields]['name'] = $name; $this->fields[$this->Nfields]['label'] = $label; $this->Nfields = $this->Nfields + 1; } function addRadio($rname, $rvalue, $rlabel) { $this->radios[$this->Nradios]['rname'] = $rname; $this->radios[$this->Nradios]['rvalue'] = $rvalue; $this->radios[$this->Nradios]['rlabel'] = $rlabel; $this->Nradios = $this->Nradios + 1; } } ?> <?php $contact_form = new Form("process.php", "Submit Data >>"); $contact_form->addField("first_name", "First Name"); $contact_form->addField("last_name", "Last Name"); $contact_form->addRadio("gender", "male", "Male"); $contact_form->addRadio("gender", "femail", "Female"); $contact_form->displayForm(); ?> Hi I am in the process of converting to Object Oriented from Procedural. To cater for this I have built an admin_login function, contained within a class: 'siteFunctions'. However, I am having trouble pointing the admin form to the function correctly. Every time I click 'submit', the form does not process anything. It doesn't even 'think' about it i.e. show the egg timer.... I have built this script heaps of times using the procedural method, so I guess I am somehow doing something wrong with respect to referencing the action attribute of the form (due to my new approach). I am very new to OO so please go easy on me: I know the script isn't particularly advanced. I just want to get used to putting functions into classes, and then calling the code, before I move onto more advanced stuff. I have placed all of the files within the same folder in order to rule out driectory path issues. Here are the three scripts that I think are relevant (login, functionsClass, and the mysql connection script): Login $pageTitle = "Admin Login"; include("admin_header.php"); include_once("sitefunctions.php"); new siteFunctions(); echo '<div class="admin_main_body">'; <form action="<?php echo htmlentities($_SERVER["PHP_SELF"]);?>" method='post'> <input type="text" name="username" id="username" size="20"> <label>Username</label><br /> <input type="password" name="password" id="password" size="20"> <label>Password</label><br /> <input type="submit" name="submit" id="submit" value="submit"> </form> echo '<div>'; include("includes/admin_footer.php"); sitefunctions.php //$page = "admin_index.php"; class siteFunctions { var $message; function admin_login() { echo '<div class="admin_main_body">'; $message = NULL; if (isset($_POST['submit'])) { require_once ("mysql_connect.php"); if (empty($_POST['username'])) { $u = FALSE; $message .= '<p> Please enter your username </p>'; } else { $u = escape_data($_POST['username']); } if (empty($_POST['password'])) { $p = FALSE; $message .= '<p>You forgot to enter your password </p>'; } else { $p = escape_data($_POST['password']); } if ($u && $p) { // If everything's OK. $query = "SELECT * FROM admin WHERE username= ('$u') AND password=('$p')"; $result = @mysqli_query($GLOBALS["___mysqli_ston"], $query); $row = mysqli_fetch_array($result, MYSQLI_BOTH); if ($row) { session_start(); $_SESSION["admin_id"] = $row[0]; //header("$page"); //Redirects user to admin_index.php //header('location: "$page"'); header ("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "admin_index.php"); //echo '$_SESSION["admin_id"]'; } else { $message = '<p> The username and password combination are incorrect.</p>'; } ((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res); } else { $message .= '<p>Please try again.</p>'; } } if (isset($message)) { echo '<font color="red">', $message, '</font>'; } //$adminLogin = 'admin_login'; } //Closes function } //Closes class Connection Script // This file contains the database access information. This file also establishes a connection to MySQL and selects the database. // Set the database access information as constants. DEFINE ('DB_USER', 'atkinson'); DEFINE ('DB_PASSWORD', 'XYZ111WA'); DEFINE ('DB_HOST', 'localhost'); DEFINE ('DB_NAME', 'practicesite'); if ($dbc = @($GLOBALS["___mysqli_ston"] = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD))) { // Make the connnection. if (!((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . constant('DB_NAME')))) { // If it can't select the database. // Handle the error. my_error_handler (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_errno($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false)), 'Could not select the database: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))); // Print a message to the user, include the footer, and kill the script. echo '<p><font color="red">The site is currently experiencing technical difficulties. We apologize for any inconvenience.</font></p>'; include_once ('includes/footer.php'); exit(); } // End of mysql_select_db IF. } else { // If it couldn't connect to MySQL. // Print a message to the user, include the footer, and kill the script. my_error_handler (((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_errno($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false)), 'Could not connect to the database: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))); echo '<p><font color="red">The site is currently experiencing technical difficulties. We apologize for any inconvenience.</font></p>'; include_once ('includes/footer.php'); exit(); } // End of $dbc IF. // Function for escaping and trimming form data. function escape_data ($data) { global $dbc; if (ini_get('magic_quotes_gpc')) { $data = stripslashes($data); } return mysqli_real_escape_string( $dbc, trim ($data)); } // End of escape_data() function. Any help would be appreciated. Cheers Will 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 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 Hi Can you call Class A's methods or properties from Class B's methods? 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 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? 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>"; } } }} |