Jump to content

functions, variables and globals


TimUSA

Recommended Posts

Learning something new here so if anyone can tell me why I this wont return a value?

 

page1.php

<?php
require "page2.php";

getuserid();
echo $userID;
  
?>

 

page2.php

<?php
function getuserid() {
        $user =& JFactory::getUser();
        $userID = $user->id;
        global $userID;
    }
?>

Link to comment
Share on other sites

Forget that you ever saw the global keyword. Functions should return (i.e. via a return $userID; statement) the value the function produces. You even used the word 'return' in your question. By returning the value, you can then use the value any way you want. You can assign it to a variable $userID = getuserid();, echo it echo getuserid();, or use it as a call time parameter in another function call  if(in_array(getuserid(),$some_array)){

 

As to the actual problem in your code, the global $userID; statement must come before you reference the $userID variable so that php knows you are referencing not a local variable but the global one (or more simply, functions should return the value they produce and not even mess with the global keyword.)

Link to comment
Share on other sites

I was able to get my userID and now I am getting empty query results and not sure where this is breaking down, my full code now looks like this:

 

conducttest.php

<?php
require "library.php";

function conducttest() {
    //GET JOOMLA USER ID FOR USER
    $userID = getuserid();    
    //NEW TESTS QUERY (what purchased test are available for use with 'item_available' == '1' {unused test} and matching current 'user_id')
    $new_test=new_test_query();
    //RESUME TESTS QUERY (what purchased test are available for use with 'item_available' == '1' {unused test} and matching current 'user_id')
    $resume_test=resume_test_query();
    
    //PART1 SELECT A TEST TO BE USED
    if(!isset($_POST['select_test'])) {
        echo '
            <form method="post" action="'.$PHP_SELF.'">
            <fieldset>
            <legend>Please Select A Test To Be Used</legend>
            <table>';
        if (empty($new_test)) {
            echo '
                <th colspan="3"align="left">NO NEW TESTS AVAILABLE</th>';
        }
        else {     
            echo '
                <th colspan="3"align="left">NEW TESTS AVAILABLE</th>
                <tr>
                    <td width="75px">SELECT</td>
                    <td width="50px">ID</td>
                    <td width="150px">TEST TYPE</td>
                    <td width="150px">UNIQUE TEST ID</td>
                <tr>';
            foreach ($new_test as $result1) {
            echo ' 
                <tr>
                    <td><input type="radio" value="' .$result1['Id']. '" name="Id"></td>
                    <td>'.$result1['Id'].'</td>
                    <td>'.$result1['test_name'].'</td>
                    <td>'.$result1['test_number'].'</td>
                <tr>';   
            }
        }
        echo '
            </table>
            <hr />
            <table>';
        if (empty($resume_test)) {
            echo '
                <th colspan="3"align="left">NO NEW TESTS AVAILABLE</th>';
        }
        else {     
            echo '
                <th colspan="3"align="left">NEW TESTS AVAILABLE</th>
                <tr>
                    <td width="75px">SELECT</td>
                    <td width="50px">ID</td>
                    <td width="150px">TEST TYPE</td>
                    <td width="150px">UNIQUE TEST ID</td>
                <tr>';
            foreach ($resume_test as $result2) {
            echo ' 
                <tr>
                    <td><input type="radio" value="' .$result2['Id']. '" name="Id"></td>
                    <td>'.$result2['Id'].'</td>
                    <td>'.$result2['test_name'].'</td>
                    <td>'.$result2['test_number'].'</td>
                <tr>';   
            }
        }
        echo '
            </table>
            </fieldset>
            <input type="submit" name="select_test" value="Select" />
            </form>';
    }
    else
        echo'nothong to do yet';        
    
} 
?>

 

library.php

<?php
    //GET JOOMLA USER ID & USERNAME FOR LOGGED USER
    function getuserid() {
        $userID =& JFactory::getUser();
        return $userID->id;
    }
    
    //NEW TESTS QUERY (what purchased test are available for use with 'item_available' == '1' {unused test} and matching current 'user_id')
    function new_test_query() {
        $db =& JFactory::getDBO();
        $new_test_query =    "
                  SELECT *
                  FROM crt_transactions
                  WHERE user_id = ".$userID." AND test_available = '1'
                  ORDER BY test_name, id
                  ";
        $db->setQuery($new_test_query);
        $new_test = $db->loadAssocList();
        return $new_test;
    }
  
    //RESUME TESTS QUERY (what purchased test are available for use with 'item_available' == '2' {resume test} and matching current 'user_id')
    function resume_test_query() {
        $db =& JFactory::getDBO();
        $resume_test_query =    "
                  SELECT *
                  FROM crt_transactions
                  WHERE user_id = ".$userID." AND test_available = '2'
                  ORDER BY test_name, id
                  ";
        $db->setQuery($resume_test_query);
        $resume_test = $db->loadAssocList();
        return $resume_test;
    }
?>

Link to comment
Share on other sites

Do you have php's error_reporting set to E_ALL and display_errors set to ON in your master php.ini on your development system so that php will help you by reporting and displaying all the errors it detects? You will save a TON of time. Stop and start your web server to get any changes made to the master php.ini to take effect and check the output from a phpinfo statement to make sure that the two settings actually changed in case the php.ini that you are changing is not the one that php is using.

Link to comment
Share on other sites

im on a virtual server, so no development server and to be honest the php.ini is typically over my head as I am still a rookie. this is from my php.ini:

 

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; error_reporting is a bit-field.  Or each number up to get desired error
; reporting level
; E_ALL             - All errors and warnings (doesn't include E_STRICT)
; E_ERROR           - fatal run-time errors
; E_RECOVERABLE_ERROR  - almost fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it's automatically initialized to an
;                     empty string)
; E_STRICT          - run-time notices, enable to have PHP suggest changes
;                     to your code which will ensure the best interoperability
;                     and forward compatibility of your code
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
;
; Examples:
;
;   - Show all errors, except for notices and coding standards warnings
;
error_reporting = E_ALL & ~E_NOTICE
;
;   - Show all errors, except for notices
;
;error_reporting = E_ALL & ~E_NOTICE | E_STRICT
;
;   - Show only errors
;
;error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR
;
;   - Show all errors, except coding standards warnings
;
;error_reporting  =  E_ALL

; Print out errors (as a part of the output).  For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below).  Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
display_errors = On

