Page 1 of 1

Problem with my db class

Posted: Sat Apr 10, 2004 10:10 pm
by d3ad1ysp0rk
Just whipped this up, and I'm not a good OOP programmer (as you'll see in a second), but I can't even figure out why this doesn't work.. it's pathetic..

Code: Select all

<?php //dbclass.php
Class DB {
   var $dbHost = "localhost";
   var $dbUser = "d3ad1ysp0rk";
   var $dbPass = "squall";
   var $dbName = "testdb";
   var $link;

   function newdb(){
      $this->conn();
      $this->selectdb();
   }
   function conn(){
      $this->$link = mysql_connect($host,$dbuser,$dbpass) or die("Could not connect: " . mysql_error());
   }
   function selectdb(){
      //debugging stuff
      /*echo $dbHost;
      echo $dbUser;
      echo $dbPass;
      echo $dbName;
      echo $link;*/
      mysql_select_db($dbName, $link) or die("Could not use table: " . mysql_error());
   }
   function endconn(){
      mysql_close($link);
   }
}
?>
Page that calls it:

Code: Select all

<?php //testsql.php
include("dbclass.php");
if(count($_POST) > 2){
   $mydb = new DB();
   $mydb->newdb();
   
   extract($_POST, EXTR_SKIP);
   $sql = "INSERT INTO newtable(username,password,rank) VALUES('$username','$password','$rank')";
   mysql_query($sql) or die("Error: " .mysql_error());
   $mydb->endconn();
}
else {
   echo "You must enter all values!!";
}
?>
Errors:
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in C:\Documents and Settings\Administrator\Desktop\Server\dbclass.php on line 23
Could not use table:
Thanks to anyone who can spot my mistake.

Posted: Sat Apr 10, 2004 10:23 pm
by Vicious
try making these 2 variables with different names
$this->conn();
$this->selectdb();

Posted: Sat Apr 10, 2004 10:34 pm
by d3ad1ysp0rk
$this isn't a variable, it's a way to reference functions and variables in a class.

Posted: Sat Apr 10, 2004 10:56 pm
by Ixplodestuff8
when calling to a variable inside a class with $this (or outside the class with $classvariable) you don't use a dollar sign for the variable ex:

Code: Select all

<?php 

$this-> link = 'something'; 

//and not

$this-> $link = 'something';  

?>
edit: I spotted that error and stopped looking, sorry about that, other things about class variables is they always need to used with a $this.

Code: Select all

<?php
//your line
mysql_select_db($dbName, $link) or die("Could not use table: " . mysql_error());

//should be
mysql_select_db($this -> dbName, $this -> link) or die("Could not use table: " . mysql_error());
?>

Posted: Sat Apr 10, 2004 11:16 pm
by Vicious
that was my bad i mis read it