PHP - Returning A Variable From A Function.
I have just started using functions, and have been following a few tutorials. I think im misunderstanding returns.
lets say i have the variables called $math1 an $math2 and i want to make $total = $math1 + $math2; i then use return $total; I then thought i could echo $total and it would work outside of the function but its giving me an error of an underfines variable. Could anyone explain what im doing wrong please? thanks Similar TutorialsI'll try to explain this as easily as possible. I'm working on making a little link shortener site just for fun/practice as a beginner with php. I originally used the source code 'lilurl' as a base to start out, but now I'm adding stuff to it for actual practice. I need some help though. I have two files, my index and my external php file. The external file is called on at the beginning of the index with require_once. The user submits a url into the PHP_SELF form and a url is returned, and it works all great. Now I'm trying to add the option to make a custom url suffix. Code: [Select] <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <fieldset> <label for="longurl">Enter a URL:</label> <input type="text" name="longurl" id="longurl" /> <input type="text" name="suffix" id="suffix" /> <input type="submit" name="submit" id="submit" value="Shrink!" /> </fieldset> </form>[/code] The form looks like this. I added the 'suffix' textbox. So after the user submits the code, it goes back up to the top (phpself). A variable is set for the url the user has inputted as "$longurl", like this. Code: [Select] $longurl = trim(mysql_escape_string($_POST['longurl']));So I added this. Code: [Select] $suffix = ($_POST['suffix']);And to check if it worked, I went down the the bottom of the index and had it echo the suffix variable. When I entered in code into the suffix text box, it would be echoed at the bottom of the page, so the variable did receive the value. So here's where the external file comes in. It is called on by require_once at the very beginning of the index. It is full of functions. One of the functions generates a random string of numbers (that I coded) to be used as the url suffix (uses the $id variable). So my plan was to erase the $id = $rand1 . blah blah stuff and put $id = $suffix. $suffix being the variable from the index that the user inputted. Make sense? Well whenever I try it, it always acts the like the variable is empty, even when I echo it on the index it returns the value of the textbox. Does anyone know what I'm doing wrong? Could it be because since I call on $suffix in the external file, and it's only been declared in the index that it's treating it like a new/empty variable? [spoiler] Someone also explained it to me like this. -I call upon the external file. -I declare the variable is the value of the text box. (Which means it's currently empty because the form has not been submitted.) -Then, the form is submitted as PHP_SELF. -The external file is called upon again. -The variable is then assigned a value. It's hard to explain, but basically that the variable in the external file is not told about the new value of the variable because they are declared after the external file is called upon? :\ So I tried moving the $suffix = ($_POST['suffix']); before the external file is called upon, but the same thing happens. It's hard to explain the situation, but I've tried a lot of things and can't get it to work.[/spoiler] Hello all, I'm a PHP newbie, so please pardon me if this question has already been asked somewhere in this forum. I have been reading the PHP documentation. On this page http://www.php.net/manual/en/language.references.pass.php, I came across this code: <?php ... snip ... function &bar() { $a = 5; return $a; } foo(bar()); ?> This is returning a reference to local variable $a. Coming from a C/C++ background, my intuition tells me this just shouldn't work, since the local variable $a should be deleted as soon as the function "bar" returns. The code seems to work, though. My guess is that PHP is basically ref-counting and garbage collecting local variables like $a, and so it will not be automatically cleaned up on call exit. Is this about right? Thanks! WN Code: [Select] //policies subreport function opportunity_sub_report($business_contact_id){ global $edit, $styles; $sql="Select * from opportunities WHERE op_business_contact_id='$business_contact_id'"; $rs=myload($sql); echo '<table>'; if (count($rs)>0){ // print a header row echo '<tr> <td>Opportunity ID</td> <td>Category</td> <td>Agent</td> <td>Opportunity Name</td> <td>Priority</td> <td>Assigned To</td> <td>Opportunity Type</td> <td>Opporunity Status</td> <td>Opportunity Submission</td> <td>Due Date</td> <td>Contracting Recieved(Y or N)?</td> <td>New Business</td> <td>Notes</td> <td>Business Contact ID</td> </tr>'; // print all data rows foreach ($rs as $r){ echo '<tr> <td>'.display_field('', $p,$r['op_id']).'</td> <td>'.display_field('',$p,$r['op_category']).'</td> <td>'.display_field('', $p,$r['op_agent_id']).'</td> <td>'.display_field('', $p, $r['op_opportunity_name']).'</td> <td>'.display_field('', $p, $r['op_priority']).'</td> <td>'.display_field('', $p, $r['op_assigned_to']).'</td> <td>'.display_field('', $p, $r['op_opportunity_type']).'</td> <td>'.display_field('', $p, $r['op_status']).'</td> <td>'.display_field('', $p, $r['op_submission_date']).'</td> <td>'.display_field('', $p, $r['op_due_date']).'</td> <td>'.display_field('', $p, $r['op_contracting_received_y_or_n']).'</td> <td>'.display_field('', $p, $r['op_new_business_app_received_y_or_n']).'</td> <td>'.display_field('', $p, $r['op_wholesaler_notes']).'</td> <td>'.display_field('', $p, $r['op_business_contact_id']).'</td> </tr>'; } } echo '</table>'; } I'm having some trouble with some code I'm tasked with maintaining. This code works, but it doesn't return the information in a tab. I'm using tabber.js It's being called here Code: [Select] echo ' <tr> <td class="timegrid" colspan=5> <div class="tabber"> <div class="tabbertab" title="Contracting"></div> <div class="tabbertab" title="Licensing"></div> <div class="tabbertab" title="Cases"></div> <div class="tabbertab" title="Commissions"></div> <div class="tabbertab" title="Opportunities">'.opportunity_sub_report($rs[0][bc_business_contact_id]).'</div> <div class="tabbertab" title="Tasks"></div> <div class="tabbertab" title="Calendar"></div> <div class="tabbertab" title="Attachments">'.agent_detail_attachments($rec_id).'</div> </div> </td> </tr>'; echo '</table>'; I've tried changing it from echo to return, but I'm not sure how to keep the foreach loop intact in such a way. I'm trying to create subreports in a web app, that would act like access. Any help would be much appreciated. <?php function time_convert($l_timestamp) { $l_timestamp = $l_timestamp * 86400; $time = date('Y-m-d',$l_timestamp); echo(date('Y-m-d',$l_timestamp)); //This does return (date('Y-m-d',$l_timestamp)); //This does not work return $time; // This does not work echo $time; //This does not work } time_convert(32155.0); ?> Can anyone help me, I am not getting the return parameter as I want Hey Guys, I am hoping you can help me find out why a function of mine is only returning 1 record when I am asking for 10. Here is the function I am using to get the data. When I run the $sql that is printed in phpmyadmin.... I get then records. But when I print the $event_data I am only getting 1 record. Any help would be greatly appreciated function get_events($data) { //print_r($data); $lat = $data['lat']; $long = $data['long']; $offset = $data['offset']; $radius = $data['radius']; $amount = $data['amount']; //the events query $sql = sprintf("SELECT *, ( 3959 * acos( cos( radians('%s') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( latitude ) ) ) ) AS distance FROM events WHERE `status` = '0' HAVING distance < '%s' ORDER BY distance LIMIT $amount OFFSET $offset", mysql_real_escape_string($lat), mysql_real_escape_string($long), mysql_real_escape_string($lat), mysql_real_escape_string($radius)); //debugging print_r($sql); $event_data = array(); $event_data = mysql_fetch_array(mysql_query($sql)); //debugging print_r($event_data); return $event_data; } Where is my "Progr" return value?
This is not my first day using php but I don't code in the language that often. I don't understand why my dynamic variable is not returned in AJAX GET? Essentially, I need to give the client a simple UI so that they can copy files to a printer and I wanted to provide a little unfiltered feedback so they knew whether operation was a success. My feedback was just going to be output of exec() function though cleaned up slightly (perhaps replace line breaks with html break tags). PHP version is 5.2.17.17 and cannot be upgraded. Web Server Apache.
PHP dumbed down code:
exec("LoadZPL_PURL.bat", $output); Im trying to understand the code below. (taken from an O'REILLY book) Im trying to get my head around this, so can anyone tell me if im thinking about this in the right way; The function (fix_names) borrows the values from $a1,$a2 and $a3 and puts them into $n1,$n2, and $n3. It then processes the strings contained within these newly created variables and then returns the processed values back into $a1,$a2,and $a3? The variables $n1,$n2, and $n3 cannot be echoed as they were created within the function.? Please correct me if im wrong. Code: [Select] <html> <head> </head> <body> <?php $a1 = "EDWARD"; $a2 = "thomas"; $a3 = "wriGHT"; fix_names($a1,$a2,$a3); echo $a1." ".$a2." ".$a3; function fix_names(&$n1,&$n2,&$n3) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); $n3 = ucfirst(strtolower($n3)); } ?> </body> </html> Hello all, I'm new to PHP and new to this forum (although I have benefitted from your help already -cheers!). However, this time I cannot find the answer I need/recognise/understand.. I have a form and want to conduct tests on each field returning an error message as a session variable if the test fails. The test will be different for some of the fields, and the error message is specific to each field. If there is an error in any one of the fields I want to be redirected to a failure page where all of the error messages are displayed, otherwise I am sent on to another page. I have already written and tested a function to sanitise the incoming form data, so that's not a problem - it's just how to loop through and test. I can guess that there are many ways to do this but I need to understand why one option is better than another, and follow the syntax used (it's all part of my steep learning curve) The approach I have thought to use is to create an array holding the field name, the test and the message, then loop through using foreach, applying the array values into the test and creating the error message....but it's not working for me. The other method is to declare a variable $Stop='No' and if the loop identifies an error, part of the output is to change this to 'yes' and through that redirect to the error page. I'd really welcome your advice and tuition....cheers.. my code so far is... Code: [Select] $Stop='No'; $StaffPassCheck=sanitisealphanum($_POST['PasswordCheck']); $Errors[0]['value']= sanitisealphanum($_POST['FirstName']); $Errors[0]['message']='Please re-enter your name'; $Errors[0]['test']=($StaffFname=""); $Errors[1]['value']= sanitisealphanum($_POST['Surname']); $Errors[1]['message']='Please re-enter your surname'; $Errors[1]['test']=($StaffSname=""); $Errors[2]['value']= sanitisealphanum($_POST['Post']); $Errors[2]['message']='You must select an option'; $Errors[2]['test']=($StaffPost="Select Value"); $Errors[3]['value']= sanitisealphanum($_POST['Username']); $Errors[3]['message']='You must select an option'; $Errors[3]['test']=($StaffUser=""); $Errors[4]['value']= sanitisealphanum($_POST['Password']); $Errors[4]['message']='Please re-enter your password'; $Errors[4]['test']=($StaffPass=""); $Errors[5]['value']= sanitisealphanum($_POST['PasswordCheck']); $Errors[5]['message']='Sorry, your passwords do not match'; $Errors[5]['test']=($StaffPass===$StaffPassCheck); foreach ($Errors as $key => $Value){ if ( $Errors['test']=true ){ $Stop='Yes'; return $_SESSION[$key]=$Value['message']; } } if ($Stop='Yes'){ header('Location.test.php'); die(); }else{ header('Location.indexp.php'); } Moodle 2.5 *nix server Theme: Essential ---------------------- Hi Folks I have a small mind bender in how php is returning results from a mysql query. There are two issues: 1) The mysql query from phpmyadmin is correct, while the php function that handles the query from the website is not. 2) It takes a very long time to run this query with php, 30 seconds to over a minute. Phpmyadmin is rather quick (Query took 0.0239 seconds). The query is: SELECT u.firstname AS 'Name' , u.lastname AS 'Surname', c.shortname AS 'Course', ( CASE WHEN gi.itemname LIKE '%summative%' THEN 'SUMMATIVE' WHEN gi.itemname LIKE '%formative 2%' THEN 'FORMATIVE 2' ELSE 'MC' END) AS 'Assessment', from_unixtime(gi.timemodified, '%d/%m/%y') AS 'Date', IF (ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) > 70,'Yes' , 'No') AS Pass, ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) AS 'Mark', ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) AS 'Mark' FROM mdl_course AS c JOIN mdl_context AS ctx ON c.id = ctx.instanceid JOIN mdl_role_assignments AS ra ON ra.contextid = ctx.id JOIN mdl_user AS u ON u.id = ra.userid JOIN mdl_grade_grades AS gg ON gg.userid = u.id JOIN mdl_grade_items AS gi ON gi.id = gg.itemid JOIN mdl_course_categories AS cc ON cc.id = c.category WHERE gi.courseid = c.id AND gi.itemname != 'Attendance' AND u.firstname LIKE '%03%' AND gi.itemname LIKE '%mative%' ORDER BY `Name` , `Surname` , `Course`, `Assessment` ASCWhen I run the query in phpmyadmin , it gives back; Name Surname Category Module Course Assessment Date Competent Mark G03 Itumeleng Velmah Mokwa Fundamentals Communications CO1 119472 FORMATIVE 2 07/04/14 Yes 100.00 G03 Itumeleng Velmah Mokwa Fundamentals Communications CO1 119472 SUMMATIVE 07/04/14 Yes 100.00 G03 Itumeleng Velmah Mokwa Fundamentals Communications CO2 119457 FORMATIVE 2 05/04/14 Yes 100.00 G03 Itumeleng Velmah Mokwa Fundamentals Communications CO2 119457 SUMMATIVE 05/04/14 Yes 88.00 G03 Lally Sheila Mokane Fundamentals Communications CO1 119472 FORMATIVE 2 07/04/14 NYC 59.00 G03 Lally Sheila Mokane Fundamentals Communications CO1 119472 SUMMATIVE 07/04/14 Yes 90.00 G03 Lally Sheila Mokane Fundamentals Communications CO2 119457 FORMATIVE 2 05/04/14 Yes 100.00 G03 Lally Sheila Mokane Fundamentals Communications CO2 119457 SUMMATIVE 05/04/14 Yes 98.00And it is perfect so I have no issues with that. Now in php I call; function print_overview_table_groups($COURSE, $choosegroup, $fromdate, $todate, $numarray) { global $DB; //check data if(!$choosegroup){ die('No Records To Display.'); } $thisgroup = $numarray[$choosegroup]; $sql = "SELECT DISTINCT u.firstname AS 'Name' , u.lastname AS 'Surname', (CASE WHEN cc.parent = '2' THEN 'Fundamentals' WHEN cc.parent = '3' THEN 'Core' WHEN cc.parent = '4' THEN 'Elective' END) AS 'Category', cc.name AS 'Module', c.shortname AS 'Course', (CASE WHEN gi.itemname LIKE '%summative%' THEN 'SUMMATIVE' WHEN gi.itemname LIKE '%formative 2%' THEN 'FORMATIVE 2' ELSE 'MC' END) AS 'Assessment', from_unixtime(gi.timemodified, '%d/%m/%y') AS 'Date', IF (ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) > 70,'Yes' , 'NYC') AS Competent, ROUND(gg.finalgrade / gg.rawgrademax * 100 ,2) AS 'Mark' FROM mdl_course AS c JOIN mdl_context AS ctx ON c.id = ctx.instanceid JOIN mdl_role_assignments AS ra ON ra.contextid = ctx.id JOIN mdl_user AS u ON u.id = ra.userid JOIN mdl_grade_grades AS gg ON gg.userid = u.id JOIN mdl_grade_items AS gi ON gi.id = gg.itemid JOIN mdl_course_categories AS cc ON cc.id = c.category WHERE gi.courseid = c.id AND gi.itemname != 'Attendance' AND u.firstname LIKE '%03%' AND gi.itemname LIKE '%mative%' ORDER BY `Name` , `Surname` , `Course`, `Assessment` ASC"; return $DB->get_records_sql($sql); }This is returned to the index.php page from the function call; $lists = print_overview_table_groups($COURSE, $choosegroup, $fromdate, $todate, $numarray); print "<pre>"; print_r($lists); print "</pre>";The result is baffling... Array ( [G03 Itumeleng] => stdClass Object ( [name] => G03 Itumeleng [surname] => Mokwa [category] => Fundamentals [module] => Communications [course] => CO2 119457 [assessment] => SUMMATIVE [date] => 05/04/14 [pass] => Yes [mark] => 88.00 ) [G03 Lally] => stdClass Object ( [name] => G03 Lally [surname] => Mokane [category] => Fundamentals [module] => Communications [course] => CO2 119457 [assessment] => SUMMATIVE [date] => 05/04/14 [pass] => Yes [mark] => 98.00 ) )I only get one record for each student. Can anyone help me solve this? Regards Leon Hi I am new to php, I am trying to capture the url and place into a variable but I only get the 1st digit to show, I just cant see what I am doing wrong. Sorry to ask such a basic question but I just can't work it out, I have attached a screen shot of all me code, your help would be very very much appreciated. Hello all, I have some piece of code that is nested like this $variable = 'This is a global argument'; function parentFunction($variable) { function childFunction() { echo 'Argument of the parent function is '.$GLOBALS['variable']; } childFunction(); } parentFunction(5); What I want to know is - Is there a way to access a variable from the parent function without passing arguments to the child function? (Something like how classes have parent::?). I don't want to use $GLOBALS because it might cause some variable collision, and I didn't want to pass arguments because incase I decide to change the arguments in the parent function I'd have to do it in the child function aswell. From my searching around in the Internet it seems like this is not possible, but if theres a slight chance that there might be something out there, i'm willing to give it a shot . Thanks in advance I want to define a function instead of repeating query in all my php pages. I call a function by passing an $id value and from that function i have to get all the info related to that id, like name, description and uom.
I am trying to do this, but i dont know how to get these values seperately.
here is my function
function items($item_id) { $details = array(); $result = mysql_query("select item_id, name, uom, description from items where item_id=".$item_id."") or die (mysql_error()); while($row = mysql_fetch_array($result)) { $details[] = array((stripslashes($row['name'])), (stripslashes($row['uom'])), (stripslashes($row['description']))); } return $details; }and i call my function like this $info = items($id);Can somebody guide me in this I have a function that get's a quick single item from a query: function gimme($sql) { global $mysqli; global $mytable; global $sid; $query = "SELECT ".$sql." FROM ".$mytable." WHERE sid = ".$sid; $result = $mysqli->query($query); $value = $result->fetch_array(MYSQLI_NUM); $$sql = is_array($value) ? $value[0] : ""; return $$sql; // this is what I've tried so far $result->close(); } It works great as: echo(gimme("name")); Then I realized that I could use that as a variable ('$name' in this case) elsewhere. However, I can't figure out how get that new, variable variable 'outside' of the function. As such, echo($name); isn't working outside the function. Is there a way to return a variable variable? In other words, is there a way to make a function that creates a variable variable that will available outside of the function?
Thanks
I am using two diffrent databases in my php system, MySQL and MSSQL. my issue is i need a list of results from a MySQL query to be part of a Where clause in the MSSQL query. I cant put the the MSSQL query in the while section of the MySQL query as i need to sort by the results of the MSSQL query. if i do the MySQL query and then use the info from that in the MSSQL query I get only one result. so i decided to make it a function. how ever i need to know how to make the function into a variable so i can input it in the MSSQL query. Hope this all makes senes. heres what i have that is not working . function somefunction($vaiable) { $gers = mysql_query(sprintf("SELECT emp_id, lastname FROM info WHERE active='1' AND oid='$oid' AND pidnumber='4'")) or die(mysql_error()); while ($gerow = mysql_fetch_array($gers)) { echo "ci.attorney='$lastnamey' OR "; } } $attlist = getattorney($vaiable); echo $attlist; $rscw=odbc_exec($conn, sprintf("SELECT ci.attorney, SUM(ci.totalweight) AS 'citw' FROM info ci, clients cl WHERE ci.ID = cl.ID AND (cl.county = '$xca' OR cl.county ='$xcb' OR cl.county ='$xcc' OR cl.county ='$xcd') AND ($attlist ci.attorney='xyz') GROUP BY ci.attorney ORDER BY citw DESC")) or die (odbc_errormsg()); while (odbc_fetch_row($rscw)) { echo odbc_result($rscw,"attorney"); echo odbc_result($rscw,"citw"); } is there a way to make a function be defined as a variable? Any help is appreciated i want to use a variable that is created inside of a function in another function some thing like this function show_category ($cats, $index, $level) { global $categories_use_categories_top_only; $categories_use_categories_top_only='no'; . . $catRow = '<tr class="scPL-' . $level . '">' . "\n" . '<th colspan="' . PL_COLCOUNT . '">' . $cats[$index]['categories_name'].'<br><i>'. $categories_use_categories_top_only . '</i><br><i>'. $cat_top . '</i></th>' . "\n" . '</tr>' . "\n"; return $catRow; } function show_product ($cats, $cat_index, $prod_index) { global $categories_use_categories_top_only; . . if ($categories_use_categories_top_only=='no' ) { include(DIR_WS_MODULES . 'options.php'); } . . i want to use $categories_use_categories_top_only which its value determined in the first function in the second function as i showed. the first function acts correctly how can i do this? Code: [Select] class replayer extends users { --SNIP-- public $islive = false; --SNIP-- function chat($id, $nick, $chat) { --SNIP-- <----------- } } There's my code, I want to take the variable $islive from the above class and use it in the chat() function. How would I do it? I've tried making it a global inside of the chat() function. Hello I have a question (that i think i know the answer to). What would be more efficient: 1. Create a global variable and run a php function and store result in there and call back the variable when needed 2. just echo the return value of the function when needed Now im guessing that calling the function once and storing that in a variable rather than keep calling the function is more efficient 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 I dont know why I'm having so many problems with this. I need to get a variable that defined in an included file inside of a function I've got this Inside file.php I've got the $variable1 and $variable2 defined (they're dynamic/different to each user) include('file.php'); function foo() { GLOBAL $variable1, $variable2; echo $variable1; echo $variable2; } foo(); Yet it outputs nothing? If I Include file.php right inside of the function it works however. Any idea? Hi, Im trying to pass a variable ($in_this_instance) into, and then back out of a function. The variable goes into the function no problem, and is echo'ed out fine. However the echo after the close of the function, does not give anything out. Code: [Select] $in_this_instance = 'boo'; function in_this_instance($data) { global $in_this_instance; echo $in_this_instance; $in_this_instance = 'hoo'; $rep_val = '[front banner]'; $test = strpos($data, $rep_val); if ($test === false) { return $data; } else { return $data;; } } add_filter('the_content', 'in_this_instance'); echo $in_this_instance; Could any one give me a pointer please? Many Thanks! |