gomesh munda
gomesh munda

Reputation: 850

PDO Sql query not working

I am using the following code to insert in MYSQL table:

try{
    $sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES(':t_id',':t_name',':mem_id')";
$stmt=db::con()->prepare($sql);
$stmt->bindParam(':t_id',$tid,PDO::PARAM_INT);
$stmt->bindParam(':t_name',$tNm,PDO::PARAM_STR);
$stmt->bindParam(':mem_id',$mId,PDO::PARAM_INT);
$stmt->execute();
}catch(PDOException $ex){
   die("Error occured:".$ex->getMessage());
}

$tid variable has value=1;
$tNm variable has value='CBSE';
$mId variable has value=9

when this piece of code is run then no error is generated but in MYSQL table i observe the field values as 't_id'=0, 't_name'=t_name, 'mem_id'=0.I just don't understand what is wrong with my code.However, one funny thing is that when i try to acomplish the same task using the below mentioned code, proper data is inserted into the table.The code is

$db= new Database();
$db->open();
$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES('$tid','$tNm','$mId')";
$db->query($sql);

Upvotes: 1

Views: 151

Answers (1)

xathien
xathien

Reputation: 822

When using PDO to bind parameters, keep in mind that it appropriately quotes and escapes for you automatically. This means you need to remove the quotes from your VALUES statement, as follows:

$sql="INSERT INTO tblmtd(t_id,t_name,mem_id) VALUES(:t_id,:t_name,:mem_id)";

Upvotes: 1

Related Questions