PHP - How To Activate Ziparchive Class
im just a student and taking my on-the-job training.
i already ask my supervisor to help but she only said that i should research about that problem. so this is the problem: im working on a zip files and it displays an error undefined function zip_open.. i've posted here earlier and a moderator told me to read a link. a zlib is already installed i have read on http://www.php.net/manual/en/zip.installation.php and it said that "In order to use these functions you must compile PHP with zip support by using the --enable-zip configure option." how can i compile php using the --enable-zip configure option.. help again pls.. i run this on linux Similar TutorialsHello, I am trying to implement a simple script that ZIPs up a text file. The problem is that I don't think the ZIPArchive is available on my server. Here is an example of my code: Code: [Select] <?php $zip = new ZipArchive(); $filename = "./PJR.v2.zip"; if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) { exit("cannot open <$filename>\n"); } if ($handle = opendir('WORKDIR')) { while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { $zip->addFile($entry); } } closedir($handle); } $zip->close(); ?> When I run it from the command line, I get Code: [Select] PHP Fatal error: Class 'ZipArchive' not found in /users/albert/zip_POC.v2.php on line 2 This is the version info on my server: Code: [Select] php -v PHP 5.1.6 (cli) (built: Nov 12 2008 11:22:53) Copyright (c) 1997-2006 The PHP Group Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies Is there a way that I can install that class even though I am not the 'root' user?? Hi there,
I'm trying to create a zip file from an array of images that are posted from a form using the following code:
<?php $shortlist = $_POST['shortlist']; $dir = $_POST['imageDir']; $imageDir = $dir; $imageArr = array(); $imageArr = preg_split('/\r\n|\r|\n/', $_POST['shortlist']); array_shift($imageArr); /* foreach ($imageArr as &$value) { $value = rtrim($value); $value = $imageDir . "/" . $value; } */ $imageTotal = count($imageArr); $zip = new ZipArchive(); // Load zip library $zip_name = time().".zip"; // Zip name if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE) { // Opening zip file to load files echo "* Sorry ZIP creation failed at this time"; } else { echo"zip created"; chmod($zip_name, 0755); foreach($imageArr as $file) { $hostedFile = $imageDir . '/' . $file; echo '<img src="' . $hostedFile . '" />'; $zip->addFile($hostedFile,$file); } $close = $zip->close(); if ($close) { echo 'File Closed'; } else { echo 'fail!!'; } echo 'Download these images as a <a href="'.$zip_name.'">ZIP file</a>.\n'; } ?>The php file is in a separate folder e.g. www.website.com/php/zip-test.php to the images folder as I want to be able to re-use it for other folders. I get as far as adding the files to the zip but when I try to close the zip it fails. The only thing I can think is that the $hostedFile is a relative link, e.g. /images/image1.jpg rather than http://www.website.c...ages/image1.jpg so it's not finding the image to add to the zip So I tried adding the full website path to the image but it still does not work. The image is displaying fine when I echo it as an image, it just doesn't add to the zip. Any ideas? Thanks, Bob Hello folks, I am new to the forum. I am having a problem on SBS 2011 creating a ZipArchive with PHP. Although I have specified the filename to create as "myzip.zip" the file created in the temp folder is "myzip.zip.a10860". If I try again immediately the file becomes "myzip.zip.b10860" and then "myzip.zip.c10860". Of course the numbers will change if I wait a few minutes. I have also tried creating the file first with fopen() then closing it and trying the ZipArchive::OVERWRITE. Still the same result I have tried many standard scripts from the net as well as my own very basic script and always the same result. PHP is set up through Fastcgi. Any thoughts would be appreciated. Michael Is it possible to activate shadowbox http://www.shadowbox-js.com (similar to lightbox) if php value = 1? I'm using a wordpress theme that always tries to load a specific search tab first. ive tried figuring out if theres a way to make the second tab load first but cant seem to get it. hopefully someone can help a rookie like myself understand it for a live "demo" to get a sense of what im talking about you can see it here http://demo.woothemes.com/estate/ the Search Our Properties tab loads first. I want it to load the "Search the MLS" tab first or only display and load that one to be honest. Code: [Select] <span id="mls-search"> code is below. thanks! Code: [Select] <?php if (defined('DSIDXPRESS_OPTION_NAME')) { $options = get_option(DSIDXPRESS_OPTION_NAME); } else { $options = array('Activated' => false); } ?> <div class="search-tab <?php if(get_option('woo_idx_plugin_search') != 'true'){ echo 'no-idx'; }?>"> <?php if(get_option('woo_search_header')) { ?> <span id="local-search" class="current"><?php echo stripslashes(get_option('woo_search_header')); ?></span> <?php if ( $options['Activated'] && ( get_option('woo_idx_plugin_search') == 'true' ) ) { ?> <span id="mls-search"><a class="red-highlight"><?php echo stripslashes(get_option('woo_search_mls_header')); ?></a></span> <?php } ?> <?php } ?> </div> <div id="search"> <form name="property-webref-search" id="property-webref-search" method="get" action="<?php bloginfo('url'); ?>/"> <input type="text" class="text webref" id="s-webref" name="s" value="<?php _e('Property ID', 'woothemes'); ?>" onfocus="if (this.value == '<?php _e('Property ID', 'woothemes'); ?>') {this.value = '';}" onblur="if (this.value == '') {this.value = '<?php _e('Property ID', 'woothemes'); ?>';}" /> <input type="submit" class="submit button" name="property-search-webref-submit" value="<?php _e('Go To', 'woothemes'); ?>" /> </form> <form name="property-search" id="property-search" method="get" action="<?php bloginfo('url'); ?>/"> <div class="query"> <?php if (isset($_GET['s'])) { $keyword = strip_tags($_GET['s']); } else { $keyword = ''; } if ( $keyword == 'View More' ) { $keyword = ''; } ?> <input type="text" class="main-query text" id="s-main" name="s" value="<?php if ( $keyword != '' ) { echo $keyword; } else { _e(get_option('woo_search_keyword_text'), 'woothemes'); } ?>" onfocus="if (this.value == '<?php _e(get_option('woo_search_keyword_text'), 'woothemes') ?>') {this.value = '';}" onblur="if (this.value == '') {this.value = '<?php _e(get_option('woo_search_keyword_text'), 'woothemes') ?>';}" /> <input type="submit" class="submit button" name="property-search-submit" value="<?php _e('Search', 'woothemes'); ?>" /> <span class="or"><?php _e('Or', 'woothemes'); ?></span> <div class="fix"></div> </div><!-- /.query --> <div class="filters"> <?php if (isset($_GET['sale_type'])) { $sale_type = $_GET['sale_type']; } else { $sale_type = ''; } if ($sale_type == '') { $sale_type = 'all'; } ?> <div class="saletype"> <label for="saletype"><?php _e(get_option('woo_label_sale_type'), 'woothemes'); ?>:</label> <input type="radio" name="sale_type" value="all" <?php if ($sale_type == 'all') { ?>checked<?php } ?>> <?php _e('All', 'woothemes') ?> <input type="radio" name="sale_type" value="sale" <?php if ($sale_type == 'sale') { ?>checked<?php } ?>> <?php _e(get_option('woo_label_for_sale'), 'woothemes') ?> <input type="radio" name="sale_type" value="rent" <?php if ($sale_type == 'rent') { ?>checked<?php } ?>> <?php _e(get_option('woo_label_for_rent'), 'woothemes') ?> </div><!-- /.saletype --> <div class="location-type"> <label><?php _e(get_option('woo_label_property_location_and_type'), 'woothemes'); ?>:</label> <?php //property locations drop down if (isset($_GET['location_names'])) { $category_ID = $_GET['location_names']; } else { $category_ID = 0; } if ($category_ID > 0) { //Do nothing } else { $category_ID = 0; } $dropdown_options = array ( 'show_option_all' => __(get_option('woo_label_locations_dropdown_view_all')), 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', 'name' => 'location_names', 'id' => 'location_names', 'taxonomy' => 'location', 'hide_if_empty' => 1, 'selected' => $category_ID ); wp_dropdown_categories($dropdown_options); ?> <?php //property types drop down if (isset($_GET['property_types'])) { $category_ID = $_GET['property_types']; } else { $category_ID = 0; } if ($category_ID > 0) { //Do nothing } else { $category_ID = 0; } $dropdown_options = array ( 'show_option_all' => __(get_option('woo_label_property_type_dropdown_view_all')), 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', 'name' => 'property_types', 'id' => 'property_types', 'taxonomy' => 'propertytype', 'hide_if_empty' => 1, 'selected' => $category_ID, 'class' => 'last' ); wp_dropdown_categories($dropdown_options); if (isset($_GET['price_min'])) { $price_min = $_GET['price_min']; } else { $price_min = ''; } if (isset($_GET['price_max'])) { $price_max = $_GET['price_max']; } else { $price_max = ''; } ?> </div><!-- /.location-type --> <div class="fix"></div> <div class="price"> <label for="price_min"><?php _e(get_option('woo_label_min_price'), 'woothemes'); ?> <?php echo '('.get_option('woo_estate_currency').')'; ?>:</label><input type="text" class="text price validate_number" name="price_min" id="price_min" value="<?php if ( $price_min != '' ) { echo $price_min; } ?>" > <label for="price_max"><?php _e(get_option('woo_label_max_price'), 'woothemes'); ?> <?php echo '('.get_option('woo_estate_currency').')'; ?>:</label><input type="text" class="text price validate_number" name="price_max" id="price_max" value="<?php if ( $price_max != '' ) { echo $price_max; } ?>" > </div><!-- /.price --> <span class="advanced-search-button button"><?php _e(get_option('woo_label_advanced_search'), 'woothemes'); ?> ↓</span> <div class="fix"></div> <div id="advanced-search"> <?php if (isset($_GET['no_garages'])) { $no_garages = $_GET['no_garages']; } else { $no_garages = 'all'; } ?> <?php if (isset($_GET['no_beds'])) { $no_beds = $_GET['no_beds']; } else { $no_beds = 'all'; } ?> <?php if (isset($_GET['no_baths'])) { $no_baths = $_GET['no_baths']; } else { $no_baths = 'all'; } ?> <?php if (isset($_GET['size_min'])) { $size_min = $_GET['size_min']; } else { $size_min = ''; } ?> <?php if (isset($_GET['size_max'])) { $size_max = $_GET['size_max']; } else { $size_max = ''; } ?> <?php $options_features_amount = array("0","1","2","3","4","5","6","7","8","9","10+"); ?> <div class="features-filters"> <label for="no_garages"><?php _e(get_option('woo_label_garages'), 'woothemes'); ?>:</label> <select class="postform" id="no_garages" name="no_garages"> <option <?php if ($no_garages == 'all') { ?>selected="selected"<?php }?> value="all"><?php _e('Any', 'woothemes') ?></option> <?php foreach ($options_features_amount as $option) { ?><option <?php if ($no_garages == $option) { ?>selected="selected"<?php }?> value="<?php echo $option; ?>"><?php echo $option; ?></option><?php } ?> </select> <label for="no_beds"><?php _e(get_option('woo_label_beds'), 'woothemes'); ?>:</label> <select class="postform" id="no_beds" name="no_beds"> <option <?php if ($no_beds == 'all') { ?>selected="selected"<?php }?> value="all"><?php _e('Any', 'woothemes') ?></option> <?php foreach ($options_features_amount as $option) { ?><option <?php if ($no_beds == $option) { ?>selected="selected"<?php }?> value="<?php echo $option; ?>"><?php echo $option; ?></option><?php } ?> </select> <label for="no_baths"><?php _e(get_option('woo_label_baths_long'), 'woothemes'); ?>:</label> <select class="postform last" id="no_baths" name="no_baths"> <option <?php if ($no_baths == 'all') { ?>selected="selected"<?php }?> value="all"><?php _e('Any', 'woothemes') ?></option> <?php foreach ($options_features_amount as $option) { ?><option <?php if ($no_baths == $option) { ?>selected="selected"<?php }?> value="<?php echo $option; ?>"><?php echo $option; ?></option><?php } ?> </select> <label for="size_min"><?php _e(get_option('woo_label_min_size'), 'woothemes'); ?> <?php echo '('.get_option('woo_label_size_metric').')'; ?>:</label><input type="text" class="text size validate_number" name="size_min" id="size_min" value="<?php if ( $size_min != '' ) { echo $size_min; } ?>" > <label for="size_max"><?php _e(get_option('woo_label_max_size'), 'woothemes'); ?> <?php echo '('.get_option('woo_label_size_metric').')'; ?>:</label><input type="text" class="last text size validate_number" name="size_max" id="size_max" value="<?php if ( $size_max != '' ) { echo $size_max; } ?>" > </div><!-- /.size --> </div><!-- /#advanced-search --> <div class="fix"></div> </div><!-- /.filters --> <?php $term_names = ''; $price_list = ''; $size_list = ''; //Taxonomies $taxonomy_data_set = get_terms(array('location',/*'pricerange',*/'propertytype','propertyfeatures'), array('fields' => 'names')); $taxonomy_data_set = woo_multidimensional_array_unique($taxonomy_data_set); foreach ($taxonomy_data_set as $data_item) { //Convert string to UTF-8 $str_converted = woo_encoding_convert($data_item); //Add category name to data string $term_names .= htmlspecialchars($str_converted, ENT_QUOTES, 'UTF-8').','; } //Post Custom Fields $meta_data_fields = array('address'); $meta_data_set = woo_get_custom_post_meta_entries($meta_data_fields); $meta_data_set = woo_multidimensional_array_unique($meta_data_set); foreach ($meta_data_set as $data_item) { //Convert string to UTF-8 $str_converted = woo_encoding_convert($data_item->meta_value); //Add category name to data string $term_names .= htmlspecialchars($str_converted, ENT_QUOTES, 'UTF-8').','; } $price_list = ''; //Post Custom Fields $meta_data_fields = array('price'); $meta_data_set = woo_get_custom_post_meta_entries($meta_data_fields); $meta_data_set = woo_multidimensional_array_unique($meta_data_set); foreach ($meta_data_set as $data_item) { //Convert string to UTF-8 $str_converted = woo_encoding_convert($data_item->meta_value); //Add category name to data string $price_list .= htmlspecialchars($str_converted, ENT_QUOTES, 'UTF-8').','; } //Post Custom Fields $meta_data_fields = array('size'); $meta_data_set = woo_get_custom_post_meta_entries($meta_data_fields); $meta_data_set = woo_multidimensional_array_unique($meta_data_set); foreach ($meta_data_set as $data_item) { //Convert string to UTF-8 $str_converted = woo_encoding_convert($data_item->meta_value); //Add category name to data string $size_list .= htmlspecialchars($str_converted, ENT_QUOTES, 'UTF-8').','; } ?> <script> jQuery(document).ready(function($) { <?php if ( ( ($no_garages == 'all') || ($no_garages == '') ) && ( ($no_beds == 'all') || ($no_beds == '') ) && ( ($no_baths == 'all') || ($no_baths == '') ) && ( $size_min == '' ) && ( $size_max == '' ) ) { ?>jQuery("#advanced-search").toggle();<?php } ?> jQuery(".advanced-search-button").click(function(){ var hidetext = 'Hide <?php echo get_option('woo_label_advanced_search'); ?>'; var showtext = '<?php echo get_option('woo_label_advanced_search'); ?>'; var currenttext = jQuery(".advanced-search-button").text(); //toggle advanced search jQuery("#advanced-search").toggle(); //toggle text if (currenttext == hidetext) { jQuery(".advanced-search-button").text(showtext); //reset search values jQuery("#no_garages").val('all'); jQuery("#no_beds").val('all'); jQuery("#no_baths").val('all'); } else { jQuery(".advanced-search-button").text(hidetext); } }); //GET PHP data items var keyworddataset = "<?php echo $term_names; ?>".split(","); var pricedataset = "<?php echo $price_list; ?>".split(","); var sizedataset = "<?php echo $size_list; ?>".split(","); //Set autocomplete(s) $("#s-main").autocomplete(keyworddataset); $("#price_min").autocomplete(pricedataset); $("#price_max").autocomplete(pricedataset); $("#size_min").autocomplete(sizedataset); $("#size_max").autocomplete(sizedataset); //Handle autocomplete result $("#s").result(function(event, data, formatted) { //Do Nothing }); $("#price_min").result(function(event, data, formatted) { //Do Nothing }); $("#price_max").result(function(event, data, formatted) { //Do Nothing }); $("#size_min").result(function(event, data, formatted) { //Do Nothing }); $("#size_max").result(function(event, data, formatted) { //Do Nothing }); }); </script> <div class="fix"></div> </form> <?php if ( $options['Activated'] && ( get_option('woo_idx_plugin_search') == 'true' ) ) { $pluginUrl = DSIDXPRESS_PLUGIN_URL; $formAction = get_bloginfo("url"); if (substr($formAction, strlen($formAction), 1) != "/") $formAction .= "/"; $formAction .= dsSearchAgent_Rewrite::GetUrlSlug(); ?> <form name="property-mls-search" id="property-mls-search" method="get" action="<?php echo $formAction; ?>"> <?php $defaultSearchPanels = dsSearchAgent_ApiRequest::FetchData("AccountSearchPanelsDefault", array(), false, 60 * 60 * 24); $defaultSearchPanels = $defaultSearchPanels["response"]["code"] == "200" ? json_decode($defaultSearchPanels["body"]) : null; $propertyTypes = dsSearchAgent_ApiRequest::FetchData("AccountSearchSetupPropertyTypes", array(), false, 60 * 60 * 24); $propertyTypes = $propertyTypes["response"]["code"] == "200" ? json_decode($propertyTypes["body"]) : null; $requestUri = dsSearchAgent_ApiRequest::$ApiEndPoint . "LocationsByType"; //cities $location_cities = explode("\n", get_option('woo_idx_search_cities')); //communities $location_communities = explode("\n", get_option('woo_idx_search_communities')); //Tracts $location_tracts = explode("\n", get_option('woo_idx_search_tracts')); //Zips $location_zips = explode("\n", get_option('woo_idx_search_zips')); ?> <div class="mls-property-type"> <label for="idx-q-PropertyTypes"><?php _e('Property Type', 'woothemes'); ?>:</label> <select name="idx-q-PropertyTypes" class="dsidx-search-widget-propertyTypes"> <option value="All">- All property types -</option> <?php if (is_array($propertyTypes)) { foreach ($propertyTypes as $propertyType) { $name = htmlentities($propertyType->DisplayName); echo "<option value=\"{$propertyType->SearchSetupPropertyTypeID}\">{$name}</option>"; } } ?> </select> <label for="idx-q-MlsNumbers"><?php _e('MLS #', 'woothemes'); ?>:</label> <input id="idx-q-MlsNumbers" name="idx-q-MlsNumbers" type="text" class="text" /> </div> <div class="fix"></div> <div class="mls-area-details"> <label for="idx-q-Cities"><?php _e('City', 'woothemes'); ?>:</label> <select id="idx-q-Cities" name="idx-q-Cities" class="small"> <?php if (is_array($location_cities)) { foreach ($location_cities as $city) { $city_name = htmlentities(trim($city)); echo "<option value=\"{$city_name}\">$city_name</option>"; } } ?> </select> <label for="idx-q-Communities"><?php _e('Community', 'woothemes'); ?>:</label> <select id="idx-q-Communities" name="idx-q-Communities" class="small"> <option value="">- Any -</option> <?php if (is_array($location_communities)) { foreach ($location_communities as $community) { $community_name = htmlentities(trim($community)); echo "<option value=\"{$community_name}\">$community_name</option>"; } } ?> </select> <label for="idx-q-TractIdentifiers"><?php _e('Tract', 'woothemes'); ?>:</label> <select id="idx-q-TractIdentifiers" name="idx-q-TractIdentifiers" class="small"> <option value="">- Any -</option> <?php if (is_array($location_tracts)) { foreach ($location_tracts as $tract) { $tract_name = htmlentities(trim($tract)); echo "<option value=\"{$tract_name}\">$tract_name</option>"; } } ?> </select> <label for="idx-q-ZipCodes"><?php _e('Zip', 'woothemes'); ?>:</label> <select id="idx-q-ZipCodes" name="idx-q-ZipCodes" class="small"> <option value="">- Any -</option> <?php if (is_array($location_zips)) { foreach ($location_zips as $zip) { $zip_name = htmlentities(trim($zip)); echo "<option value=\"{$zip_name}\">$zip_name</option>"; } } ?> </select> </div> <div class="fix"></div> <div class="mls-features"> <label for="idx-q-PriceMin"><?php _e('Min Price', 'woothemes'); ?>:</label> <input id="idx-q-PriceMin" name="idx-q-PriceMin" type="text" class="text validate_number" /> <label for="idx-q-PriceMax"><?php _e('Max Price', 'woothemes'); ?>:</label> <input id="idx-q-PriceMax" name="idx-q-PriceMax" type="text" class="text validate_number" /> <label for="idx-q-ImprovedSqFtMin"><?php _e('Min Size', 'woothemes'); ?> <?php echo '(SQ FT)'; ?>:</label> <input id="idx-q-ImprovedSqFtMin" name="idx-q-ImprovedSqFtMin" type="text" class="text validate_number" /> <label for="idx-q-BedsMin"><?php _e('Beds', 'woothemes'); ?>:</label> <input id="idx-q-BedsMin" name="idx-q-BedsMin" type="text" class="text validate_number" /> <label for="idx-q-BathsMin"><?php _e('Baths', 'woothemes'); ?>:</label> <input id="idx-q-BathsMin" name="idx-q-BathsMin" type="text" class="text validate_number" /> </div> <input type="submit" value="Search" class="submit button" /> <?php if($options["HasSearchAgentPro"] == "yes"){ echo 'try our <a href="'.$formAction.'advanced/"><img src="'.$pluginUrl.'assets/adv_search-16.png" /> Advanced Search</a>'; } ?> <div class="fix"></div> </form> <?php } ?> </div><!-- /#search --> Hey guys I wasnt sure if this is a php topic or java script im trying to make my drop down menu's activate onchange. what confuses me is how do I make php know that the java script is being run. Or have the java script trip my php code. To know a button has been pressed i use "if (isset['_POST'])" echo '<select name="siege_list" id="siege_list">'; foreach($name as $key => $value) { echo '<option value="' . $value['name'] . '" ' . ($value['name'] == $current1 ['name'] ? 'selected="selected"' : '') . '> ' . $value['name'] . '</options>'; } echo '</select><input type="submit" id="siege_planet" onchange="this.form.submit()">'; Hi is it possible to make the Icon for my input activate the date picker (I'm using Materialize for my class) A lot of users seem to instinctively try to click the icon rather than the input field on mobile devices <div class="input-field col s12 m8 l7 xl7"> <i class="material-icons prefix">calendar_today</i> <input type="text" name="r_date" class="datepicker"> <label for="r_date"></label> </div> <script> $(document).ready(function(){ $('.sidenav').sidenav(); $('select').formSelect(); $('.datepicker').datepicker({ format:'yyyy-mm-dd' }); $(".dropdown-trigger").dropdown(); }); </script>
Some help would be great here. The following snippets work, but I am unable to figure out how to activate the error message "You did not select a name for editing". Both of the other error codes work but if I input 'given' and 'family' and forget to select the relevant radio button, the error message doesn't work. No other problems with the code. Code: [Select] <html> <table> <?php // Query member data from the database $query1 = mysql_query("SELECT userId FROM users WHERE managerId='".$recid."' AND userGroup='".$group2."' ORDER BY userId ASC"); while($row1 = mysql_fetch_array($query1)) { $firstGroup .=$row1['userId']. ' <input type="radio" name="snames" value="'.$row1['userId'].'" /> ' . " <br /><br>"; } ?> <form method="post" enctype="multipart/form-data" action="<?PHP echo $_SERVER["PHP_SELF"]; ?>"> <tr> <td><?php echo $firstGroup;?></td> <td><input type="text" name="given" value="" /><p> <input type="text" name="family" value="" /><p> <input type="submit" value="submit" name="Send Data"></form></td> </tr> </table> </html Here are the error messages and their activation method. Code: [Select] <?php // Process the form if it is submitted if ($_POST['snames']) { $snames = $_POST['snames']; $family = preg_replace("/[^A-Za-z0-9]/", ".", $_POST['family']); $given = preg_replace("/[^A-Za-z0-9]/", ".", $_POST['given']); //next section deals with error messaging $errorMsg = "ERROR:"; if(!$snames) { $errorMsg .= "--- You did not select a name for editing."; } else if(!$family) { $errorMsg .= "--- You did not enter a family name."; } else if(!$given) { $errorMsg .= "--- You did not enter a given name."; } else { exit(); } }// close if post echo $errorMsg; ?> 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 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 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. 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. 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 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? 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. 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? 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? 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>"; } } }} |