PHP - Use Variable Outside Of Function
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? Similar TutorialsHello 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 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! 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 Hi All, I have a function that i want to pass a variable into so that i can do some SQL on it. The information that i want to pass into it is a data-id on a button that is used to trigger the function. The button that will be clicked is this <div class='modaltrigger btn btn-primary' data-id='$itemId' data-toggle='modal'>Manage</div> This button is being created by another function. I would like to know either how i pass the variable from one function to another or how i pass it from the data-id to the function in php. Thanks in advance. 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 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. Hi guys, I have a trouble with my php snippet, when I insert the var function in the url bar something is like: http://www.mysite.com/delete.php?favorites&id=0 or http://www.mysite.com/delete.php?whateveritis&id=0 It doesn't get pass the favorites function to delete the id. It is the same things that it goes for each different function. Here's the current code: <?php Code: [Select] session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbuser'); define('DB_PASSWORD', 'mydbpass'); define('DB_DATABASE', 'mydbtablename'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $favorites = clean($_GET['favorites']); $id = clean($_GET['id']); if($favorites && $id == ''){ // both are empty $errmsg_arr[] = 'favorites id are missing.'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $insert = array(); if(isset($_GET['id'])) { $insert[] = 'id = \'' . clean($_GET['id']) .'\''; } if(isset($_GET['favorites'])) { $insert[] = 'favorites = \'' . clean($_GET['favorites']) . '\''; } if($favorites && $id) { mysql_query("DELETE FROM favorites WHERE id='$id'"); $deleted = mysql_affected_rows(); if($deleted > 0) { echo "favorites channels is deleted"; } else { echo("favorites is already deleted"); } } } ?> If you do know how to get pass the favorites function, then please say so as i need your help. Any advice would be much appreicated. This seems really straight forward but I can't figure out why it's happening. As a part of an account registration script, I'm randomly generating a password using a function called, generatePassword($length,$strength); I hash the password (md5) before putting it in the database but I also email the non-hashed version to the user. My problem is that each time I call the variable, it generates a new password so the one in the database does not match the one received by the user, $user_password_plain = generatePassword($length,$strength); $user_password = md5($user_password_plain); Is there a different way to store the variable so that I can access it later in the script and it will be the same? I tried using a session variable but that didn't seem to work either. Thanks! 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 Hello, I have been trying to replace a variable's value inside a function in case it matches a certain criteria but I can't seem to get it right. Let me give an example: Code: [Select] <?php function replace_value($obj) { if($obj==1) { $obj=2; } } $number = 1; replace_value($number); echo $number; So how do I go about making $number = 2, because it still has a value of 1 even after I pas it through the function replace_value. Hi, I'm having an image upload function I did create for few weeks ago - it has an variable called $newname, which contains the path and file. I'm then using the imageupload() function in another function called EditFrontPage(), which is used to 'update' some content. If I update the image, it runs the imageupload function, which is great, it resize and optimize the image, and it moves it to the folder I specified. What I then want, is within' my EditFrontPage() function, is to echo out the $newname variable from the imageUpload function. is there a way to do this? in a smart way? If my code is needed, you can take a look at it he http://codepad.org/poKNSU5H Thank you a lot guys! I am currently using a javascript to redirect the page using a select tag and the onchange property. Each page calls a different function. I want to be able to pass the <select> value to a variable that I can use within a php condition statement on the same page. This will generate the required output based on the <select> value. This way I dont require a seperate page for each query. So onchange.... $select_value == this.value? Then within my page: Code: [Select] if ($select_value == 'alpha') { get_query_alpha(); } if ($select_value == 'bravo') { get_query_bravo(); } This is my current set up... Code: [Select] <p>Order by: <select name="query" id="query" onchange="gotourl(this.value)"> <option value="query1.php" >Sort by A</option> <option value="query2.php" >Sort by B</option> <option value="query3.php" >Sort by C</option> <option value="query4.php" >Sort by D</option> </select></p> <table> <?php get_query_1();?> </table> and js... Code: [Select] function gotourl(url){ window.location= url; } function selectsubject(){ alert("Please select a subject!"); } Is there a simple way to do this? Thanks. Hello guys, basically i am doing a search function based on regular expressions. What i have done is to store the string i want to regex as a variable. Variable is named as $new_string -> preg_split("/\.\(.*\)\.\(.*\)/", $file); So inside the while loop, i would like to call another variable to store $new_string. However, I found out that the preg_split function stored inside $new_string doesn't work. If i use preg_split function directly inside the while loop it will work - > refer to //$parts = preg_split("/\.\(.*\)\.\(.*\)/", $file); I have troubleshooted it for like 1 hour plus.hope someone can help me thanks <?php //"$DOCUMENT_ROOT"."new/"; $current_dir = 'C:\xampp\htdocs\Audit_Reports'; //Put in second part, the directory - without a leading slash but with a trailing slash! $dir = opendir($current_dir); // Open the sucker $newArgument = $_POST[argument]; $newArgument1 = $_POST[argument1]; $string ='preg_split("/\.\(.*\)\.\(.*\)/", $file);'; $new_string = preg_replace("#\/\\\.\\\\\(\.\*\\\\\)#","/\.\\($newArgument\)",$string); $new_string = preg_replace("#\\\.\\\\\(\.\*\\\\\)#","\.\\($newArgument1\)", $new_string); echo ("<p><h1>List of Audit Reports:</h1></p><hr><br />"); while ($file = readdir($dir)) // while loop { //$parts = preg_split("/\.\(.*\)\.\(.*\)/", $file); $parts = $new_string; echo $parts; if (is_array($parts) && count($parts) > 1) { // does the dissected array have more than one part $extension = reset($parts); // set to we can see last file extension if ($extension == "Audit_Report" OR $extension == "audit_report") // is extension ext or EXT ? echo "<a href=\"$file\" target=\"_blank\"> $file </a><br />"; // If so, echo it out else do nothing cos it's not what we want } } echo "<hr><br />"; closedir($dir); // Close the directory after we are done ?> <form action="readdirectory.php" method='post'>Search Files:<p> Hostname: <input type="text" name="argument"<p> IP Address: <input type="text" name="argument1"<p> Date: <input type="text" name="argument2"<p> <p><input type="submit" name="submitFinal" value="Update"> <p> </form> </p> This is object programming right? Is there a performance issue with this? for example: $notfications = ( blah blah ) ? : ''; then if ($notificatiosn != blabla){ echo 'hey'; }or.... $notifications = function(){ do my stuff here then return 'hey'; }Which way is faster or slower? Reason I Ask this is because I've been doing some object orientated programming in javascript, and didn't know you could do it in php. I'd rather do the objective way so I don't have to use so many freaking variables above the regular way, lol. Edited by Monkuar, 22 January 2015 - 12:22 PM. Ok it's abit complicated so i'll try to explain as best as I can. Upon registration a file is created with your username that was registered and also a file for your profile named after your username so it would be /profiles/usernamesprofilehere.php. I put a code into the profile that is: Code: [Select] include ("/home/giacjrdi/public_html/mysite/profiles/profileinfo/$username.info.php"); echo "<center><b><br /> $user's Profile <br /></b></center>"; $username is calling the cookie's username while $user is calling the account's username. eg if I try to view "bob"'s profile but logged in as "fred" since the include function is under $username which is cookies, it will retrieve "fred"'s information and post it on "bob"'s profile. The only sollution i can think of would be to store a username variable in the url and use it for the include function. http://pastebin.com/DbHQSYd7 Been stumbling my way through OOP and seem to be understanding it for the most part (I think..) But I've got a couple questions / kinks that I can't seem to work out. a) How do I return a variable from a class so that a different class has access to it (meta_data) b) I'm getting a "$this" cannot be redefined error (which I know why, but I don't know how to fix)) c) How do I call a function from within one class, where the function resides in another class, AND pass it variables? Any help would be greatly appreciated I've tried to Google warrior A and I think I can figure that one out, but B and C are proving to be the real stumbling blocks. |