PHP - Functions?
i am wondering what the '@' is used for when used in front of a function like
Function(@$VAR); What is the benefit of the @? Similar TutorialsI have a script I am putting together that simulate a cricket game. The only issue is, that there are a huge number of functions because there doesn't seem to be any other way to do this properly. As well as this, there a while() loop and all this seems to be leading to the page reaching a max 30 second timeout when generating the result. My code is attached below, it is quite messy at the moment because i've just be working on it, but I was wondering if anyone has any solutions of how I can speed this up or change to prevent a timeout: <?php // Error reporting error_reporting(E_ALL); // Connect DB mysql_connect("wickettowicket.adminfuel.com", "rockinaway", "preetha6488") or die(mysql_error()); // Select DB mysql_select_db("wickettowicket") or die(mysql_error()); // MySQL queries to find batsmen and bowlers $array_batsmen = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 1 ORDER BY id ASC'); $array_bowlers = mysql_query('SELECT id, name, ability, strength FROM wtw_players WHERE team_id = 2'); // Start table for data $data = '<table width="600px">'; // Create blank scorecard while ($array_bat = mysql_fetch_array($array_batsmen)) { $data .= '<tr><td>'.$array_bat['name'].'</td><td></td><td></td><td>0</td></tr>'; } // Set up arrays for players $current_batsman = $current_bowler = array(); // Reset query mysql_data_seek($array_batsmen,0); $in_one = $in_two = $it = ''; function currentBatsman($id, $name, $ability, $strength, $out, $in, $runs) { global $current_batsman; $current_batsman = array ( 'id' => $id, 'name' => $name, 'ability' => $ability, 'strength' => $strength, 'out' => $out, 'in' => $in, 'runs' => $runs ); echo 'set current'; } // Set up arrays of batsmen while ($array = mysql_fetch_array($array_batsmen)) { if ($it < 3 && $in_one == '') { currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_one = $array['id']; $current = $array['id']; $it++; } else if ($it < 3 && $in_two == '') { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 1, 'runs' => 0 ); $in_two = $array['id']; $it++; } else { $batsmen[$array['id']] = array ( 'id' => $array['id'], 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'], 'out' => 0, 'in' => 0, 'runs' => 0 ); } } // Bowler Array while ($array = mysql_fetch_array($array_bowlers)) { $bowlers[] = array ( 'name' => $array['name'], 'ability' => $array['ability'], 'strength' => $array['strength'] ); } // Reset both queries mysql_data_seek($array_bowlers,0); mysql_data_seek($array_batsmen,0); function changeBatsman($just_out) { global $array_batsmen, $batsmen; //Update array $batsmen[$just_out] = array ( 'in' => 1, 'out' => 1 ); while ($array = mysql_fetch_array($array_batsmen)) { if ($just_out != $array['id'] && $batsmen[$array['id']]['out'] != 0) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'change batsman'; } function swapBatsman($other_batsman) { global $array_batsmen, $batsman; while ($array = mysql_fetch_array($array_batsmen)) { if ($other_batsman != $array['id'] && $batsman[$array['id']]['out'] != 0 && $batsman[$array['id']]['in'] == 1) currentBatsman($array['id'], $array['name'], $array['ability'], $array['strength'], 0, 1, 0); } // Reset query mysql_data_seek($array_batsmen,0); echo 'swap batsman'; } $runs = $outs = $balls = $overs = 0; $played = array(); function selectBowler() { global $bowlers, $current_bowler; // Select random bowler $choose_bowler = array_rand($bowlers, 1); $current_bowler = array ( 'name' => $bowlers[$choose_bowler]['name'], 'ability' => $bowlers[$choose_bowler]['ability'], 'strength' => $bowlers[$choose_bowler]['strength'] ); } /* function selectBatsman(); { global $array_batsmen; while ($array_batsmen[]['out'] != 1) { }*/ function bowl() { global $batsmen, $bowlers, $current_bowler, $current_batsman, $data, $balls, $outs, $runs; if ($current_batsman['out'] == 0) { echo 'bowling'; // Set the initial number $number = rand(0, 190); // Ability of batsman if ($current_batsman['ability'] > 90) $number += 30; else if ($current_batsman['ability'] > 70) $number += 15; else if ($current_batsman['ability'] > 50) $number += 2; else $number = $number; // Strength of batsman if ($current_batsman['strength'] > 90) $number += 15; else if ($current_batsman['strength'] > 70) $number += 10; else if ($current_batsman['strength'] > 50) $number += 5; else $number = $number; // Depending on overs if ($balls > 270) $number += 30; else if ($balls > 120) $number -= 10; // Ability if ($current_bowler['ability'] > 90) $number -= 30; else if ($current_bowler['ability'] > 70) $number -= 15; else if ($current_bowler['ability'] > 50) $number -= 2; else $number = $number; // If batsman has made a huge total of runs, we need to knock some numbers off - more likely to get out if ($current_batsman['runs'] > 200) $number -= 70; else if ($current_batsman['runs'] > 100) $number -= 30; // Finally sort out runs if ($number > 190) $run = 6; else if ($number > 170) $run = 4; else if ($number > 160) $run = 3; else if ($number > 100) $run = 2; else if ($number > 50) $run = 1; else if ($number > 10) $run = 0; else if ($balls > 120 && $number > 0) $run = 0; else $run = -1; // Increase number of balls $balls += 1; // Are they out? if ($run == -1) { $current_batsman['out'] = 1; $played[] = $current_batsman['id']; $find = '<tr><td>'.$current_batsman['name'].'</td><td></td><td></td><td>0</td></tr>'; $replace = '<tr><td>'.$current_batsman['name'].'</td><td></td><td>'.$current_bowler['name'].'</td><td>'.$current_batsman['runs'].'</td></tr>'; $data = str_replace($find, $replace, $data); changeBatsman($current_batsman['id']); echo 'out'; } else { $current_batsman['runs'] += $run; $runs += $run; if ($run == 1 || $run == 3) { swapBatsman($current_batsman['id']); echo 'time to swap'; } echo $run; } // Count outs if ($current_batsman['out'] == 1) $outs += 1; } } function game() { global $main, $batsmen, $bowlers, $data, $batted, $balls, $outs, $current_batsman; // Check if possible while ($balls <= 295 && $outs < 10) { selectBowler(); // Actually bowl now bowl(); } } game(); echo $data; I teaching myself php, but I am coming from java and other compiled languages, so the process has been a little bumpy. I am trying to do something like this: Code: [Select] class my_class { function one () { $two = two (); $three = three (); $five = $two + $three; return $five; } function two () { $two = 2; return $two; } function three () { $three = 3; return $three; } } Unfortunately, I keep getting an error message saying that my call to two () is an undefined function. I am gathering from this that the scope of one () is not aware of the existence of two (). Is there a way to get around this so I can call two () and three () from one ()? Hi, I could use a little guidance here. 1) is a function with values to be sent to 2). 1) <!-- use ajax - OnCalc function to send data to your database. --> function OnCalc(value1,op,value2,total) { 2) php file using above function values <?php header( "refresh:5;url='http://localhost/hom...lcprint.php'"); echo 'You\'ll be redirected in about 5 secs. If not, click <a href="http://localhost/hom...hp">here</a>.'; echo '<script type="text/javascript">' , 'OnCalc();' , '</script>'; No error but code not working? OK, so if I've got this in my one of my class files: public function userr($user) { $thisquery = mysql_query("SELECT * FROM users WHERE username='". $user ."'"); if(mysql_num_rows($thisquery) == 1) { return true; } return false; } Could I use something like this: if($class->userr($user)) { // Something } If not, how would I go about doing something like it? And is there any way I could use a mysql_fetch_assoc in a function? Hi, I've got 3 different upload forms in one form. I'm making a function so it just one piece of code. I'm having a bit of a problem changing some of the code so it works for all 3. Here is the function function loadImages ($action, $position) { $link = mysql_connect("","",""); if (!$link) { die('Error: could not connect: ' . mysql_error()); } $db_select = mysql_select_db("",$link); if (!$db_select) { die ("Error: database selection failed: " . mysql_error()); } $page = ($_POST["pageName"]); if ((($_FILES["bfile"]["type"] == "image/gif") || ($_FILES["bfile"]["type"] == "image/jpeg") || ($_FILES["bfile"]["type"] == "image/pjpeg")) && ($_FILES["bfile"]["size"] < 9000000)) { if ($_FILES["bfile"]["error"] > 0) { echo "Return Code: " . $_FILES["bfile"]["error"] . "<br />"; } else { $success = '<p style="font-weight: bold; color: #C00">Upload successful<br />'; // move uploaded temporary file to final destination move_uploaded_file($_FILES["bfile"]["tmp_name"], "uploads/" . $_FILES["bfile"]["name"]); // update database with new filename $filename = $_FILES["bfile"]["name"]; $sql = "UPDATE images SET filename= '$filename' where page = '$page' and position = '$position'"; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } } } else { $fail = '<p style="font-weight: bold; color: #C00">Invalid file'; } mysql_close($link); } Now the $action is the bit that will determine whether it's updateTop updateMiddle or updateBottom. $position finds out if it's top middle or bottom if (isset($_POST['updateTop'])) { loadImages ($_POST['updateTop'], "top"); } Here is a sample of the html, it's in a switch case "Products": echo "<p>Image Top</p> <input type=\"file\" name=\"file\" id=\"file\" /> <input type=\"submit\" name=\"updateTop\" value=\"Update $page Top\" /> <p>Image Middle</p> <input type=\"file\" name=\"mfile\" id=\"mfile\" /> <input type=\"submit\" name=\"updateMiddle\" value=\"Update $page Middle\" /> <p>Image Bottom</p> <input type=\"file\" name=\"bfile\" id=\"bfile\" /> <input type=\"submit\" name=\"updateBottom\" value=\"Update $page Bottom\" /> "; break; What I need to do is get $_FILES["bfile" into a variable to see whether it's "bfile" "mfile" or "file" but not sure how to write it. Thanks for the help. Hi. I am trying to write a function but they are new to me and confusing me. On multiple pages I am requesting users details. I thought instead of writing out the query every time I want to do this I would include a functions page with the query in it. The only variable I carry from the user is the user name as a session when they log in. The user name is the email address of the person signed in. so here is my first function. As im sure you can see it doesn't work but I don't understand why or how to call it properly. Can someone please explain.... function GetUser($user = "") { $qFindUser = "SELECT * FROM members WHERE email = '$user'"; $rFindUser = mysql_query($qFindUser) or die (mysql_error()); $UserInfo = mysql_fetch_array($rFindUser); } calling the function to return all details of a member as an array. <?php $Name = $_SESSION['MM_Username']; $UserInfo = GetUser($Name); echo $UserInfo['forename']; ?> Hey guys. Can anyone tell me what this means? function foo { } It is basic php but I don't get it. Should it be called for execution, or does it work automatically, or both? The php manual at w3schools and php.net are too tough for me. That's why I posted here. Thanks! I have a function to get some data from the database. However it always comes back with: Code: [Select] Notice: Undefined variable: db in C:\wamp\www\ASF A Simple Forum\functions\functions.php on line 233 Fatal error: Call to a member function query() on a non-object in C:\wamp\www\ASF A Simple Forum\functions\functions.php on line 233 here is the code: require_once(ASF_ROOT."includes/init.php"); // this is where the db connection is function get_db_info($type, $select, $table, $where="", $order="DESC", $limit="") { if (empty($type) || empty($select) || empty($table)) { try { throw new emptyArgs(); } catch (emptyArgs $invalid) { echo "<div style=\"border:1px solid #f00; padding:5px; width:350px; line-height:10px;\">"; echo "<b>$invalid</b>"; echo "<p>get_info() needs atleast 3 arguments (Type, Select and Table) - none supplied</p>"; echo "</div>"; } } else { if ($type == "num") { $query = $db->query(" SELECT $select FROM ".TBL_PREFIX."$table $where $order $limit ") or die($db->error()); $result = $db->num_rows(MYSQLI_NUM); return $result; } else { $query = $db->query(" SELECT $select FROM ".TBL_PREFIX."$table $where $order $limit "); $result = $query->fetch_array(MYSQL_ASSOC); return $result; } } } I have a function for mysqli_real_escape_string above this function and it works with no errors. Have i done something wrong? as you can see i am including the file which holds the connection but it doesnt seem to use it. every other file that uses the connection works fine. When in OOP I have been watching tutorials and some have functions just written like Code: [Select] class user { public $user; public function __construct($u) { $this->user = $u; } } do I need to type public before the function or is it better practice to just put Code: [Select] class user { public $user; function __construct($u) { $this->user = $u; } } Thanks! Can someone tell me by looking at the following code why function pcust() does not work, I am new to programming? Code: [Select] $firstname = "chris"; $surname = "reynolds"; $address1 = "12 birch end"; $town = "Wallington"; $county = "surrey"; $postcode = "wh20 3bg"; $telephone = "01372 854785"; $cust_details = fix_cust($firstname, $surname, $address1,$town, $county, $postcode, $telephone ); function fix_cust($n1, $n2, $n3, $n4, $n5, $n6, $n7) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); $n3 = ucwords(strtolower($n3)); $n4 = ucfirst(strtolower($n4)); $n5 = ucfirst(strtolower($n5)); $n6 = ucfirst(strtoupper($n6)); $n7 = ucfirst(strtolower($n7)); return array($n1, $n2, $n3, $n4, $n5, $n6, $n7); } echo $cust_details[0] . " " . $cust_details[1]; echo "<br />"; echo $cust_details[2]; echo "<br />"; echo $cust_details[3]; echo "<br />"; echo $cust_details[4]; echo "<br />"; echo $cust_details[5]; echo "<br />"; echo $cust_details[6]; echo "<br />"; function pcust(){ $length = count($cust_details ); for ($i = 0; $i < $length; $i++) { echo $cust_details[$i]; echo "<br />"; } } pcust(); As painfully simple as this may be, I seem to be doing something wrong as always. New to php and decided to start using functions. I'm trying to add functions from an external functions.php file to my other pages and then call the functions where necessary. How should I go about it? I tried something like this: Functions.php: Code: [Select] <?php function field() { echo 'text heherh'; } ?> and then when calling it to when needed for example: include 'includes/functions.php'; // at the top of the page Code: [Select] <?php // and when trying to call the function on a specific line if (!$sname) $errorstring = $errorstring . "<b>Surname:" . field() ; //field being the function name ?> I know this is very simple but I have never used functions before.. tried google, didn't help much and I'm pressed for time so decided to ask here. Thanks in advance I have a database that holds a list of companies. the database includes and ID, and name of each company. Now when an articles gets submitted to my site it can then be related to company. We a relate a company to an article its related through its ID. What I want to do is create a function that would let me easly convert my company ID into company name within having to write out the queries over and over again in my code. Only problem is I can't get it to work. I have two files, index.php and functions.php. functions.php Code: [Select] function cname($pubid) { global $db; $company= $db->query("SELECT * FROM my_database WHERE id='$pubid'") or die(mysql_error()); while($company= $db->fetch_array($company)) { $cname = $company['name']; } return $cname; } and within index.php I put Code: [Select] echo cname($companyID); Now, when I first looked at index.php I was getting an error. I know it had something to do with me using my variables within the function and after some searching I ended up getting rid of the error by adding "global $db;" to my code. Please note that I include functions.php at the top of index.php. What am I doing wrong and why wont it work? HELP PLEASE! also note that my i've rechecked and all the database info is correct and names spelt right. Just dont know what else to do. i have been searching for a solution for about a day already. can anyone help me on how to use the http functions (if thats what it is called) in php? http://www.php.net/manual/en/book.http.php like for example. i need to use the http_get() function but it returns Fatal error: Call to undefined function.. in the manual it says that i need to put php_http.dll on the ext dir and enable it in php ini like this.. extension=php_http.dll ..which i already did im working under.. windows xp sp3 php 5.3.1 thanks guys I wonder if is out there function in php that is doin this . function like strpos that is does not notice from CAPITAL words to small words. function like strpos that does finds all matchs and not only 1. function like strpos that is search inside connected words like "strposfunction" so if i search "function" it will find it. thanks , Mor. Hey , I'm looking for functions names from the GD directory. 1.function that open image. 2.function that getting pixel color. 3.function that changing pixel color. thanks. I have some variables that I have set with the global command but they don't seem to be working correctly. It's probably my order of operation but not sure. Here's the stripped down version of whats going on: locator() //functions function geoip() global $zip, $city, $areacode, $metrocode, $state, $country, $latitude, $longitude; function locator() geoip() use globals from geoip pass to- ad_display() function ad_display() does some work stat_tracking() function stat_tracking() access global $zip, $city, $areacode, $metrocode, $state, $country, $latitude, $longitude; The problem is once I call stat_tracking() and try to access the global variables, they are all empty. Just to clarify the chain of events is: page loads, calls locator(), locator() calls function geoip() fine then passes work to ad_display(), ad_display() calls stat_tracking(), stat_tracking() now tries to access the globals I made but all variables are blank if I echo them. Any ideas? Hi, I develop some functions in PL/SQL and PL/PgSQL. In these languages are IN and OUT parameters in Functions and Store Procedures. There is IN and OUT parameters in PHP Functions? Sorry my bad english. Best Regards, Hi there. How do I stop a function from running it it's taking to long to proccess. For example, say after 10 seconds the code is still working I display an error message? As you can in the following code it's pulling the contents from an url or file which might take too long to load. function Tester($url); { return file_get_contents($url); } Thanks a mil Greetings. First time poster looking for some PHP help if it can be provided, because I'm confused as hell. First off, I'll explain my situation. I'm the IT technician of a small business tasked with ensuring the business' computers and website are running in top shape. I originally joined as a Data Entry clerk to post products to the business' website, but got promoted when they original IT technician left town to pursue his PhD. Before he left, he taught me a few things to prepare watching over the website as my new duty, including some PHP and MySQL. Now, a few months after he's left, I have the glorious task of trying to move our website to a new host because we've apparently outgrown our original host's capabilities. And being based on PHP with a MySQL database, it's turning out to be OH-so-fun. So far, I've managed to download our entire website from the old host and given it to our new host to put up as a testing site, to ensure everything works before we switch hosts. And for the most part, a lot of it has come together nicely, but there's still work needed to be done. And thus we come to the problem I hope someone here can help with. Our website has two back-end Admin sections, an older one that used to handle everything, and a newer one that's sleeker but still reads off a lot of data from the older one to work properly. Normally, when you access those sections, you need to log in first. Now, in the testing site, when I access those areas, the header of each of those sections now reads <?= $row[title] ?> and if I attempt to log in as normal, it just flashes back to the login page with the fields now cleared of what I typed in. When I asked about this to see what the problem might be, the new host said it might "at least two misconfigurations on the new server relative to the old server". So, I've been trying to Google for some help with PHP Configuration Functions, but I don't know if what I'm reading will help me fix the problem. Would anyone here happen to know what they might mean in this case, because my knowledge of PHP is fairly limited beyond what I was taught to keep the website in order without considering a host change... Thanks to those who help or can direct me to a place that helps! i know how to use spl_autoload_functions, spl_autoload_register, spl_autoload_unregister. but i want to know where and how to use the functions , such spl_autoload, spl_autoload_call, spl_autoload_extendsions. my understanding is spl_autoload_entendions can return the current list of extensions each separated by comma, and also i can set the extension. if i set the extension . That how it working. |