Jump to content

Search the Community

Showing results for tags 'functions'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I'm making a registration form and I'm really new at it. I've had a look about at similar issues but feel like I've got my code set up right, I obviously don't. I have a registration_handler.php and a functions.php file. I'm simply trying to pass an array ($errors[]) from the functions that generate them to a function that prints them out on registration_handler.php. It seems so easy, but I'm not getting it. Here's my code: from functions.php: (this is just an example of one of the functions) // USERNAME (MANDATORY) //uses the clean_names() and checks for empty input function assign_username() { global $conn; $username = $_POST['username']; if(!$username){ $errors[] = "A username is mandatory"; echo "A username is mandatory <br>"; } else { $username = clean_names($username); } //check for duplicate username and return $username if doesn't exist already $username_check = mysqli_query($conn, "SELECT username FROM users WHERE username='$username'"); $number_rows = mysqli_num_rows($username_check); if($number_rows > 0) { $errors[] = "Username already in use <br>"; echo "Username already in use <br>"; } else { return $username; } return $errors; } // END USERNAME Also from functions.php, the function to print out the error array: //display error array function show_errors($errors) { print_r($errors); } and the function call from registration_handler.php: if(isset($_POST['register_button'])) { //assign clean form variables $firstname = assign_firstname(); $lastname = assign_lastname(); $username = assign_username(); $email = assign_email(); $password = assign_password(); $date = date("Y-m-d"); $errors = array(); show_errors($errors); } I'm intentionally leaving the username out to test this on the form but I only get returned Array() It echos "Username is mandatory" but it seems like it's not passing the error string to the error array Can anyone point me towards what I'm doing wrong, please. I appreciate the replies
  2. I've made this code for a very simple registration form practice: //assign form variables $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $username = $_POST['username']; function clean_names($dirty_name) { strip_tags($dirty_name); str_replace(' ', '', $dirty_name); ucfirst(strtolower($dirty_name)); //return $dirty_name; } $names = array($firstname, $lastname, $username); if(isset($_POST['register_button'])) { // WHY IS THIS FUNC CALL NOT WORKING?? foreach($names as $name) { clean_names($name); } echo "First Name: " . $firstname . "<br>"; echo "Last Name: " . $lastname . "<br>"; echo "Username: " . $username . "<br>"; } The values are returned but they haven't been put through the clean_names function. I'm really new with PHP. Can someone tell me why this isn't working? Thank you
  3. I have two functions that execute an exe program (personal project for a minecraft back end.) Windows only. First one will execute the sending of commands (THIS ONE WORKS) /* check to see if admin is sending commands to terminal via web */ if(isset($_POST['command'])) { $content = $_POST['command']; writeMCCommandTxt($content); try { exec(SERVER_DIR.'mcCommand.exe',$output); } catch ( Exception $e ) { die ($e->getMessage()); } }// END COMMAND ENTRY This has been a head scratcher for most the week - any help or suggestions would be great!! thanks!! HTML <div id="commands"> <div id="command_input"> <form method="post" id="commandForm" action="index.php"> <label for="command" >Console Command:</label><br/> <input type="text" name="command" autofocuS/> <input type="submit" name="submit_command" value=" >> " /> &nbsp; <input type="button" value="Refresh page" onclick="location.reload(true);" /> </form> </div> </div> This is used to start the server // STARTING SERVER if(isset($_POST['startServerBtn'])){ try { exec(SERVER_DIR.'startServer.bat 2>&1' ,$output); } catch( Exception $e ) { die ($e->getMessage()); } } HTML <div id="server_control"> <ul> <li> <form action="index.php" method="post"> <input type="submit" value="START" id="startServerBtn" name="startServerBtn"/> </form> </li> </ul> </div> MCCOMMANDS.EXE will work from both browser(php) and file manager(tested) the STARTSERVER.EXE will NOT work from browser(php), but will work from file manager The function IS being accessed - debug is showing it going there, and it seems to be running Both exe's are in the same folder
  4. Hi all, I am trying to pass 4 variables from one php page to another php page containing a google maps api. The variables I am passing are geo coordinates. at the end I want to show the map on my php page however I am struggling with linking php and javascipt together. This is what I have so far: external function page: http://pastebin.com/NAKHmKxW [PART OF MAIN PHP PAGE] <div class="row"> <?php include_once("function_maps.php"); initMap($latitude, $longitude,$row['Latitude'],$row['Longitude']); ?> </div>
  5. Ok, I want to do this: if (logins < 10) { header("Location: ../help") } Can i do it?
  6. Hello guys! I really really really hope anyone can help me because I am quite desperate about a little project I'm making. I want to construct a sort of online catalog for books with a "shoppingcart" and a profile for every user, but object orientated. I have a database with the table products which contains: ID, title, author, genre, price etc etc etc My main question is: How can I get one single field from the database with e.g. a function called getPrice(); I tried everything but nothing displays the data the way i want to. I simply want to have a sql-statement in this function and when I am calling the function getPrice() later on it displays just the number and no Array, code or whatever. Is there a way to call getPrice() and get "20.00" back? Please Help!
  7. Hi Guys I am a rookie here... I have a function which gets information from a postgres database. And returns an array. But how do I echo a single value from the array returned by the function. Please see function below: function getDate($campid) { global $conn,$agencies; $return=array( 'date'=>'', ); $sql = "SELECT tsc_date_completed FROM tasks_completed WHERE campid = '".$campid."' AND tsk_id = 10 ORDER BY id DESC LIMIT 1"; $r = pg_query($conn,$sql); if ($r) { $d = pg_fetch_array($r); if (!empty($d)) { $return['date'] = $d['tsc_date_completed']; } } @pg_free_result($r); return $return; }
  8. hi how can I make a function for multi pages , the function accept two arguments (page name, number of records which showed in one page). and returns the data from the table , also returns the number of pages
  9. Hi, everyone. I'm having some trouble finding tutorial projects for PHP Functions. Can anyone point me in the right direction if you know of any? I apologize if this is the wrong category to post in for my particular question.
  10. Help I am trying to pass a php variable into a javasript function. Here is my code. <a href="<?php echo $row['track']; ?>" download="<?php echo $row['track']; ?>" onclick="myhit(<?php echo $row['track']; ?>)">Download</a> <script> function myhit(top){ alert(top); } </script> the javascript function is never called
  11. Write a function Counter() that keeps track of the number of times it is called. This function should not take any parameters and return the number of times that it has been called. Example: echo Counter();//1 echo Counter(); //2 I think I would go like this... $count = 0; function Counter() { $count = $count + 1; } Is this too simple? Am I doing it wrong
  12. So I have this CMS that I have spent the last 5 years building and rebuilding and updating blah blah. It's a fairly extensive piece work and I am now looking at converting the entire system over to OOP. I am fairly new to OOP but understand the easy basics of it. I do fight with the concept of when to make a class and when to just make a normal function. I have many functions that I built specific to how my system works and some I suppose could be grouped into categories but then many others are just plain functions that only serve one purpose and may only be a few lines long. I will be using the spl_autoload_register() to load the classes as needed which is obviously much easier than including all the function pages that are needed. So for that reason I like the idea of making classes for everything but it just seems like more than is needed. So what I am looking for is some insight as to when and how to decide if a class should be made and whether to group functions by category to limit the amount of classes OR to just leave them as normal functions. Here is a example function for creating a thumbnail. I would guess that I could make a class called Thumb and put this in it, but what exactly would be the benefit of that based on the syntax of the function AND could you show me how you would convert this to OOP to make it worth while putting it in a class? // Creates a thumbnail function createThumb($img, $type, $dest = NULL, $xy = NULL) { if($type=="admin_product") { $thumb_width = $GLOBALS['admin_thumb_width']; $thumb_height = $GLOBALS['admin_thumb_height']; } elseif($type=="custom") { $thumb_width = ($dest !== NULL) ? $xy['x'] : (int)$_GET['width']; $thumb_height = ($dest !== NULL) ? $xy['y'] : (int)$_GET['height']; } $src_size = getimagesize($img); if($src_size['mime'] === 'image/jpg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/jpeg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/pjpeg') {$src = imagecreatefromjpeg($img);} elseif($src_size['mime'] === 'image/png') {$src = imagecreatefrompng($img);} elseif($src_size['mime'] === 'image/gif') {$src = imagecreatefromgif($img);} $src_aspect = round(($src_size[0] / $src_size[1]), 1); $thumb_aspect = round(($thumb_width / $thumb_height), 1); if($src_aspect < $thumb_aspect)//Higher { $new_size = array($thumb_width, ($thumb_width / $src_size[0]) * $src_size[1]); $src_pos = array(0, (($new_size[1] - $thumb_height) * ($src_size[1] / $new_size[1])) / 2); } elseif($src_aspect > $thumb_aspect)//Wider { $new_size = array(($thumb_height / $src_size[1]) * $src_size[0], $thumb_height); $src_pos = array((($new_size[0] - $thumb_width) * ($src_size[0] / $new_size[0])) / 2, 0); } else//Same Shape { $new_size = array($thumb_width, $thumb_height); $src_pos = array(0, 0); } if($new_size[0] < 1){$new_size[0] = 1;} if($new_size[1] < 1){$new_size[1] = 1;} $thumb = imagecreatetruecolor($new_size[0], $new_size[1]); imagealphablending($thumb, false); imagesavealpha($thumb, true); imagecopyresampled($thumb, $src, 0, 0, 0, 0, $new_size[0], $new_size[1], $src_size[0], $src_size[1]); //$src_pos[0], $src_pos[1] 3rd and 4th of zeros position on above line if($src_size['mime'] === 'image/jpg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/jpeg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/pjpeg') { if($dest !== NULL) { imagejpeg($thumb, $dest, 95); } else { header('Content-Type: image/jpeg'); imagejpeg($thumb, NULL, 95); } } elseif($src_size['mime'] === 'image/png') { if($dest !== NULL) { imagepng($thumb, $dest); } else { header('Content-Type: image/png'); imagepng($thumb); } } elseif($src_size['mime'] === 'image/gif') { if($dest !== NULL) { imagegif($thumb, $dest); } else { header('Content-Type: image/gif'); imagegif($thumb); } } imagedestroy($src); } Your insight is appreciated.
  13. Whats up guys. I've created two links in an html document. The problem is the JavaScript below gives me a value of undefined after running the for loop. I know this has something to do with closures, which I don't have much experience with so I can't figure out why the value of links is undefined. JavaScript: window.onload = function getLinks(){ var links = document.links; for(var i = 0, count = links.length; i < count; i++){ links[i].onclick = function(){ alert(links[i].href); return false; }; } }; html: <body> <p><a href="linkOne.html" id="link" target="linkOne">Link B</a></p> <p><a href="linkTwo.html" id="link" target="linkTwo">Link A</a></p> <script src="js/handleLinks.js"></script> </body> </html>
  14. I've never understood the application of return true and return false after function calls in JavaScript. Could somebody please explain their meaning. This is a very simple script which will create a popup window for each links in an html document. function createPopup(e) { 'use strict'; // Get the event object: if (typeof e == 'undefined') var e = window.event; // Get the event target: var target = e.target || e.srcElement; // Create the window: var popup = window.open(target.href, 'PopUp', 'height=100,width=100,top=100,left=100,location=no,resizable=yes,scrollbars=yes'); // Give the window focus if it's open: if ( (popup !== null) && !popup.closed) { popup.focus(); return false; // Prevent the default behavior. } else { // Allow the default behavior. return true; } } // End of createPopup() function. // Establish functionality on window load: window.onload = function() { 'use strict'; // Add the click handler to each link: for (var i = 0, count = document.links.length; i < count; i++) { document.links[i].onclick = createPopup; } // End of for loop. }; // End of onload function. The only part of the script that doesn't make sense here is the return true/false. Why do we use return true or return false after calling a JavaScript function?
  15. Hey guys, i am working for the first time on a localhost. at the moment i have an index file and i want to start splitting the page up to make this website dynamic. at first i tried to take my <head>.( <meta> / <title> tags , ) and include() them with a header.php file I am not sure if this is something i can even do or if my path is just not correct. i have my wamp on my C drive and its all through a www folder path. i then created an include file inside the www, where all files that i would use dynamically would be placed( header, footer, etc..) i tried two paths: include('include/header.php'); - didn't work i then removed the folder and had all the php files in one folder. include('header.php'); none of this works , the css of the page doesnt show up. i then replace the <head> info back inside the index, and all works fine. any suggestions ?
  16. I have checkbox function that creates a checkbox list from my database. I also have a map that I want onclick to check the checkbox align with that section of the map. So if you click Bominvile on the map the checkbox for Bominville gets checked/unChecked. [FUNCTION CALL] (From db.php) / This will create a CHECK BOX based on the property/value pairs in table AND the toggle all checkbox. function buildCheckBox($table, $prechecked) { $conn = db_connect(); // establish connection $sql = "SELECT property, value FROM ".$table.""; $results = pg_query($conn, $sql); //THIS LOOP ONLY RUNS ONCE ON PAGE LOAD. JUST TO DISPLAY // THE REORDS IN THE CITY DB TABLE. while ($record = pg_fetch_array($results)) { $checked = ($prechecked == $record['value'])?"checked=\"checked\"":""; echo '<input type="checkbox" name="'. $table.'[]" ' .$checked.' value="'. $record['value'] .'">'. $record['property'] .'<br/>'; } //echo "show me whats record ". $record['property']. "<br/>"; } [/FUNCTION] <script language="javascript"> function myclick(whichone) { if (document.getElementById(whichone).checked == true) { document.getElementById(whichone).checked = false; } else { document.getElementById(whichone).checked = true; } } </script> <tr> <td class="left"> <input type="checkbox" id="city_toggle" onclick="cityToggleAll();" name="city[]">City Toggle All<br/> <!-- FUNCTION CALL TO LOOP THROUGH TOGGLING CHECK BOXES ON/OFF--> <?php echo buildCheckBox('city', $selected_city);?> <input type="checkbox" id="city[]"><br> </td> <td><img src="pictures/durham_mapgoodbeforewhitby.png" alt="durham_map" width="417" height="340" usemap="#map1"> <a href="#" onClick="myclick('city[]')"> <map name="map1"> <area shape="poly" coords="193,207,284,207,391,214,190,287,260,299,300,307,344,310,389,322" href="#" id="city[]" title="Bowmanville" alt="Bowmanville" /> </map> </a><br> </td> </tr>
  17. Hello everybody. First: Sory for my english. I'm searching a way to know wich lines of files are executed in all the request... Or something like that. Example: If we have this code: line 01: <?php line 02: function foo(){ line 03: echo 'Hello'; line 04: return false; line 05: } line 06: line 07: echo 'We are testing'; line 08: foo(); line 09: echo 'end of script'; line 10: ?> I need get the lines and the files executeds... For example, a log-file with this information: file index.php lines executeds: 07, 08, 02, 03, 04, 09, 10 Or something like that... I don't know... Anybody can help me? Tnks! Noel
  18. Hi, I'm not sure if either I just have had a stupid error or what. Here is my code on the page with the functions for my script, which is called using require_once() on my other page. session_start(); function log_in($username, $password) { global $ss_con; $_SESSION['logged_in'] = 'true'; $_SESSION['username'] = $username; } This is the code for the other page that has require once... require_once('firstpage.php'); log_in(); if ($_SESSION['logged_in'] != 'true') { echo $_SESSION['logged_in']; echo 'fail!'; } The responce I get is "fail!" Don't worry about log_in() being set. I did that on another page on the same host that just forwards to this. Please help me!
  19. I am making a php calendar but struggling to get the query to work. The php calendar is made through a function with 3 variables fed into it. you can find the full calendar http://davidwalsh.name/php-event-calendar Anyway back to my variables. 3 of them.... $month, $year, $events Which are gotten as so.... /* date settings */$month = (int) ($_GET['month'] ? $_GET['month'] : date('m'));$year = (int) ($_GET['year'] ? $_GET['year'] : date('Y')); /* get all events for the given month */$events = array();mysql_select_db($database_dbconnect, $dbconnect);$query = "SELECT title,idcalendar, DATE_FORMAT(event_date,'%Y-%m-%D') AS event_date FROM calendar WHERE event_date LIKE '$year-$month%'";$result = mysql_query($query, $dbconnect) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) {$events[$row['event_date']][] = $row;} Now I have my 3 vars I feed them into my function with the following line <?php echo draw_calendar($month,$year,$events); ?> Now within my function there is the following line to print out the event on any given day /* list the events */if(isset($events[$event_day])) {foreach($events[$event_day] as $event) {$calendar.= '<div class="event">'.$event['title'].'</div>'; }}else {$calendar.= str_repeat('<p> </p>',2);} As you can see if it finds an event it will show it and if it cant it will show 2 empty paragraph tags. I have an event in my database and under the field titled event_date and the event is for 2013-07-16 00:00:00 which is obviously today. If I use MySQL to run the query it pulls back my event quite happy. As soon as I run it in the webpage I get my empty paragraph tags back. Please help
  20. I was given this function question for an interview. I don't think I'm interested in the job and therefore will not submit this, but I am curious how to answer this. Once I start something like this, I can't just quit without knowing the answer. Questions: 1. Does the function have any errors? 2. What is the purpose of the function? 3. What can be done to improve it? 4. Why is isset() used instead of a simple conditional used above it? 5. What assumptions can you make about the database structure? function auto_query( $table, $vars ) { $_result = $this->query( "EXPLAIN $_table_name" ); $_fields = array(); // Empty array assigned to variable while( $_row = $_result->fetchRow() ) { array_push( $_fields, $_row['Field'] ); // Push one or more elements onto the end of array } if( $vars[$table . 'id'] ) { $_query = "UPDATE $_table SET "; } else { $_query = "INSERT INTO $_table SET " . $_table . '_date_created = NOW(), '; } $_query_params = array(); // Empty array assigned to variable foreach( $_fields as $_field ) { if( isset( $_vars[$_field] ) ) { $_query_params[] = "$_field = " . $this->dbh->quoteSmart( $_vars[$_field] ); } } $_query .= implode( ',', $_query_params ); // Join array elements with a string if( $_vars[$_table . '_id'] ) { $_query .= " WHERE {$_table}_id = " . $this->dbh->quoteSmart($_vars[$_table . '_id']); } return $_query; }
  21. I need some help turning code into functions, I am getting my page to do as it should but its not with functions $confId = rand(1,1000); I need for this to be a function as well as this if($base == "") { $errors .= "<li>How Many Days Are You Attending the Convention?</li><br />"; } if($base == "One") { $cost = 100;} if ($base == "One" && $mealPlan =="Yes") { $cost = 100 + 50; } if($base == "Two" ) { $cost = 175;} if ($base == "Two" && $mealPlan =="Yes") { $cost = 175 + 75; } if($base == "Three") { $cost = 225;} if ($base == "Three" && $mealPlan =="Yes") { $cost = 225 + 100; } $count = count($extra); // If no errors, display the form data if($errors == "") { echo <<<END <p>$first_name $last_name thank you for your interest.</p> <p>You have registered for $base day(s) at our Technology Conference</p> <p> You choose $track as for your track of interest.</p> <p>Please bring cash or your credit card the first day for payment.</p> <p> your Confirmation number is $confId</p> <p> Your total cost including your meal plan option is$$cost</p> <p> We look forward to your participation</p> <ul> END; echo <<<END </ul> END; } else // If errors, display errors { errorMessage($errors); } Thank alot for the help
  22. I want to add to an array when each recursive function is called. I have played around with it a few ways, but just getting error after error. This is about where I am up to, it should be enough to work out what I am trying to accomplish. function structure($x, $structure = array()) { $qry = mysql_query("SELECT `parent_id` FROM `categories` WHERE `categories_id`=$x"); $result = mysql_fetch_assoc($qry); $cat = $result['parent_id']; if($cat !=0) { structure($cat, $structure[] = $cat); } echo $cat.' >'; return $structure; } echo structure(22); var_dump($structure); So I am also trying to return the array as well, unsuccessfully. I am not sure how you return an array from a function either. So I would appreciate help on how to add to an array with each recursive function and return the array outside of the function into a useable variable.
  23. Hey guys! I am trying to achieve the following functionality; Use javascript to display page content that is stored on one page by showing the requested content through the navigation, i.e. clicking the Home link, and making the previous page content invisible. I have been playing around with altering the CSS styling off the div's. I have 3 div's each name; Home, Portfolio and Enquire. Here is the CSS for them; #home { display: block; } #portfolio { display: none; } #enquire { display: none; } So from this the home div is the first that is seen when the page loads. Now using the navigation I have I am calling a function; <nav class="row"> <ul> <li class="above-border"> </li> <li class="nav-smallfont">about</li> <li><a href="javascript:toggle_visibility('portfolio');" alt="Portfolio" target="_self">PORTFOLIO</a></li> <li class="above-border"> </li> <li class="nav-smallfont">back</li> <li><a href="javascript:toggle_visibility('home');" alt="Homepage" target="_self">HOME</a></li> <li class="above-border"> </li> <li class="nav-smallfont">furniture</li> <li><a href="#" onclick="toggle_visibility('enquire');" alt="Enquire" target="_self">ENQUIRE</a></li> <li class="above-border"> </li> </ul> </nav> I was playing around with the difference between onclick and javascript: - I didnt really see any major difference. Now my Javascript is this; <script type="text/javascript"> function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block'){ e.style.display = 'none'; } else{ e.style.display = 'block'; } } </script> Now whenever I click on the home navigation it will show/hide the content and when I click on say, the portfolio link it will show this content as well as the home. Im pretty sure you understand what I am hoping to achieve; A navigation style functionality so that when the portfolio link is click, it hides the other content and show only that and visa versa for the other links. Thanks for your help! Sam
  24. i need to make a php function which will summarize a website content. the idea is to get all those content using Simple html dom parsar , then match some lines with the keyword and return them. i know how to fetch content, but can't understand how to match the keywords with lines, then pick the most matched lines! later, i found this great article http://stackoverflow.com/questions/1195947/best-practices-on-displaying-search-results-with-associated-text-snippets-from-a#1201464 but cant configure! i wish something like this > http://smmry.com/ as a beginning prog. i can't understand how to do this ... pls pls help me
  25. Hey, I am new to learning PHP and I am trying to echo out an array using a function, but its just displaying "array" Can someone please tell me what am i doing incorrectly? Thanks! <?php function get_stores() { $store_array = array(); $stores = array('store1','store2'); foreach ($stores as $store_temp) { $store_array[] = $store_temp; } return $store_array; } echo get_stores(); ?>
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.