Reputation: 221
I created a class that has 2 functions that deal with the connection to the database and to make a questy. One of these calls the other. This is my code, but it gives me error .... sure something wrong in calling the function. Can anyone help me?
class DB{
public function connect(){
session_start();
include_once('libs/Smarty.class.php');
$smarty = new Smarty();
$smarty->setTemplateDir('templates/');
$smarty->setCompileDir('templates_c/');
$smarty->setConfigDir('configs/');
$smarty->setCacheDir('cache/');
$host = "localhost";
$user = "root";
$pass = "pass";
$tablename = "table";
return $connect = mysql_connect($host, $user, $pass);
mysql_select_db($tablename, $connect) or die(mysql_error());
}
public function do_query($query){
echo DB::connect();
if(mysql_query($query,DB::connect())){
$message="Annuncio inserito correttamente!!";
echo $message;
}else{
$message="Error insert data into DB: ";
echo $message. mysql_error();
}
}
}
Upvotes: 1
Views: 395
Reputation: 15696
First of all, code placed after return
is not executing. This is never used:
mysql_select_db($tablename, $connect) or die(mysql_error());
So the database is never selected.
Secondly, you are connecting to your database twice per one query, while it should be once per whole http request.
Next thing, is that you use mysql
lib, while there is newer called mysqli
. Also you can try with PDO wrapper.
Upvotes: 0
Reputation: 3903
Your return the $connect ... but you might want to return the mysql_select_db
$connect = mysql_connect($host, $user, $pass);
return mysql_select_db($tablename, $connect) or die(mysql_error());
EDIT:
I was answering to "sure something is wrong ..." as it was an obvious mistake that the last statement isn't executed.
But if you want to use the connect you need to return it, sure!
$connect = mysql_connect($host, $user, $pass);
mysql_select_db($tablename, $connect) or die(mysql_error());
return $connect;
Upvotes: 2
Reputation: 768
You are calling DB::connect() which is static function you need to declare it as static such as
public static function connect(){
}
if you wanna call it inside the class, you have to do it like
Self::connect();
Upvotes: -1
Reputation: 13535
there is some design errors, your template logic should be outside of database connection method. Apart from that following changes needs to be made
class DB {
private $host = "localhost";
private $user = "root";
private $pass = "pass";
private $tablename = "table";
private $con = null; //change here
public function connect(){
$this->con = $connect = mysql_connect($this->host, $this->user, $this->pass); change here
mysql_select_db($this->tablename, $this->con) or die(mysql_error()); //should be database name
}
public function do_query($query){
if(mysql_query($query,$this->con)){ //notice the change in this line
$message="Annuncio inserito correttamente!!";
echo $message;
}else{
$message="Error insert data into DB: ";
echo $message. mysql_error();
}
}
Upvotes: 0