PHP - Making Variable Avaliable Outside Function- ?global
I run these functions to find the key of a given element inside an array. Like so;
$ban_ip_file = file("ip_file.txt"); foreach($ban_ip_file as $key => $value) { $value = trim($value); if($value == $ip_from_form)// passed to page by a form $set = $key; } How do I make $set available for testing and file writing further down the script? Tried assigning global $set; just above the $set=$key; ----but it did not work. Similar TutorialsWhen I put this chunk of code into it's own function: function fetch_all ($dbc, $query) { include ('knuffix_list_func.php'); pagination_start ($dbc, $query); $offset = $pag_array[0]; $rows_per_page = $pag_array[1]; $query = $query . " LIMIT $offset, $rows_per_page"; echo "test query: " . $query; knuffix_list ($query, $dbc); pagination_end ($pag_array); } And when I echo out the query as you can see in the example, then I notice that the variables $offset and $rows_per_page never get appended. I set the variable $pag_array to a global inside the function pagination_start(). It usually works when I DON'T wrap a function around this chunk of code, but if I do wrap a function around everything then the global suddenly won't work anymore. Btw, this also won't work if I wrap a function around the function DECLARATIONS. Any ideas, how I could make it work? Sorry, this will be a simple question. Say you define two global variables in your functions.php file as: GLOBAL $salesTax = .07; GLOBAL $shipping = 5.00; Those variables would be accessiible in the checkout.php page, right? ok iv set up a simple demo this is the code im running include('simple_html_dom.php'); include('config.php'); include('connect.php'); include('functions.php'); include($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'globalFunctions.php'); test(); echo "test variable = ".$test; exit; this is the function which is in globalFunctions.php which is two directories back ../../ function test() { $test = 10; global $test; } how come when i run script i am not getting variable echoed Hi, im having a problem using a global object in all my scripts and programs. Its a register singleton so it have all the configuration values, etc... Now im doing: 1-I create a script for testing, test.php 2-I include in that script 'errores.php', thats my error system library. 3-The error library include once 'registroglobal.php', thats my file for the global register. 4-Because i can use a lot of systems with a complete library or alone, i created a system where i test if the library module is part of a more greater library or not. If not, it instantiates the global register in errors.php (called in the include in test.php). 5-Here is the problem. Includes add and execute code, so, i must have all errors.php functions and the global register created. 6-If i test the global register in the test.php script, it goes well. 7-But if i call a function of my errores.php system, it says that my global register is undefined. Well, thats all the explanation. Whats going on? How can i solve this? Hi All, For the last post,I m very happy that i found out so many great mind who are watching my problem and solving online. anyway great thanks for all, just now i m making a project and i m facing problem in the below code "i need to know how can make this code easy or how can i make rdata variable accessible for the download button" generatecv.php file <?php if(isset($_REQUEST['submit'])) { $name=$_REQUEST['pname']; $pin=$_REQUEST['pin']; $mnumb=$_REQUEST['mnumber']; $tnumb=$_REQUEST['telenumber']; $email=$_REQUEST['email']; $obj=$_REQUEST['obj']; $title=$_REQUEST['jobt']; $activity=$_REQUEST['activity']; //$file=fopen('test.doc','a+'); //echo @fwrite($file,$name); //fclose($file); $rdata=""; $rdata.="<table id='cvtbl' border='0' align='center' > <th>Resume</th> <tr><td>".$name.":</td></tr><tr><td>Objective:</td></tr>"; $rdata.="<tr><td>".$obj."</td></tr>"; $rdata.="<tr><td>Email:".$email."</td></tr>"; $rdata.="</table>"; echo $rdata; echo "<style>#cv{display:none;}</style>"; echo "<form><input type='submit' name='dwnld' id='dwnld' value='Download'/></form>"; } if(isset($_REQUEST['dwnld'])) { header("Content-type:application/msword"); header("Content-disposition:attachment;filename=test.doc"); $fp=fopen("test.doc","r") or die("try again"); $data=fread($fp,filesize('test.doc')); fwrite($fp,$rdata); echo $data; fclose($fp); //echo $rdata."<br />".$rdata; } ?> this is the html file <html> <title>User details</title> <body> <form name='cv' id='cv' method="post" enctype="multipart/form-data" action='generatecv.php'> Enter your name<input type=text name=pname id=pname /> Zip Code<input type=text name=pin id=pin /> Mobile number<input type=text name=mnumber id=mnumber /> <br />Telephone number <input type=text name=telenumber id=telenumber /> Email address<input type=text name=email id=email /> <br />Enter your objective<br /><textarea name=obj id=obj cols=30 rows=5 ></textarea> <!--University Name <input type=text name=university id=university /> --> <br /><!--uni, city ,state ,type of degree ,full degree name,date--> <br /><!--Experience<br /><textarea name=exp id=exp cols=30 rows=5 ></textarea> --> Select type of resume <select name='type' id='type' onChange=''> <option value='0'>Graduate</option> <option value='1'>Post Graduate</option> <option value='2'>Non Graguate</option> <option value='3'>Other</option> </select> Job title<input type='text' name='jobt' id='jobt' /> <br /><!--company name,city ,state ,office number ,job description ,date of employment--> <br />Activity <input type=text name=activity id=activity size=100 /> <br />Honors/Awards<input type=text name=honor id=honor size=100 /> <input type='submit' name='submit' id='submit' value='Generate CV' /> <input type='reset' name='Reset' id='submit' value='Reset' /> </form> </body> </html> Many thanks in advance Hello I've have read that global variables should not be used. so if i have 2 .php files: index.php - main content php file sitefunctions.php - php functions site file on my index.php page i have the following (an example of my problem): <?php displayError($errorID); ?> and in the sitefunctions.php file i have the following (an example of my problem): <?php function displayError($errorID) { if($errorID == 1) { echo "Password Failure"; } else { echo "Other Failure"; } } ?> now that works but since when first accesing that page the $errorID is not set then i get an error. How can i achieve this without first setting a blank $errorID global variable? Thanks I need $row['con_id'] outside the function so I can put it into a query, but simply putting global in front of it won't work. What would be the right way to do? This portion of code is INSIDE a function: //Loop through the array of data while ($row = mysqli_fetch_array ($data)) { echo "<table padding='0' margin='0' class='knuffixTable'>"; echo "<input type='hidden' name='con_id' value='<?php echo " . $row['con_id'] . "; ?>' />"; echo "<tr><td width='65px' height='64px' class='avatar_bg' rowspan='2' colpan='2'><img src='$avatar_path' alt='avatar' /></td><td class='knuffix_username'><strong>" . $user_name; echo "</strong><br />" . $row['category'] . " | " . date('M d, Y', strtotime($row['contributed_date'])) . "</td></tr><tr><td>"; echo "<form action='' method='post'> <input type='submit' name='plusVote' value='Y' /> <input type='submit' name='minusVote' value='N' /> </form></td><td class='votes'>Y[ - ] | N[ - ]</td></tr>"; echo "<tr><td class='knuffix_name' colspan='3'><strong>" . htmlentities($row['name']) . "</strong><br /></td></tr>"; echo "<tr><td colspan='2' class='knuffix_contribution'><pre>" . $row['contribution'] . "</pre><br /></td></tr>"; echo "</table>"; The PHP documentation does not show any examples how to GLOBALIZE a mysqli function. I'd need a way to use $row['con_id'] outside the function for the voting script I'm writing. Thanks for the suggestions. Hello, my global variable is getting whacked (defined null or being undefined) after a function call. I'm not sure if it's happening when leaving the function that assigns it or when the form is "posted", or something else. Code: [Select] <? //global variables $globalVarString = ""; //function definitions function displayResults() { global $globalVarString; if ($globalVarString == "") {displayForm("please enter your search string again");} else {displayForm("you typed: $globalVarString");} } function getResults($searchInput) { global $globalVarString; $globalVarString = $searchInput; //give status ?> <html><head><title>Search</title></head><body> <form action="<?=$_SERVER['PHP_SELF']?>" method="post"> Thanks for entering your data (<? echo "$globalVarString" ?>).<br><br>Please press the submit button to process your data    <input type="Submit" value="Submit" name="processQuery"> </form></body></html> <? } function displayForm($message) { //prompt for input ?> <html><head><title>Search</title></head><body> <form action=" <? $_SERVER['PHP_SELF'] ?>" method="post"> <h3>Please enter your search <input type="text" name="searchString">    <script type="text/javascript">document.forms[0].searchString.focus();</script> <input type="Submit" value="Submit Query" name="searchQuery"></h3> </form> <? if (!$message == ""){echo "<br>    <h4>" . $message . "</h4><br>";} ?> </body></html> <? } //main() if(array_key_exists('searchQuery', $_POST)) {getResults($_POST['searchString']);} elseif (array_key_exists('processQuery', $_POST)) {displayResults();} else {displayForm("");} ?> I declared a variable in a page. When i want to access that variable in other page i am bound to state as global such as global $var; now i can not access this variable in other pages even if declared global. Please some one tell me how to declare a variable once and can use in any page i want. tried mysql_insert_id but dont think this is the one that I need. Good evening, Im using GenRandomString, and wondered how I can get $confirm to keep its first value throughout my script. I have put comments on the lines that use $confirm. Do I need to change $confirm to a constant and how can I go about this? $firstname = $_GET['firstname']; $lastname = $_GET['lastname']; $companyname = $_GET['companyname']; $doornumber = $_GET ['doornumber']; $street = $_GET ['street']; $town = $_GET['town']; $postcode = $_GET['postcode']; $useremail = $_GET ['usermail']; $telephone = $_GET['telephone']; $shortcode = substr($postcode,0,2); function genRandomString() { $length = 10; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))];} return $string;} $confirm = genRandomString(); //creating a random number $query =mysql_query ("INSERT INTO treesurgeons (firstname, lastname, companyname, doornumber, street, town, postcode, useremail, telephone, Id) VALUES ('$firstname', '$lastname', '$companyname','$doornumber', '$street', '$town', '$postcode', '$useremail', '$telephone', '$confirm')");//1st Value echo mysql_error(); echo "<p>Thankyou for submiting your details.\r\n Please check your inbox and click on your confirmation link.</p>"; $message = "The following details have been submited to the tree directory and are awaiting confirmation; \r\n Please click on the link below to confirm these details are correct\r\n '$firstname', '$lastname', '$companyname','$doornumber', '$street', '$town', '$postcode', '$usermail', '$telephone' <a href='http://www.mywebsite.co.uk/confirmed.php?Id=$confirm'>"; //2nd Value $subject = "Your tree directory details"; $to = "$useremail"; $email = "$emailad"; mail( "$to", "$subject","$message", "$headers"); ?></body></html> I havent really played around with constants before, so please an advice appreciated! Im guessing im using DEFINE but im unsure how I would combine this with GenRandomString in my code. $link = ?><a href="post?id=<?php echo $id; ?>&title=<?php echo $slug_title; ?>"><?php echo $title; ?></a><?phpBasically what I am trying to do is get a url link of a current page that I'll be sending in an email. I have all the $_GET variables I need to duplicate the current url. For some reason it's giving me an error. Can you please fix what is shown above into something that'll work? Thanks. Edited by man5, 15 July 2014 - 07:09 PM. So what i mean is if i set a variable to "[" ($some_variable = "[") the rest of my code is now going to go CRAZY because there is an open [. Is there a way I can just make everything inside the first set of "" not relevant to the code? thanks! 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 Okay, really newbie question, but for this code... Code: [Select] <!-- Gender --> <label for="gender">Gender:</label> <select id="gender" name="gender"> <option value="">--</option> <option value="F">Female</option> <option value="M">Male</option> </select> 1.) How do I assign a variable to this? 2.) How do I make this "sticky"? Here is how I have usually done other form types... Code: [Select] <!-- First Name --> <label for="firstName">First Name:</label> <input id="firstName" name="firstName" type="text" maxlength="30" value="<?php if(isset($firstName)){echo htmlentities($firstName, ENT_QUOTES);} ?>" /><!-- Sticky Field --> <?php if (!empty($errors['firstName'])){ echo '<span class="error">' . $errors['firstName'] . '</span>'; } ?> Oh, by the way, at the top of my PHP file I have this code... Code: [Select] if ($_SERVER['REQUEST_METHOD']=='POST'){ // Form was Submitted (Post). // Initialize Errors Array. $errors = array(); // Trim all form data. $trimmed = array_map('trim', $_POST); Thanks, Debbie 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? |