CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   PHP (http://www.codingforums.com/forumdisplay.php?f=6)
-   -   Use a Function (http://www.codingforums.com/showthread.php?t=286976)

ROYW1000 02-03-2013 07:36 PM

Use a Function
 
Hi

I have got a query counter to run using the following code:

PHP Code:

class dbAccess {

        var 
$resID;
        var 
$lastError;
        var 
$currentDatabase;
        var 
$queriesRun;
        var 
$lastQuery;
        var 
$timeTotal;
        [
B]var $roysqueries;[/B

PHP Code:

function dbAccess() {
            
$this->resID FALSE;
            
$this->lastError "";
            
$this->queriesRun 0;
            
$this->lastQuery "";
            
$this->timeTotal 0;
            [
B]$this->roysqueries 0;[/B]
        } 

PHP Code:

function showroysqueries() {
            echo 
"Roys Total Queries: ".$this->roysqueries;
        } 

If I echo the .$this->roysqueries it works ok but now I need to use that variable in another page.

Is there a way I can say for example $test1 = $this->roysqueries

Thanks
Roy

Fou-Lu 02-03-2013 11:51 PM

Your question isn't clear.
Given that you are using PHP 4 syntax for your objects, you can simply assign an object property directly to a variable. So to answer your question, yes since you have a var scoped variable which is an alias to public in PHP 5, you can simply assign it to another variable.
Public access to object properties in languages like PHP isn't exactly wise though. Since it is datatype weak, you have no way of enforcing the proper datatype to be used unless you use setters and getters.

ROYW1000 02-04-2013 08:23 AM

Hi

This is the entire script that does the queries and if I add $dbA->showQueries(); to the index page it shows the amount of queries.

What I want it to do is show me on every page the amount of queries and the execution time as well as the page load speed.

Is it possible to create a variable rather than a function that can be used throughout the site as it does not work on other pages except index.

Thanks
Roy
PHP Code:

<?php
    
function dbConnect(&$dbA) {
        global 
$databaseHost,$databaseUsername,$databasePassword,$databaseName;
        
$dbA = new dbAccess();
        
$dbStatus $dbA-> connect($databaseHost,$databaseUsername,$databasePassword,$databaseName);
        if (
$dbStatus == false) {
            
$dbA->showDBError();
            exit;
        }
    }
    
    class 
dbAccess {

        var 
$resID;
        var 
$lastError;
        var 
$currentDatabase;
        var 
$queriesRun;
        var 
$lastQuery;
        var 
$timeTotal;

        function 
dbAccess() {
            
$this->resID FALSE;
            
$this->lastError "";
            
$this->queriesRun 0;
            
$this->lastQuery "";
            
$this->timeTotal 0;
        }
        
        function 
showDBError() {
            global 
$jssShopFileSystem;
            include(
templatesCreatePath("templates/")."databaseproblem.html");
            return 
false;
        }

        function 
connect($sql_host_name,$sql_username,$sql_password,$sql_database_name) {
            
$this->currentDatabase $sql_database_name;
            
$this->resID = @mysql_connect($sql_host_name,$sql_username,$sql_password);
            if (
$this->resID == FALSE) {
                
$this->lastError "Could not connect to mySQL server";
                return 
FALSE;
            } else {
                if (@
mysql_select_db($sql_database_name)) {
                    return 
TRUE;
                } else {
                    return @
mysql_query("create database $sql_database_name");
                    return 
FALSE;
                }
            }
        }

        function 
close() {
            if (@
mysql_close()) {
                return 
TRUE;
            } else {
                
$this->lastError = @mysql_errno().": ".mysql_error();
                return 
FALSE;
            }
        }
        
        function 
showQueries() {
            echo 
"Total Queries: ".$this->queriesRun;
        }

        function 
query($sql_query) {
            global 
$safeMode;
            
$this->queriesRun++;
            
$this->lastQuery $sql_query;
            if ((@
$safeMode == "1" && strtolower(substr($sql_query,0,6)=="select")) || @$safeMode != "1") {
                
$result = @mysql_query($sql_query);
                if (
$result == FALSE) {
                    
$this->lastError mysql_errno().": ".mysql_error();
                    return 
FALSE;
                } else {
                    return 
$result;
                }
            } else {
                return 
true;
            }    
        }

        function 
fetch($sql_result) {
            
$result =  @mysql_fetch_assoc($sql_result);
            if (
$result == FALSE) {
                
$this->lastError mysql_errno().": ".mysql_error();
                return 
FALSE;
            } else {
                foreach(
$result as $k=>$v) {
                    
//$result[$k] = stripslashes($v);
                    
$result[$k] = $v;
                }
                return 
$result;
            }
        }

        function 
seek($sql_result,$sql_row) {
            
$result =  @mysql_data_seek($sql_result,$sql_row);
            if (
$result) {
                return 
TRUE;
            } else {
                
$this->lastError mysql_errno().": ".mysql_error();
                return 
FALSE;
            }
        }

        function 
count($sql_result) {
            return @
mysql_num_rows($sql_result);
        }

        function 
lastID() {
            return @
mysql_insert_id();
        }
        
        
//extra functions to quicken development
        
        //checks to see if an ID exists in a table
        
function doesIDExist($theTable,$idField,$theValue,&$resultSet) {
            
$this->queriesRun++;
            
$result mysql_query("select * from $theTable where $idField=$theValue");
            
$myCount mysql_num_rows($result);
            if (
$myCount 0) {
                
$resultSet mysql_fetch_assoc($result);
                foreach(
$resultSet as $k=>$v) {
                    
$resultSet[$k] = stripslashes($v);
                }
                return 
true;
            } else {
                return 
false;
            }
        }

        
//checks to see if a field is the same in another ID
        
function isUnique($theTable,$idField,$idValue,$uniqueField,$uniqueFieldValue) {
            
$this->queriesRun++;
            
$result $this->query("select * from $theTable where $uniqueField=\"$uniqueFieldValue\" and $idField != $idValue");
            
$myCount mysql_num_rows($result);
            if (
$myCount 0) {
                return 
false;
            } else {
                return 
true;
            }
        }

        function 
doesRecordExist($theTable,$uniqueField,$uniqueFieldValue) {
            
$this->queriesRun++;
            
$result $this->query("select * from $theTable where $uniqueField=\"$uniqueFieldValue\"");
            
$myCount mysql_num_rows($result);
            if (
$myCount 0) {
                return 
true;
            } else {
                return 
false;
            }
        }
        
        function 
deleteRecord($theTable,$idField,$idValue) {
            
$this->queriesRun++;
            
$result $this->query("delete from $theTable where $idField=$idValue");
            return 
true;
        }
        
        function 
updateRecord($theTable,$whereClause,$recArray,$myDebug=0) {
            
$this->queriesRun++;
            
$theQuery="update $theTable set ";
            for (
$f 0$f count($recArray); $f++) {
                if (
$f 0) { $theQuery .=","; }
                switch (
$recArray[$f][2]) {
                    case 
"S":    //string
                        
$recArray[$f][1] = str_replace("\\r\\n","{rnb}",$recArray[$f][1]);
                        
$theQuery .= $recArray[$f][0]."=\"".mysql_real_escape_string($recArray[$f][1])."\"";
                        
$theQuery str_replace("{rnb}","\\r\\n",$theQuery);
                        break;
                    case 
"N":    //number
                        
$theQuery .= $recArray[$f][0]."=".makeInteger($recArray[$f][1]);
                        break;
                    case 
"YN":    //yes no field
                        
$theQuery .= $recArray[$f][0]."=\"".makeYesNo($recArray[$f][1])."\"";
                        break;
                    case 
"D":
                        
$theQuery .= $recArray[$f][0]."=".makeDecimal($recArray[$f][1]);
                        break;
                    case 
"C":
                        
$theQuery .= $recArray[$f][1];
                        break;                        
                }
            }
            if (
$whereClause != "") {
                
$theQuery .= " where ".$whereClause;
            }
            if (
$myDebug == 1) { echo $theQuery; }
            
$result $this->query($theQuery);
            return 
$result;
        }

        function 
insertRecord($theTable,$recArray,$myDebug=0) {
            
$this->queriesRun++;
            
$theQuery="insert into $theTable (";
            for (
$f 0$f count($recArray); $f++) {
                if (
$f 0) { $theQuery .=","; }
                
$theQuery .= $recArray[$f][0];
            }
            
$theQuery .= ") VALUES(";
            for (
$f 0$f count($recArray); $f++) {
                if (
$f 0) { $theQuery .=","; }
                switch (
$recArray[$f][2]) {
                    case 
"S":    //string
                        
$recArray[$f][1] = str_replace("\\r\\n","{rnb}",$recArray[$f][1]);
                        
$theQuery .= "\"".mysql_real_escape_string($recArray[$f][1])."\"";
                        
$theQuery str_replace("{rnb}","\\r\\n",$theQuery);
                        break;
                    case 
"N":    //number
                        
$theQuery .= makeInteger($recArray[$f][1]);
                        break;
                    case 
"YN":    //yes no field
                        
$theQuery .= "\"".makeYesNo($recArray[$f][1])."\"";
                        break;
                    case 
"D":
                        
$theQuery .= makeDecimal($recArray[$f][1]);
                        break;
                }
            }
            
$theQuery .= ")";
            if (
$myDebug == 1) { echo $theQuery; }
            
$result $this->query($theQuery);
            return 
true;
        }

        function 
replaceRecord($theTable,$recArray,$myDebug=0) {
            
$this->queriesRun++;
            
$theQuery="replace into $theTable (";
            for (
$f 0$f count($recArray); $f++) {
                if (
$f 0) { $theQuery .=","; }
                
$theQuery .= $recArray[$f][0];
            }
            
$theQuery .= ") VALUES(";
            for (
$f 0$f count($recArray); $f++) {
                if (
$f 0) { $theQuery .=","; }
                switch (
$recArray[$f][2]) {
                    case 
"S":    //string
                        
$recArray[$f][1] = str_replace("\\r\\n","{rnb}",$recArray[$f][1]);
                        
$theQuery .= "\"".mysql_real_escape_string($recArray[$f][1])."\"";
                        
$theQuery str_replace("{rnb}","\\r\\n",$theQuery);
                        break;
                    case 
"N":    //number
                        
$theQuery .= makeInteger($recArray[$f][1]);
                        break;
                    case 
"YN":    //yes no field
                        
$theQuery .= "\"".makeYesNo($recArray[$f][1])."\"";
                        break;
                    case 
"D":
                        
$theQuery .= makeDecimal($recArray[$f][1]);
                        break;
                }
            }
            
$theQuery .= ")";
            if (
$myDebug == 1) { echo $theQuery; }
            
$result $this->query($theQuery);
            return 
true;
        }        
        
        function 
getTableList() {
            global 
$databaseName;
            
$tableList "";
            
$result mysql_query("SHOW TABLES FROM ".$databaseName);
            while (
$row mysql_fetch_array($result)) {
                
$tableList[] = $row[0];
            }
            return 
$tableList;
        }
        
        function 
tableFields($result) {
            return 
mysql_num_fields($result);
        }
        
        function 
retrieveFieldInformation($tableName) {
            
$result mysql_query("SHOW FIELDS FROM ".$tableName);
            while (
$row mysql_fetch_array($result)) {
                
$ftype  $row['Type'];
                   
$fname  $row['Field'];
                   
$fnull   $row['Null'];
                   
$fkey $row['Key'];
                   
$fdefault = @$row['Default'];
                   
$fextra $row['Extra'];
                   
$allFields[] = array("name"=>$fname,"type"=>$ftype,"null"=>$fnull,"key"=>$fkey,"default"=>$fdefault,"extra"=>$fextra);
            }            
            return 
$allFields;
        }
        
        function 
retrieveIndexInformation($tableName) {
            
$result mysql_query("SHOW INDEX FROM ".$tableName);
            while (
$row mysql_fetch_array($result)) {
                
$fkeyname  $row['Key_name'];
                   
$fseq  $row['Seq_in_index'];
                   
$fcolumn   $row['Column_name'];
                   
$fnonunique   $row['Non_unique'];
                   
$allFields[] = array("key"=>$fkeyname,"seq"=>$fseq,"column"=>$fcolumn,"nonunique"=>$fnonunique);
            }            
            return 
$allFields;
        }
        
        function 
retrieveAllRecords($theTable,$theOrder="") {
            
$this->queriesRun++;
            if (
$theOrder == "") {
                
$result $this->query("select * from $theTable");
            } else {
                
$result $this->query("select * from $theTable order by $theOrder");
            }
            
$count = @mysql_num_rows($result);
            
$retArray "";
            for (
$f 0$f $count$f++) {
                
$retArray[] = mysql_fetch_assoc($result);
                foreach(
$retArray[$f] as $k=>$v) {
                    
$retArray[$f][$k] = stripslashes($v);
                }
            }
            return 
$retArray;
        }

        function 
retrieveAllRecordsFromQuery($theQuery) {
            
$this->queriesRun++;
            
$result $this->query($theQuery);
            
$count = @mysql_num_rows($result);
            
$retArray null;
            for (
$f 0$f $count$f++) {
                
$retArray[] = mysql_fetch_assoc($result);
                foreach(
$retArray[$f] as $k=>$v) {
                    
$retArray[$f][$k] = stripslashes($v);
                }
            }
            return 
$retArray;
        }        
    }
?>


Fou-Lu 02-04-2013 01:52 PM

It'll show wherever you execute an $obj->showQueries() call. If you want to extract it to a variable, and you will need to do this on any script anyways, you can do so by rewriting the function to this:
PHP Code:

function &showQueries()
{
    return 
"Total Queries: " $this->queriesRun;


And assigning it as:
PHP Code:

$var = &$obj->showQueries(); 

Now anytime you echo $var, it will be the value of $obj->showQueries.

ROYW1000 02-09-2013 09:36 PM

Hi

As soon as I enter this code onto the page it stops working and Dreamweaver shows a syntax error. What am I doing wrong?

PHP Code:

function &showQueries()
{
    return 
"Total Queries: " $this->queriesRun;
}
  
$var = &$obj->showQueries(); 

Its this part that causes the error.

$var = &$obj->showQueries();

I think if this works this example will be very good.

Thanks in advance for your help.

Roy

Fou-Lu 02-10-2013 03:50 PM

Did you put that in a script, or did you rewrite the showQueries function? It has to be in the scope of a class since you refer to $this, so if its not in a function it'll throw an error since you cannot access $this.
I did biff this logic though. Return by references must be variables, not strings. So simply return the member:
PHP Code:

function &showQueries()
{
    return 
$this->queriesRun;


There is a downside to returning by reference though; you can rewrite a private member value this was as well since the $var in my example would refer to $this->queriesRun.


All times are GMT +1. The time now is 11:59 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.