; Even when display_errors is on, errors that occur during PHP's startup
; sequence are not displayed.  It's strongly recommended to keep
; display_startup_errors off, except for when debugging.
display_startup_errors = Off

; Log errors into a log file (server-specific log, stderr, or error_log (below))
; As stated above, you're strongly advised to use error logging in place of
; error displaying on production web sites.
log_errors = Off

; Set maximum length of log_errors. In error_log information about the source is
; added. The default is 1024 and 0 allows to not apply any maximum length at all.
log_errors_max_len = 1024

; Do not log repeated messages. Repeated errors must occur in same file on same
; line until ignore_repeated_source is set true.
ignore_repeated_errors = Off

; Ignore source of message when ignoring repeated messages. When this setting
; is On you will not log errors with repeated messages from different files or
; source lines.
ignore_repeated_source = Off

; If this parameter is set to Off, then memory leaks will not be shown (on
; stdout or in the log). This has only effect in a debug compile, and if
; error reporting includes E_WARNING in the allowed list
report_memleaks = On

;report_zend_debug = 0

; Store the last error/warning message in $php_errormsg (boolean).
track_errors = Off

; Disable the inclusion of HTML tags in error messages.
; Note: Never use this feature for production boxes.
;html_errors = Off

; If html_errors is set On PHP produces clickable error messages that direct
; to a page describing the error or function causing the error in detail.
; You can download a copy of the PHP manual from http://www.php.net/docs.php
; and change docref_root to the base URL of your local copy including the
; leading '/'. You must also specify the file extension being used including
; the dot.
; Note: Never use this feature for production boxes.
;docref_root = "/phpmanual/"
;docref_ext = .html

; String to output before an error message.
;error_prepend_string = "<font color=ff0000>"

; String to output after an error message.
;error_append_string = "</font>"

; Log errors to specified file.
;error_log = filename

; Log errors to syslog (Event Log on NT, not valid in Windows 95).
;error_log = syslog

Link to comment
Share on other sites

turned on joomla's debugging and got this:

 

JDatabaseMySQLi::query: 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND test_available = '1' ORDER BY test_name, id' at line 3 SQL=SELECT * FROM crt_transactions WHERE user_id = AND test_available = '1' ORDER BY test_name, id
Link to comment
Share on other sites

Did you look at the query statement that was output as part of the error message? What value is missing in it?

 

There's another part to using functions correctly, passing input values into the function as call time parameters. Your function definition needs an $id parameter that you then use in the query statement -

 

<?php
    function new_test_query($id) {
        $db =& JFactory::getDBO();
        $new_test_query =    "
                  SELECT *
                  FROM crt_transactions
                  WHERE user_id = ".$id." AND test_available = '1'
                  ORDER BY test_name, id
                  ";
        $db->setQuery($new_test_query);
        $new_test = $db->loadAssocList();
        return $new_test;
    }

 

The reason for call time parameters as inputs into functions is again to simplify code and make the programmer's job easier. You would call the above function using -

 

 $new_test=new_test_query($userID);

 

or if you are only using the $userID in one place, you could do away with the $userID variable and just use -

 

$new_test=new_test_query(getuserid());

 

By writing functions this way - (optionally) supplying inputs as call time parameters, code and local variables inside the function needed to do its processing, and (optionally) returning the output that the function produces, allows them to be used as building blocks and allows you to more easily write code without needing to remember any of the details about the code inside the function (after you have tested it), such as what global variables it uses and, oops, what global variables did I define in all those other functions so that I don't accidentally overwrite anything.

$new_test=new_test_query();

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.