Gå til innhold

OOP i PHP4, sliter litt


Anbefalte innlegg

Har begynt å bevege meg inn på OOP og det første jeg gjorde var å lage en counter.

Problemet er at den gir masse feilmld i PHP4.

 

Fant ut at public/private ikke støttes av PHP4, men hva annet er det jeg har "brukt" som gjør at det kommer feilmld i PHP4?

 

<?php

/* Return-codes
-1      dbConn-feil
-2      Feil ved oppretting av tabell
-3      Ukjent avsluttning

1    Allerede telt (cookie eller session)
2    Allerede telt (funnet i tabellen)
3    Telt og alt i orden
*/
class counter {
   var $dbHost;
   var $dbUser;
   var $dbPwd;
   var $dbName;
   var $dbTable;
   
   var $cookieTime;
   var $countAgainTime;
   
   /* Constructor */
   public function counter($dbHost, $dbUser, $dbPwd, $dbName, $dbTable) {
       $this->dbHost = $dbHost;
       $this->dbUser = $dbUser;
       $this->dbPwd = $dbPwd;
       $this->dbName = $dbName;
       $this->dbTable = $dbTable;
       
       $this->cookieTime = 60 * 60 * 12; // Default is 12 hours
       $this->countAgainTime = 60 * 60 * 1; // Default is 1 hour (same IP counted)
   }
   
   /* Set cookieTime */
   public function setCookieTime($cookieTime) {
       $this->cookieTime = $cookieTime;
   }
   
   /* Set countAgainTime */
   public function setCountAgainTime($countAgainTime) {
       $this->countAgainTime = $countAgainTime;
   }
   
   /* Get current count */
   public function getCount() {
       $query = "SELECT countId FROM " . $this->dbTable;
       $result = mysql_query($query, $this->dbConn);
       
       return mysql_numrows($result);
   }


   /* Perform count */    
   public function doCount() {
       if (!$this->dbConnect()) {
           return -1;
       }
       
       // If already counted in this session or in a cookie
       if (isset($_SESSION['counted']) || isset($_COOKIE['counted'])) {
           return 1;
       }
       
       // If table doesn't exist, try to create it
       if (!mysql_query("DESCRIBE " . $this->dbTable, $this->dbConn)) {
           // If unsuccessfull, return false
           if (!$this->createTable()) {
               return -2;
           }
       }
       
       $query = "SELECT countId 
               FROM " . $this->dbTable . " 
               WHERE ip='" . $_SERVER['REMOTE_ADDR'] . "' 
               AND timestamp > " . (time() - $this->countAgainTime);
                    
       $result = mysql_query($query, $this->dbConn);
       $num = mysql_numrows($result);
       
       // Already counted within the timeframe, do not count again
       if ($num > 0) {
           return 2;
       }
       
       // Insert the count into the table
       else {
           $query = "INSERT INTO " . $this->dbTable . " (ip, timestamp) 
                   VALUES ('" . $_SERVER['REMOTE_ADDR'] . "', '" . time() . "')";
           $result = mysql_query($query, $this->dbConn);   
           
           // If success, set session and cookie
           if ($result) {
               $_SESSION['counted'] = true;
               setcookie("counted", true, $this-countAgainTime);
               
               return 3;
           }
       }
       return -3;        
   }
   
   
   
