PHP - Pull A Variable From An Output To A Function???
Hey Guys, I'm building a site to view images on, basically the image detail is stored in a database, the site is then accessed and a standard select query is used. I then get the image name etc pulled from the database. Is there a way to save that image name into a variable and get it to display on a form that is run from a function - completely independent to my viewing code...
Some sort of global variable, but that could change each time I viewed a different photo - and wouldn't have any effect on anyone else browsing the site etc - so the correct image name would always be passed? 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; } Folks, Requirement: I want to pass Javascript Output in a PHP Variable. Purpose: So that i can find a particular String from that Javascript Output and accordingly apply the control. Javascript: Quote <script type='text/javascript'> var amzn_wdgt={widget:'Search'}; amzn_wdgt.tag='powlawofatt-21'; amzn_wdgt.columns='3'; amzn_wdgt.rows='10'; amzn_wdgt.defaultSearchTerm='10 mp 5x zoom'; amzn_wdgt.searchIndex='Electronics'; amzn_wdgt.width='542'; amzn_wdgt.showImage='True'; amzn_wdgt.showPrice='True'; amzn_wdgt.showRating='True'; amzn_wdgt.design='2'; amzn_wdgt.colorTheme='Default'; amzn_wdgt.headerTextColor='#000000'; amzn_wdgt.outerBackgroundColor='#FFFFFF'; amzn_wdgt.marketPlace='GB'; </script> <script type='text/javascript' src='http://wms.assoc-amazon.co.uk/20070822/GB/js/AmazonWidgets.js'> </script> What i am doing: Quote $javaoutput = "<script type='text/javascript'> var amzn_wdgt={widget:'Search'}; amzn_wdgt.tag='powlawofatt-21'; amzn_wdgt.columns='3'; amzn_wdgt.rows='10'; amzn_wdgt.defaultSearchTerm='10 mp 5x zoom'; amzn_wdgt.searchIndex='Electronics'; amzn_wdgt.width='542'; amzn_wdgt.showImage='True'; amzn_wdgt.showPrice='True'; amzn_wdgt.showRating='True'; amzn_wdgt.design='2'; amzn_wdgt.colorTheme='Default'; amzn_wdgt.headerTextColor='#000000'; amzn_wdgt.outerBackgroundColor='#FFFFFF'; amzn_wdgt.marketPlace='GB'; </script> <script type='text/javascript' src='http://wms.assoc-amazon.co.uk/20070822/GB/js/AmazonWidgets.js'> </script>"; if (strpos($javaoutput, "No results for")) { echo "Sorry no product found"; } else echo $javaoutput; Problem: It seems its outputting the Javascript output in PHP variable $javaoutput but the strpost() does not work. What am i doing wrong? and How to correct it? Cheers Natasha Thomas I am trying to be true to the principle that logic and presentation should be kept separate. However, the only way to generate dynamic content and output is using something like PHP, so there is somewhat of a conflict. I just wrote this Function, and I am curious if it breaks the principle above... /** * Returns Online Status Indicator Markup * * Takes User's Last Activity and determines the User's Online Status. * Returns HTML for appropriate Online Status Indicator. * * @param DateTime $lastActivity MySQL DateTime format (yyyy-mm-dd hh:mm:ss) * @return string */ function getOnlineStatus($lastActivity){ // strtotime() converts DateTime format (yyyy-mm-dd hh:mm:ss) into a Unix Timestamp (seconds). // time() is current time measured in the # of seconds since Unix Epoch (January 1 1970 00:00:00 GMT). $minutesOnline = (time() - strtotime($lastActivity))/60; // Determine Online Status. if ($minutesOnline < 15){ // Member Online $indicator = '<img src="/images/Light_Green_10.png" width="10" alt="Member Online" /><br />'; }else if ($minutesOnline < 30){ // Member Idle $indicator = '<img src="/images/Light_Yellow_10.png" width="10" alt="Member Idle" /><br />'; }else{ // Member Offline $indicator = '<img src="/images/Light_Gray_10.png" width="10" alt="Member Offline" /><br />'; } return $indicator; }//End of getOnlineStatus Thanks, Debbie 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 Here is my function which almost works as expected: <?php function find_value($array,$value) { for($i=1;$i<sizeof($array);$i++) { if($array[$i] == $value) { echo "$i . $array[$i]<br />"; return; } } } ?> And I call the function like so: <?php $names = array('Jason','Mike','Joe'); $name = 'Joe'; find_value($names,$name); ?> And the output is: 2 . Joe According to my understanding of Arrays, Joe would be index 3 BECAUSE my counter starts at 1 in my for loop??? Why is the result like this? What am I not understanding here? Hi i turned my output_buffering to true on my php.ini because i need some of its features for trailing the system my problem now is when im getting .csv file using header function, it seems that it gives me the source code of the interpreted code instead of the expected .csv contents. Here is the source code echo $who; echo $ecrn; $myFile = "($who)$info_value[RecordName]-$ecrn"; header('Content-Type: text/csv; charset=utf-8'); $content = "Content-Disposition: attachment; filename=".$myFile.".csv"; header($content); $output = fopen('php://output', 'w'); $sql = "SELECT * FROM classrecordvalue"; $query = mysql_query($sql); // loop over the rows, outputting them while ($row = mysql_fetch_array($rows)) fputcsv($output, $row); im just wondering does output_buffering true in php.ini affect the output here? if so any other suggestions there of how i can download .csv files using php? thank you much for the people who will help 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 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? 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 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 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! 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. 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 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! 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! 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 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 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? |