PHP - Pagination With Function -> Need Query Outside Of Function
I've followed the PHP Freaks pagination tutorial which you can find here.
And I also got it to work, the only problem is that the script won't work when I use the query outside of the function. Here's the function: <?php function knuffix_list ($query, $dbc) { // find out how many rows are in the table: $query_row = "SELECT COUNT(*) FROM con"; $query_run = mysqli_query ($dbc, $query_row); $row = mysqli_fetch_row($query_run); $num_rows = $row[0]; // number of rows to show per page $rows_per_page = 5; // find total pages -> ceil for rounding up $total_pages = ceil($num_rows / $rows_per_page); // get the current page or set a default if (isset($_GET['current_page']) && is_numeric($_GET['current_page'])) { // make it an INT if it isn't $current_page = (int) $_GET['current_page']; } else { // default page number $current_page = 1; } // if current page is greater than total pages then set current page to last page if ($current_page > $total_pages) { $current_page = $total_pages; } // if current page is less than first page then set current page to first page if ($current_page < 1) { $current_page = 1; } // the offset of the list, based on current page $offset = (($current_page - 1) * $rows_per_page); echo "test " . $query; // SCRIPT ONLY WORKS IF I INSERT QUERY HERE $query = "SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY contributed_date DESC LIMIT $offset, $rows_per_page"; $data = mysqli_query ($dbc, $query) or die (mysqli_error ($dbc)); // Loop through the array of data while ($row = mysqli_fetch_array ($data)) { global $array; // Variables for the table $con_id = $row['con_id']; $likes_count = $row['likes']; $dislikes_count = $row['dislikes']; $dbuser_name = $row['nickname']; $dbuser_avatar = $row['avatar']; $user_id = $row['user_id']; // The TABLE echo "<table padding='0' margin='0' class='knuffixTable'>"; echo "<tr><td width='65px' height='64px' class='avatar_bg' rowspan='2' colpan='2'><img src='avatar/$dbuser_avatar' alt='avatar' /></td>"; echo "<td class='knuffix_username'><strong><a href='profile.php?user=$dbuser_name' title='Profile of $dbuser_name'>" . $dbuser_name . "</a> ___ " . $user_id . "____ <form action='' method='POST'><button type='submit' name='favorite' value='fav'>Favorite</button></form>"; echo "</strong><br />" . $row['category'] . " | " . date('M d, Y', strtotime($row['contributed_date'])) . "</td></tr><tr><td>"; echo "<form action='' method='post'> <button class='LikeButton' type='submit' name='likes' value='+1'>Likes</button> <button class='DislikeButton' type='submit' name='dislikes' value='-1'>Dislikes</button> <input type='hidden' name='hidden_con_id' value='" . $con_id . "' /> </form></td><td class='votes'>Y[" . $likes_count . "] | N[" . $dislikes_count . "]</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>"; // POST BUTTONS inside the table $likes = $_POST['likes']; $dislikes = $_POST['dislikes']; $con_id = $_POST['hidden_con_id']; $favorite = $_POST['favorite']; $array = array ($likes, $dislikes, $con_id, $user_id, $favorite); } /********* build the pagination links *********/ // BACKWARD // if not on page 1, show back links and show << link to go back to the very first page if ($current_page > 1) { echo " <a href='{$_SERVER['PHP_SELF']}?current_page=1'><<</a> "; // get previous page number and show < link to go to previous $prev_page = $current_page - 1; echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$prev_page'><</a> "; } // CURRENT // range of number of links to show $range = 3; // loop to show links in the range of pages around current page for ($x = ($current_page - $range); $x < (($current_page + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $total_pages)) { // if we're on current page if ($x == $current_page) { // highlight it but don't make a link out of it echo "[<b>$x</b>]"; // if it's not the current page then make it a link } else { echo "<a href='{$_SERVER['PHP_SELF']}?current_page=$x'>$x</a>"; } } } // FORWARD // if not on the last page, show forward and last page links if ($current_page != $total_pages) { // get next page $next_page = $current_page + 1; // echo forward link for next page echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$next_page'>></a> "; // echo forward link for last page echo " <a href='{$_SERVER['PHP_SELF']}?current_page=$total_pages'>>></a> "; } /***** end building pagination links ****/ mysqli_close($dbc); } ?> As you can see above, the script will only work if I put the query right below the $offset variable and above the $data variable. I put the test echo above the query to see how the query looks like when I induce the query from the outside through the function parenthesis into the function, and this is what I get printed out: test SELECT * FROM con, user WHERE con.user_id = user.user_id ORDER BY contributed_date DESC LIMIT , Obviously the $offset and the $rows_per_page variables are not set, when I induce the query from the outside into the function. So in that sense my question is: How can I induce the query from the outside into the function SO THAT the $offset and the $rows_per_page variables are set as well and NOT empty? p.s. I need the query outside of the function because I'm using a sort by category functionality. Similar TutorialsI want a simple function that converts a sql query into two queries for pagination purposes. So if the sql query is "SELECT `Name` FROM table1" I would like to perform: "SELECT COUNT(*) FROM table 1" and "SELECT `Name` FROM table1 LIMIT 10, 20" (example) (1) Would this work for most basic queries? (obviously if LIMIT wasn't already used)? (2) What command would I use to convert "SELECT `Name` FROM table1" to "SELECT COUNT(*) FROM table 1" I am aware there is more involved than this, but am just interested in the query side of things. Hiya! How do I create a pagination function that can be used multiple times, with any MySQL query? Many Thanks, Hey guys I am stuck on how to best create a php function to do the following.
I need to echo out 4 restaurants. I have a database of numerous restaurant categories: breakfast, lunch, dinner, and coffee. In this database some categories have more results than others.
Basically I want to randomly choose results from each category query, Breakfast, Lunch, and dinner to create 4 echoed results. (I understand that one category will have an extra result as there are 3 categories and 4 echoed results.) I do not want one category of restaurant to bump out another category because it has more results. Also, if there are not enough or no results from one category, I want extra results from the other queries to make up for it so that there are always 4 echoed items.
Finally, if there are not enough results from breakfast, lunch, dinner to make 4 echoed items, I would like Coffee to fill the 4 required results.
Randomly echo 4 results from the below primary queries:
Primary Query: Breakfast Restraunts Query
Primary Query: Lunch Restraunts Query
Primary Query: Dinner Restraunts Query
Get results from secondary query if Primary queries can’t echo 4 results:
Secondary Query: Coffee Shops Query
I hope this makes sense. I understand how to do the mysql queries, I just don't know how to do the php function to echo the results as required. Any help would be appreciated!
Edited by jason360, 09 January 2015 - 06:53 PM. I have a script that runs at the end of a batch process specifically built to clean out empty records. How can I make it a function and then call the function. Here is my query; Code: [Select] $sql="DELETE FROM ".$dbname." . property WHERE property . id=''"; mysql_query($sql) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error()); $sql="DELETE FROM ".$dbname." . agents WHERE agents . ip_source=''"; mysql_query($sql) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error()); $sql="DELETE FROM ".$dbname." . settings WHERE settings . prop_id=''"; mysql_query($sql) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $sql . "<br />\nError: (" . mysql_errno() . ") " . mysql_error()); I would like this to be in a function that i could specifically call the function. Why? Well because I have 5 different sets of queries like this set above and I'm going to build a conditional. So like if condition 1 then run use this function, condition 2, use function ??? etc and so on. Hi, Doing a Query SELECT * FROM table WHERE field BETWEEN low_number AND high_number If i have three rows with three numbers: IE: 27, 50, 80. and i run the query above, it returns a result of: 27 and 50. How can i get it to return a result of: 27,50, and 80.?? WHY: age range search: i want to return an age range of people = and between the age of say: 20 and 70 but i want to include the 20 and 70. How can i do this? Hello I have a general php insert function that I want to use to insert data into tables regulary, the problem is, each time I use it it creates a new row in the table instead of using certain columns to add information to, here is the function, can you tell me why does it insert a new row each time I use it?
class Query{ function add($table,$cols,$vals){ include 'conx.php'; $query = " INSERT INTO $table($cols) VALUES('$vals'); "; $res = mysqli_query($con,$query) ; if($res){ echo "Inserted value"; }else{ echo "Did not insert value"; } } } Hey, I am coding this forum and the following PDO prepare query calls the topic details. The prepare query works perfectly well, however when I add it into a function within another class and then call it, the script does not seem to work. I get errors like the following: Fatal error: Call to a member function fetch() on a non-object in C:\wamp\www\new\sources\forum\new.php on line 117 The prepare query fails to excute, this is because I do not know how to add it into a function. This is what I tried: Code: [Select] class FUNC { function userDetails($table, $column, $cVaulue, $oBy, $ASDSC) { global $dbh; $sth = $dbh->prepare('SELECT * FROM `'.$table.'` WHERE `'.$column.'` = '.$cVaulue.' ORDER BY `'.$oBy.'` '.$ASDSC.''); $sth->bindParam(':id', $id, PDO::PARAM_INT); $sth->execute(); } } The FUNC class is called as the $load variable, and in my forum class I have decalred it in my global so the variable can be passed: Code: [Select] $id = $forum_data['id']; $load->userDetails('db_topics', 't_forum_id', ':id', 't_whenlast', 'DESC'); $coll=$sth->fetch(PDO::FETCH_ASSOC); $this->html->RightForum($coll); The code is very silly, but the fact is I did not know how to do this.. Please help me put this query into a function because I need to make use of it in many other parts of the forum and I don't want to constantly declare this query. I've created a function getsub(). The idea is that this function contains a query that grabs records from the categories table, using the $row['cat_id'] that I pass to it from within an existing while ($row=mysql_fetch_assoc($res)) loop. Heres the function: function getsub($rowid,$catsort) { global $system, $LANGUAGES, $subres; $subquery = "SELECT * FROM webid_categories WHERE parent_id = " . $rowid . " " . $catsort; $subres = mysql_query($subquery); $system->check_mysql($subres, $subquery, __LINE__, __FILE__); return $subres; } And heres the code that calls this function and passes the $row['cat_id'] value to it: // prepare categories list for templates/template // Prepare categories sorting if ($system->SETTINGS['catsorting'] == 'alpha') { $catsorting = ' ORDER BY cat_name ASC'; } else { $catsorting = ' ORDER BY sub_counter DESC'; } $query = "SELECT cat_id FROM " . $DBPrefix . "categories WHERE parent_id = -1"; $res = mysql_query($query); $system->check_mysql($res, $query, __LINE__, __FILE__); $query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . mysql_result($res, 0) . " " . $catsorting . " LIMIT " . $system->SETTINGS['catstoshow']; $res = mysql_query($query); $system->check_mysql($res, $query, __LINE__, __FILE__); while ($row = mysql_fetch_assoc($res)) { $subcats = getsub($row['cat_id'],$catsorting); while($subrow = mysql_fetch_assoc($subcats){ $template->assign_block_vars('sublist', array( 'SID' => $subrow['cat_id'], 'SNAME' => $category_names[$getrow['cat_id']] )); } $template->assign_block_vars('cat_list', array( 'CATAUCNUM' => ($row['sub_counter'] != 0) ? '(' . $row['sub_counter'] . ')' : '', 'ID' => $row['cat_id'], 'IMAGE' => (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '', 'COLOUR' => (empty($row['cat_colour'])) ? '#FFFFFF' : $row['cat_colour'], 'NAME' => $category_names[$row['cat_id']] )); } then a .tpl file just references the {sublist.SID} and {sublist.SNAME} variables. BUT.... It ain't working. My page just goes blank. Any help would be massively appreciated. Hi everyone, I used to know the function, but it was a very long time ago, for when you need to just extract a single value from a query... instead of having to use mysql_fetch_assoc in a while loop to build an array... e.g. Code: [Select] $TheResultingFieldValue = mysql_fetch_SOMETHING(mysql_query("SELECT aField FROM aTable WHERE anotherField = 'aCondition'")); I'm trying to build a search function that will search all columns in a table. Here is what I've got: Code: [Select] if (isset($_POST['submitted'])) { $q = "SELECT * FROM children "; if(isset($_POST['query'])) { $q .= "WHERE "; $all = "SELECT * FROM children WHERE 1"; $r_all = mysqli_query($dbc, $all); while ($field = $r_all->fetch_field()) { // Get field headers for building query $f_name = "{$field->name} LIKE {$_POST['query']},:"; // Build query with search string $fn = explode(":",$f_name); // Need to convert $f_name to an array but this does not convert it to a single array but multiple arrays $q .= implode("OR", $fn); // Need to insert OR for the db query } // End while ($field = $r_all->fetch_field()) } // End if(isset($_POST['query'])) } // End if (isset($_POST['submitted'])) The explode function is what is not working for me. It gives me this (sam is the search string I entered into the form): Code: [Select] Array ( [0] => child_id LIKE sam, [1] => ) Array ( [0] => first_name LIKE sam, [1] => ) Array ( [0] => second_name LIKE sam, [1] => ) Array ( [0] => last_name1 LIKE sam, [1] => ) Array ( [0] => last_name2 LIKE sam, [1] => ) Array ( [0] => gender LIKE sam, [1] => ) Array ( [0] => dob LIKE sam, [1] => ) so instead of getting one array with each string being a value I get multiple arrays. Any ideas? Thanks in advance for help. I have a PHP script that has a function called traverseXMLNodes and it passes an xml string. I want anyone with a username and password to be able to call this function from his website or application or programming. In short i want my site to act as an API(Application Programming Interface). I am really stuck as to how to go about this. There are other functions i would like to call as well so traverseXMLNodes is not the only function i want to my "API" users to access. Below is the code I am using. the filename for my php i called remote.php. I am using the following query string to test and no results are returned. http://localhost/testfolder/remote.php?xmlstring=20 Code: [Select] <?php $allowedfuncs = array('xmlstring','remotefunction2'); if(in_array($_get['xmlstring'], $allowedfuncs)) { $func = $_get['xmlstring']; $output = traverseXMLNodes($func); // This calls $_get['funccall']() echo $output; } else { exit(); } function traverseXMLNodes ($func) { echo "The XML string is"; echo "<br/>"; echo $func; echo "<br/>"; } /* More functions go here */ ?> I am changing my script from connecting to the database within every function, to using one connection (in the main class). However, I am getting an error: Call to a member function query() on a non-object Here is the main class: <?php class main{ // the configuration vars public $config; // the current user variables public $uid = 0; // contains the user ID public $gid = 0; // contains the group ID // database variables public $DB; // contains the connection public $query_id; // contains the query ID public $query_count; // how many queries have there been? // cache variables public $cache; public $test = 'hi'; // initiate public function __construct(){ } // start up functions public function startup(){ // first, set up the caching if($this->config['use_memcache'] == true){ // start up cache require_once('cache.class.php'); $this->cache = new cache_TS(); } // now, set up the DB $this->connectToDatabase(); // now, set up the user session $this->setUserSession(); // are we logged in? If so, update our location if($this->uid > 0){ // update location $this->updateUserSession(); } } // connect to database public function connectToDatabase(){ // connect to database $this->DB = new mysqli($this->config['host'],$this->config['user'],$this->config['pass'],$this->config['db']); // were we able to connect? if(!isset($this->DB)){ // this is an error exit('could not connect to the database.'); } // test query $q = "SELECT id,title FROM topics WHERE id='1' LIMIT 1;"; $q = $this->DB->query($q); $r = $q->fetch_assoc(); echo $r['id'] . $r['title']; // send back return $this->DB; } // some removed.... The test query works fine. It fails he <?php class forum extends main{ public function viewTopic($tid){ // Connect To Database //$sql = new mysqli(db::$config['host'], db::$config['user'], db::$config['pass'], db::$config['db']); // Get assorted details (topic, forum, etc) // Get topic details $tid = intval($tid); $tq = "SELECT * FROM `topics` WHERE id='$tid' LIMIT 1"; $tq = $this->DB->query($tq); $tr = $tq->fetch_assoc(); startup in main has already been called before forum is. The DB connects without failure. Can anyone see what the problem is? How can I get $this->DB->query to work? (The query works fine when it's ran in the main class) Hi All, I am working on system where i am storing column names in one table of database. To retrieve value of columns with separation of comma (exp. clol1, col2,col3..). for this i am using one function which i am calling middle of mysql query. but i am not getting fetch result over there. Below is the function i have to fetch column names. Code: [Select] function retrieve_columns() { $brand_id = $_SESSION['SESS_PRODUCT_CODE']; global $columnlist; $columns_query= "Select column_name from columns_list_to_display where brand_id=$brand_id"; $result=mysql_query($columns_query); $row_num=mysql_num_rows($result); $i=0; while ($row = mysql_fetch_array($result)) { $columnlist = ""; $i++; if($i != $row_num) { echo $row['column_name'].", "; } else { echo $row['column_name'].""; } } } I am writting query like as below: Code: [Select] $query = "SELECT " . $columnlist . "FROM $userlead_table LEFT JOIN notes ON $userlead_table.id = notes.leads_id LEFT JOIN lead_status ON $userlead_table.status = lead_status.status_code WHERE ((Date(a.submitted)>='$datefrom' AND Date(a.submitted)<='$dateto')) ORDER BY a.submitted DESC"; Please let me know where i am doing wrong. Hope one of this forum member would have proper solution for it. Thanks in advance. Regards, Jitendra I have a database called "mp_users" with the following setup: Code: [Select] CREATE TABLE IF NOT EXISTS `mp_users` ( `id` int(10) unsigned default NULL auto_increment, `uid` int(10) unsigned NOT NULL, `username` varchar(100) NOT NULL, `email` varchar(50) NOT NULL, `points` int(10) unsigned NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; When I try to run the following query, I get an error: Quote SELECT COUNT(id) AS user_exists FROM `mp_users` WHERE uid=$uid LIMIT 1; Error: Fatal error: Call to a member function query() on a non-object in /home/user/public_html/marketplace-functions.php on line 52 Here is the code: Code: [Select] <?php require_once "config.php"; $sql = new mysqli($db1['host'], $db1['user'], $db1['pass'], $db1['db']); function checkUserExists($uid){ // Query $q = "SELECT COUNT(id) AS user_exists FROM `mp_users` WHERE uid=$uid LIMIT 1;"; echo $q; $q = $sql->query($q); $r = $q->fetch_assoc(); // Any results? if($r['user_exists'] == 0){ // redirect to runonce... header('Location: marketplace.php?do=runonce&return='.urlencode($_SERVER['QUERY_STRING'])); exit(); } } ?> Line 52 is the $q query. I really cannot see what the problem is. The database exists, I've tried it in phpMyAdmin and it runs without trouble, but this wont! Can anyone help? Thanks in advance Hi guys, I am trying to implement a Pagination class for a website displaying movies. I need to have the total number of posts, but on accessing the function row_count() from class Connection I get the error: "Fatal error: Uncaught Error: Call to a member function query() on null in ..\connection.php:30 Stack trace: #0 from ...\index.php(20): Connection->row_count() #1 ..." I only found two posts concerning this issue, and they led me to think this might be a scope issue with $db variable; $db is defined in the constructor function of the same Connection class so I thought the scope would be ok; but apparently, not. Can anybody help? This is a real show-stopper just now. Please let me know if you need any further information. Thanks in advance. Sept connection.txt index.txt 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 Code: [Select] <?php class OnlineStore { private $DBConnect = NULL; private $storeID = ""; private $inventory = array(); private $shoppingCart = array(); function __construct() { include("inc_OnlineStoreDB.php"); $this->DBConnect = $DBConnect; } function __destruct() { if (!$this->DBConnect->connect_error) $this->DBConnect->close(); } public function setStoreID($storeID) { if ($this->storeID != $storeID) { $this->storeID = $storeID; $SQLstring = "SELECT * FROM inventory " . " where storeID = 'jw" . $this->storeID . "'"; $QueryResult = $this->DBConnect->query($SQLstring); if ($QueryResult === FALSE) { $this->storeID = ""; } else { $this->inventory = array(); $this->shoppingCart = array(); while (($Row = $QueryResult->fetch_assoc()) !== NULL) { $this->inventory[$Row['productID']] = array(); $this->inventory[$Row['productID']]['name'] = $Row['name']; $this->inventory[$Row['productID']]['description'] = $Row['description']; $this->inventory[$Row['productID']]['price'] = $Row['price']; $this->shoppingCart[$Row['productID']] = 0; } } } } public function getStoreInformation() { $retval = FALSE; if ($this->storeID != "") { $SQLstring = "SELECT * FROM store_info " . " WHERE storeID = '" . $this->storeID . "'"; $QueryResult = @$this->DBConnect->query($SQLstring); if ($QueryResult !== FALSE) { $retval = $QueryResult->fetch_assoc(); } } return($retval); } public function getProductList() { $retval = FALSE; $subtotal = 0; if (count($this->inventory) > 0) { echo "<table width='100%'>\n"; echo "<tr><th>Product</th><th>Description</th>" . "<th>Price Each</th><th># in Cart</th>" . "<th>Total Price</th><th> </th></tr>\n"; foreach ($this->inventory as $ID => $Info) { echo "<tr><td>" . htmlentities($Info['name']) . "</td>\n"; echo "<td>" . htmlentities($Info['description']) . "</td>\n"; printf("<td class='currency'>$%.2f</td>\n", $Info['price']); echo "<td class='currency'>" . $this->shoppingCart[$ID] . "</td>\n"; printf("<td class='currency'>$%.2f</td>\n", $Info['price'] * $this->shoppingCart[$ID]); echo "<td><a href='" . $_SERVER['SCRIPT_NAME'] . "?PHPSESSID=" . session_id() . "&ItemToAdd=$ID'>Add " . " Item</a></td>\n"; $subtotal += ($Info['price'] * $this->shoppingCart[$ID]); } echo "<tr><td colspan='4'>Subtotal</td>\n"; printf("<td class='currency'>$%.2f</td>\n", $subtotal); echo "<td>$nbsp;</td></tr>\n"; echo "</table>"; $retval = TRUE; } return($retval); } public function addItem() { $ProdID = $_GET['ItemToAdd']; if (array_key_exists($ProdID, $this->shoppingCart)) $this->shoppingCart[$ProdID] += 1; } } ?> having an issue to where nothing is appearing on the page and getting the Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\PHP\Chapter.10\class_OnlineStore.php on line 24 HERE IS THE MAIN PAGE Code: [Select] <?php session_start(); require_once("class_OnlineStore.php"); $storeID = "COFFEE"; $storeInfo = array(); if (class_exists("OnlineStore")) { if (isset($_SESSION['currentStore'])) $Store = unserialize($_SESSION['currentStore']); else { $Store = new OnlineStore(); } $Store->setStoreID($storeID); $storeInfo = $Store->getStoreInformation(); } else { $ErrorMsgs[] = "The OnlineStore class is not available!"; $Store = NULL; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?php echo $storeInfo['name']; ?></title> <link rel="stylesheet" type="text/css" href="<?php echo $storeInfo['css_file']; ?>" /> </head> <body> <h1><?php echo htmlentities($storeInfo['name']); ?></h1> <h2><?php echo htmlentities($storeInfo['description']); ?></h2> <p><?php echo htmlentities($storeInfo['welcome']); ?></p> <?php $Store->getProductList(); $_SESSION['currentStore'] = serialize($Store); ?> </body> </html> I HAVE REVIEWED IT OVER AND OVER AGAIN AND I CANT SEE THE PROBLEM. MAYBE SOMEONE FROM THE OUTSIDE CAN HELP OUT. 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 have this function completely written in my class file that I am working on. The point to this function is to be able to check the login of a user or administrator for either of the control panels associated with my site. It will check the session intime as well as the page / module referenced. Once it passes all those checks, it will check and ensure the emailaddress/password stored in the current session still holds true and the account is still active... if the account is still active it will update the lastActivity as well as update all of the session variables with what is currently in the database. What I am looking for is basically a look at the function, see if it looks good.. If there is any part to it that could create security holes for the site just off the login function itself... Usage: $q->validUser($_SESSION['user'], $_mod); <?php function validUser($sess, $p) { if ($sess['inTime'] == '' && $p != 'login' && $p != 'logout') { session_destroy(); $login = '0'; $_int = ''; return $login; } else if ($sess['inTime'] < time()-3600 && $p != 'login') { $sess['inTime'] = ''; session_destroy(); $this->check_login($sess, $p); } else { $this->user = $sess['emailAddress']; $this->pass = $sess['password']; $login = $this->sql_query("SELECT * FROM users WHERE emailAddress = '".$this->user."' AND password = '".$this->pass."' AND status = '1' LIMIT '1'"); if ($login = $this->sql_numrows($login) < 1) { $sess['inTime'] == ''; session_destroy(); $login = '0'; } else { // logged in, lets update the database for last_activity AND the session. $this->sql_query("UDATE users SET lastActivity = '".now()."' WHERE emailAddress = '".$this->user."'"); $login = $this->sql_query("SELECT * FROM users WHERE emailAddress = '".$this->user."' AND password = '".$this->pass."' AND status = '1' LIMIT '1'"); $login = mysql_fetch_assoc($login); foreach ($login as $key => $value) { $sess[$key] = $value; } $sess['inTime'] = time(); $login = '1'; } return $login; } } ?> That is the main function, sql_query and sql_numrows is: <?php function sql_query($query = "", $transaction = FALSE) { unset($this->query_result); if ($query != "") { $this->num_queries++; if ($transation == BEGIN_TRANSACTION && !$this->in_transation) { $result = mysql_query("BEGIN", $this->db_connect_id); if (!$result) { return false; } $this->in_transaction = TRUE; } $this->query_result = mysql_query($query, $this->db_connect_id); } else { if ($transaction == END_TRANSACTION && $this->in_transaction ) { $result = mysql_query("COMMIT", $this->db_connect_id); } } if ($this->query_result) { unset($this->row[$this->query_result]); unset($this->rowset[$this->query_result]); if ($transaction == END_TRANSACTION && $this->in_transaction ) { $this->in_transaction = FALSE; if (!mysql_query("COMMIT", $this->db_connect_id)) { mysql_query("ROLLBACK", $this->db_connect_id); return false; } } return $this->query_result; } else { if ($this->in_transaction ) { mysql_query("ROLLBACK", $this->db_connect_id); $this->in_transaction = FALSE; } return false; } } function sql_numrows($query_id = 0) { if(!$query_id) { $query_id = $this->query_result; } return ($query_id) ? mysql_num_rows($query_id) : false; } ?> Any insight that can help to benefit these functions would be appreciated. Question 1) Is the only and proper way to call a parent function "parent::function()"? Are there other/better ways from within a child function? Question 2) What are the deciding factors for when to make a function or attribute static? How do you make that decision? Assuming 5.3... Thanks. |