I’m trying to display msg based on the return value of my function in here
class Database{
private $host = DB_HOST;
private $dbname = DB_NAME;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbh, $error, $stmt;
function __construct(){
// Set DSN, which is database source name.
$dsn = "mysql:host=" . $this->host . ";dbname=" . $this->dbname;
//setting some options
$opts = array(
PDO::ATTR_PERSISTENT => TRUE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $opts);
}catch(PDOException $e){
$this->error = $e->getMessage();
}
}
function query($q){ $this->stmt = $this->dbh->prepare($q); }
function execute(){$this->stmt->execute();}
function bind($param, $value, $type = null){
if(is_null($type)){
switch(true){
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
}
class Jobs extends Database{
function create($data){
//Insert query
$this->query("INSERT INTO jobs (cat_id, company, job_title, description, salary, location, user, email)
VALUES (:cat_id, :company, :job_title, :description, :salary, :location, :user, :email)
");
//bind values
$this->bind(":cat_id", $data['cat_id']);
$this->bind(":company", $data['company']);
$this->bind(":job_title", $data['job_title']);
$this->bind(":description", $data['description']);
$this->bind(":salary", $data['salary']);
$this->bind(":location", $data['location']);
$this->bind(":user", $data['user']);
$this->bind(":email", $data['email']);
//execute the statment & returen true or false
if($this->execute()){ return true; }else{ return false; }
}
}
but, every time this code runs, it always return false. even though the query runs very normal and the data is inserted.
Here is my run code:
if($_SERVER['REQUEST_METHOD'] == "POST"){
$data = array();
$data['job_title'] = $_POST['job_title'];
$data['company'] = $_POST['company'];
$data['cat_id'] = $_POST['cat_id'];
$data['description'] = $_POST['description'];
$data['salary'] = $_POST['salary'];
$data['location'] = $_POST['location'];
$data['user'] = $_POST['user'];
$data['email'] = $_POST['email'];
if($jobs->create($data)){
redirect("", "Your job has been listed", "success");
}else{
redirect("", "Something went wrong", "error");
}
}
It always display "Something went wrong", but the data is being inserted.
I tried to display the return value of var_dump($jobs->create(data));
it always return null of false
2
Answers
declare array outside and try
You need to return the value from execute inside of your Database class