PHP - Passimg A Variable To A Function And Getting Array Value From That Function
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 Similar TutorialsHi Guys, I'm a PHP newbie and I'm having some trouble creating a function that I can call where I can perform a MYSQL SELECT querey which returns an associative array, and be able to pull a value from that array and return it to the call. My code is below. Everything seems to work up until where I try to set the $average variable. If I return $row instead of $round_val, I see me array as "Array ( [user_id] => 64 [AVG(twos_made)] => 5.0000 )" It seems as though my my functions arugment (twos_made - which is my $column_name var) is not getting passed through or something. Any help would be greatly appreciated! Thanks! Code: [Select] function avg_of($column_name) { global $connect_db; $query = "SELECT user_id, AVG($column_name) FROM table GROUP BY user_id"; $result = mysql_query($query, $connect_db); $row = mysql_fetch_assoc($result); $average = $row['AVG($column_name)']; $round_val = round($average, 1); return $round_val; } 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 get this error Warning: current() [function.current]: Passed variable is not an array or object.. for this Code: [Select] $lastblock = current( ${"s".$row} ); print_r($lastblock); when i change to this it works.. Code: [Select] $lastblock = current( $s0 ); print_r($lastblock); The problem is i won't know the $row seeing as it is in a while loop. Solution? I am having some problems getting a query correct. Basically I have two tables, one with listings and another with categories. In the listings table I have a column called shortdescription. I am trying to pull the shortdescription from the listings table with the query $shortdesc = array_shift(mysql_fetch_row(mysql_query("select shortdescription from links where category = '".$scat->id."' "))); The shortdecription display properly on the pages display the listings, however I am getting the following error on any pages that only display the parent categories Warning: array_shift() [function.array-shift]: The argument should be an array in /home/...path/file.php on line 1462 The listings id numbers begin at 75+ because the initial parent category id ends at 74. The query seems to be searching for listing ids below 75 and spitting out an error because it is not finding them. Any ideas on how to eliminate this error and/or stop the query from looking for non-existant data? 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? 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! 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. 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 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! 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. 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! 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? 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 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. 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 I am going through the tutorial found at http://goo.gl/69MeY and in my ultimate wisdom have decided to see if I can create a form, which you input some text, and then in the php file that handles the form in puts that variable into a text document using the fwrite function, basically creating a file from the website containing whatever text you put in. There is no specific purpose to this idea, I am just trying to implement everything I have learnt so far. Form: http://pastebin.com/J62UHBeT PHP Handler: http://pastebin.com/FHuaKkxD I someone could point me in the right direction of what I am doing wrong it would be much appreciated Thanks in advance Michael I can't figure out how I'm messing up so badly. Anyway, I have:
$con=mysqli_connect("removedforsecurity"); $finderCleanup = mysqli_query($con, "SELECT * FROM Entries ORDER BY PID DESC LIMIT 1"); $finderCleanupArray = mysqli_fetch_array($finderCleanup); $integerCleanup = $finderCleanupArray['PID'] - 40; $lastPID = $finderCleanupArray['PID']; $lastPIDreduced = $finderCleanupArray['PID'] - 8;When I var_dump $lastPID, it returns INT with a number (it works correctly.) Then, I have this: function getResults($con,$lastPIDreduced)$con works correctly in the function, but $lastPIDreduced is "undefined." What is my sin? Thanks. |