PHP - Returning Array From Function
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; } Similar TutorialsI 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] //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 there, Now I was curious if there was a way I could return an array in my function like the following, I currently get a error though: Code: [Select] Catchable fatal error: Object of class panel_accounts could not be converted to string in C:\wamp\www\X-HostLTD - Panel\PanelFrontend\index.php on line 21 But can you only return strings?. Here is the function that it errors on: function returnAccountInformation($AccountID) { return mysql_fetch_array(mysql_query("SELECT * FROM ****_***** WHERE *****_***** = '".mysql_escape_string($AccountID)."'")); } Could somebody help me on the matter?, Thank you. P.S sorry for staring out the table names but I don't really want people knowing my database structure hehe. 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> Trying to retun an array which gets a file from a directory and then returns the filename as the key and the complete file url as the value but when returning it it prints out "Array" for each file in the directory rather than the file name: Doing this in wordpress. Code: [Select] function wsme_select_css_theme(){ $alt_css_template_path = WSME_THEME_CSS; // Define path to files $alt_widgets_template = array(); // set array $out = ''; // Set var if ( is_dir($alt_css_template_path) ) { // If directory exists if ($alt_css_template_dir = opendir($alt_css_template_path) ) { //opens directory while ( ($alt_css_template_file = readdir($alt_css_template_dir)) !== false ) { //if files are in the directory if(stristr($alt_css_template_file, ".css") !== false) { //if the files are .css files $out[] = array($alt_css_template_file => WSME_THEME_CSS.'/'.$alt_css_template_file); //create the array(filename => file path) for each file in the directory } } } return $out; // return array } } Code: [Select] array( 'name' => 'Style', 'id' => WS_THEME_PREFIX . '_style', 'headings' => array( array( 'name' => 'Theme CSS', 'options' => array( array('name' => 'Homepage', 'desc' => ' select the css file of the theme you want for your site', 'id' => WS_THEME_PREFIX . '_theme_css', 'value' => '', 'options' => wsme_select_css_theme(), 'type' => 'select' ) ) ) ) Any suggestions? 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 Guys, I have 6 file upload fileds in an array. When i try to return the error messages at this link: http://www.php.net/manual/en/features.file-upload.errors.php i get an error displayed for every upload box. I was wondering if it is possible to simply return 1 error instead of the 6? For example rather than getting "No File Uploaded No File Uploaded No File Uploaded No File Uploaded No File Uploaded No File Uploaded" i simply get "No File Uploaded". Also If only some files are uploaded no error should be displayed. The code i am using is: foreach ($_FILES['image']['error'] as $key => $error) { if ($error == UPLOAD_ERR_NO_FILE) { echo "No File Uploaded"; } I have tried using "break;" which works in leaving only 1 error, however the error is still displayed if less than 6 files are uploaded. All help greatly appreciated. Thanks Originally, I would get both, and unfortunately would inconsistently use both. Then, I wanted more consistently, so configured php.ini to only return objects as I felt accessing them was more concise. And then later, I found myself needing arrays more often, and initially would just typecast them to arrays but eventually my standard was to set the PDO's fetch style to an array. And now I find myself almost always explicitly requesting arrays and occasionally requesting columns or named values. Do you configure ATTR_DEFAULT_FETCH_MODE, and if so to what? PS. Anyone use FETCH_CLASS, FETCH_INTO or FETCH_NUM? If so, what would be a good use case? I have a script that runs a query against a MySQL database, then, if it returns a resultset, it takes the 'freindly name from an array containg the database connections, then adds the data for the resultset. Unfortunately at the minute, it doesn't quite work the way that I want. So far I have: //get list of servers to query, and choose them one at a time for($a = 0; $a <sizeof($slaveRes_array); $a++) { $con = mysql_connect($slaveRes_array[$a]['server'], $slaveRes_array[$a]['user'], $slaveRes_array[$a]['password']); mysql_select_db($dbs, $con); //get list of MySQL Queries, and run them against the current server, one at a time for($b = 0; $b <sizeof($query_array); $b++) { $SlaveState = mysql_query($query_array[$b]['query1'], $con); // 1st Query // If there is a resultset, get data and put into array while($row = mysql_fetch_assoc($SlaveState)) { for($c = 0; $c <mysql_num_rows($SlaveState); $c++) { $slave_array[]['name'] = $slaveRes_array[$a]['database']; for($d = 0; $d <mysql_num_fields($SlaveState); $d++) { $slave_array[][mysql_field_name($SlaveState,$d)] = mysql_result($SlaveState,$c,mysql_field_name($SlaveState,$d)); }} } } // Run Query2...Query3....etc. } The problem is that at the minute it puts each field into a separate part of the array e.g. Array ( => Array ( [name] => MySQL02_5083 ) [1] => Array ( [Slave_IO_State] => Waiting for master to send event ) [2] => Array ( [Master_Host] => localhost ) [3] => Array ( [Master_User] => root ) Whereas what I am trying to achieve is more like: Array ( => Array ( [name] => MySQL02 ) [Slave_IO_State] => Waiting for master to send event ) [Master_Host] => localhost ) [Master_User] => root )... [1] => Array ( [name] => MySQL03 etc. etc. But I can't see how to achieve this? I am trying to return all the photos in the database that has the albumid associated with that table info. I can echo the $album->id (albumid) no problem, but my query it think is somewhat off. Please anyone. Code: [Select] <div id="photo-items" class="photo-list-item"> <?php echo $album->id.'<br>'; // fetch album photos and ids $database =& JFactory::getDBO(); $query = "SELECT * FROM jos_photos where albumid = ".$album->id." ORDER BY ASC"; $photos = mysql_query($query); //This returns and array of photos, but then needs to display all the photos in loop below, but it not retuning none, even if there is 100 photos in table and in the folder directory if($photos) { for( $i=0; $i<count($photos); $i++ ){ $row =& $photos[$i]; ?> <div class="photo-item" id="photo-<?php echo $i;?>" title="<?php echo $this->escape($row->caption);?>"> <a href="<?php echo $row->link;?>"><img class="" src="<?php echo $row->getThumbURI();?>" alt="<?php echo $this->escape($row->caption);?>" id="photoid-<?php echo $row->id;?>" /></a> <?php if( $isOwner ) { ?> <div class="photo-action"> <a href="javascript:void(0);('<?php echo $row->id;?>');" class="remove"><?php echo JText::_('CC REMOVE');?></a> </div> <?php } ?> </div> <?php } } else { ?> <div class="empty-list"><?php echo JText::_('CC NO PHOTOS UPLOADED YET');?> <button class="button button-upload" href="javascript: void(0);&userid=88" id="upload-photos-button">Start Uploading</button></div> <?php } ?> </div> Hi guys, I am using this oAuth library https://github.com/elbunce/oauth2-php But more specifically these lines of code: protected function getToken($token, $isRefresh = true) { try { $tableName = $isRefresh ? self::TABLE_REFRESH : self::TABLE_TOKENS; $tokenName = $isRefresh ? 'refresh_token' : 'oauth_token'; $sql = "SELECT $tokenName, client_id, expires, scope, user_id FROM $tableName WHERE token = :token"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':token', $token, PDO::PARAM_STR); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); return $result !== FALSE ? $result : NULL; } catch (PDOException $e) { $this->handleException($e); } } However, this is retuning no value. If I modify the code to be: protected function getToken($token, $isRefresh = true) { return $token; } It returns the $token value, so the $token is definitely being passed to the function. The code should return an associative array: i.e., $token["expires"], $token["client_id"], $token["userd_id"], $token["scope"], etc Also $token should not === NULL. PS. I run a few checks on $tableName = $isRefresh ? self::TABLE_REFRESH : self::TABLE_TOKENS; $tokenName = $isRefresh ? 'refresh_token' : 'oauth_token'; And they are returning the correct values. Which from my thinking narrows it down to: $sql = "SELECT $tokenName, client_id, expires, scope, user_id FROM $tableName WHERE token = :token"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':token', $token, PDO::PARAM_STR); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); return $result !== FALSE ? $result : NULL; Any and all help is greatly appreciated. Thanks in advance. Hi fellow developers, I'm having a real problem at the moment, I'm trying to capture everything in between <body></body> tags using the following code but it does not print anything: $lines = file("http://www.bbc.co.uk/"); foreach ($lines as $line_num => $line) { $thecontent .= htmlspecialchars($line) . "<br />\n"; } preg_match('/<body.*?>(.*?)<\/body >/', $thecontent, $htmltext); $moretext = $htmltext[1]; echo $moretext; When you do place a "print($thecontent);" into the code the entire html for [whatever the website] does display but I want to capture only the html code in between the body tags. I've tried everything but I just can't get this to work. I would appreciate anyone's help and I'd like to thank you in advance. M 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. 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? Hey guys, I am using multiple inputs (checkboxes) to pass values to another page (I have named them name="blabla[]" in order to pass the values an as array). The problem is when I print_r the array, I get "Array" as a result... I have tried imploding it to a string but it doesn't seem to be working. Any ideas on what could be causing this? Thank you 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 hi Code: [Select] function livre($form_data_array['ensino']) { } this code give me a syntax error, why? what is the correct way? thanks Hi im having some trouble when i try to add values to an array from a function. The added value will not stay saved. fun1 will display both firstname and surname but when i call fun2 after calling fun1 i just get the firstname. I would like to have it so the array is updated and stays updated untill it is cleared or over written. Any help with this would be greatly appreciated. i am using codeigniter if that makes any difference. Thanks <?php class Test extends Controller { var $data1 = array( 'firstname' => 'craig' ); function fun1() { global $data1; $this->data1['surname'] = 'brute'; echo "<pre>"; print_r($this->data1); } function fun2() { global $data1; echo "<pre>"; print_r($this->data1); } } I've written the code to generate letter and number ranges: public function generateRange($type = 'numbers', $start = 0, $end = 10) { $rangelist = array(); switch($type) { case 'upper letters': { foreach(range($start, $end) as $letter) { $rangelist[] = $letter; } } case 'lower letters': { foreach(range($start, $end) as $letter) { $rangelist[] = $letter; } } case 'numbers': { foreach(range($start, $end) as $number) { $rangelist[] = $number; } } default: { return false; } return $rangelist; } } It current doesn't seem to return the array result correctly currently. If I change the line "$rangelist[] = $number;" to "echo $number;" it does print the correct data. Any ideas on why the array return line isn't working correctly? |