   /* Create table */
   private function createTable() {
       return mysql_query("
           CREATE TABLE `" . $this->dbTable . "` (
           `countId` INT( 6 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
           `ip` VARCHAR( 15 ) NOT NULL ,
           `timestamp` INT( 12 ) NOT NULL
           ) ENGINE = MYISAM;");
   }
      
   
   /* Connect to db */
   private function dbConnect() {
       $this->dbConn = mysql_connect($this->dbHost, $this->dbUser, $this->dbPwd);
       // If failed to connect, return false
       if (!$this->dbConn) {
           return false;
       }
       // If failed to select db, return false
       if (!mysql_select_db($this->dbName)) {
           return false;
       }
       return true;
   }
} // END OF CLASS

session_start();

$counter = new counter("localhost", "root", "", "test", "counttest2");
$status = $counter->doCount();
if ($status < 0) echo "Error: " . $status;

echo "Antall besøkende: " . $counter->getCount();
?>

 

Dette er PHP5-koden.

 

Når jeg fjernet public/private på PHP4 så får jeg disse:

Warning: mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /hsphere/local/home/rodekor/hjelpekorps.steinkjer-rk.no/counter.class.php on line 117

Error: -1

 

Noen tips?

 

Edit:

Siden dette er første classen jeg har laget vil jeg gjerne ha innspill på metodikken jeg har brukt. :)

Endret av ZoRaC
Lenke til kommentar
Videoannonse
Annonse

Jeg har en counter som fungerer. Veit ikke helt om det er det der OOP greia di, men det fungerer helt fint.

 

 

 

Eksempel.php

<?php

//variable declarations
$counter_data = "nummer.txt"; //counter data file
$image_dir = "/digits/";	//image directory
$style = ""; //enter text for text.Anything else for graphics
//check if file exists
if(!($fp = fopen($counter_data,"r+"))) die ("cannot open counter file");
//read in the current count from the file
$count = (int) fread($fp, 20);
//close the file
fclose($fp);
//increment count
$count++;
//text counter
if ($style == "text") 
{
echo $count;
}
//graphical counter
else 
{
$digit = strval($count);
for ($i = 0; $i < strlen($count); $i++) 
{
 echo "<img src=$image_dir/$digit[$i].gif>";
}
}
$fp = fopen($counter_data, "w");
fwrite($fp , $count);
//close the file
fclose($fp);
?>

 

 

Counter.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<p>
<?php include("counter.php"); ?>
</p>
</body>
</html>

 

Nummer.txt

0
// 0 fordi da starter den på 0

 

 

Håper jeg ikke har skrivi noe feil her nå ^^

Pass på at du har bildene kalt 0.gif, 1.gif og opp til 9.gif i en mappe kalt digits (hvis du ikke forandrer på koden over da)

Lenke til kommentar

Det der er ikke OOP, og jeg regner med at han vil lage en teller i OOP for å øve seg litt...

 

Til trådstarter: det er ikke så lurt å koble til databasen med root, menmen.

Har du prøvd å bruke den samme koden på en server som kjører PHP 5.2? Det er var jo først i PHP 5 OOP virkelig kom på banen, så det er mest sannsynlig masse som ikke går i PHP 4.

Lenke til kommentar

Andy-Pandy:

Har en teller som virker, men ville prøve å skrive objektorientert i tillegg til at jeg vil ha mer kontroll på hvor ofte samme maskin telles.

 

Ståle:

Brukte "root" lokalt på XAMPP. ;)

Koden virker på PHP 5.1.4...

 

OXODesign:

Fjernet public og private fra koden, da ble jeg kvitt de meldingene ang det, men de meldingene jeg skrev i første innlegg var fortsatt der. Har ikke prøvd å fjernet "var"...

Kobler ikke til med blankt passord på den serveren, det er bare lokalt på maskinen min jeg brukte det...

Lenke til kommentar

Ikke noe poeng å ta bort var siden det også funker i PHP4.

 

Men her er noe jeg fant som kan hjelpe (men er nok ikke dette hvis det har virket før).

 

When connecting to a MySQL server located on the local system, the mysql client connects thorugh a local file called a socket instead of connecting to the localhost loopback address 127.0.0.1. For the mysql client, the default location of this socket file is /tmp/mysql.sock. However, for a variety of reasons, many MySQL installations place this socket file somewhere else like /var/lib/mysql/mysql.sock.

 

While it is possible to make this work by specifying the socket file directly in the mysql client command

 

mysql --socket=/var/lib/mysql/mysql.sock ...

 

 

it is painful to type this in every time. If you must do so this way (because you don't have permissions to the file in the solution below), you could create an alias in your shell to make this work (like alias mysql="mysql --socket=/var/lib/mysql/mysql.sock" depending on your shell).

 

To make your life easier, you can make a simple change to the MySQL configuration file /etc/my.cnf that will permanently set the socket file used by the mysql client. After making a backup copy of /etc/my.cnf, open it in your favorite editor. The file is divided into sections such as

 

[mysqld]

datadir=/usr/local/mysql/data

socket=/var/lib/mysql/mysql.sock

 

[mysql.server]

user=mysql

basedir=/usr/local/mysql

 

 

If there is not currently a section called [client], add one at the bottom of the file and copy the socket= line under the [mysqld] section such as:

 

[client]

socket=/var/lib/mysql/mysql.sock

 

 

If there is already a [client] section in the my.cnf file, add or edit the socket line as appropriate. You won't need to restart your server or any other processes. Subsequent uses of the mysql client will use the proper socket file.

Endret av shaker
Lenke til kommentar

Fant feilen... :whistle:

En counter inkluderer man jo vanligvis, men for testingen sin del så kjørte jeg den direkte og brukte:

$counter = new counter($sql_server, $sql_username, $sql_password, $sql_database, "counts");

 

Men, ingen av de variablene var satt når jeg ikke inkluderte config-filen først... :blush:

 

I tillegg var det en liten feil på linje 94:

setcookie("counted", true, $this->countAgainTime);

 

Takk for hjelpen likevel!

Endret av ZoRaC
Lenke til kommentar

Opprett en konto eller logg inn for å kommentere

Du må være et medlem for å kunne skrive en kommentar

Opprett konto

Det er enkelt å melde seg inn for å starte en ny konto!

Start en konto

Logg inn

Har du allerede en konto? Logg inn her.

Logg inn nå
×
×
  • Opprett ny...