Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO not inserting - no error [duplicate]

I do not understand why these lines do not work:

  $host = 'localhost';
  $dbname='mydbname';
  $login='mylogin';
  $pwd='mypwd';
  $datex = date('Y/m/d H:i:s');
  $nomx = 'jrmy';
  $numx = '007';
  try {
    $bdd = new PDO('mysql:host='.$host.';dbname='.$dbname, $login, $pwd);
  }
  catch(Exception $e) {
    die('Erreur : '.$e->getMessage());
  }
  $bdd->exec('INSERT INTO dossiers(date, nom, numero, disp) VALUES(\''.$datex.'\', \''.$nomx.'\', \''.$numx.'\', \'Y\')');
  $id = $bdd->lastInsertId();
  $bdd= null;
  echo 'id: '.$id;

disclosure: the script worked on my apache server, and since I installed my script on a IIS server it stopped working...

AND the query function works perfectly... query OK, insert NO

EDIT : thank you all! really!

like image 651
jrm Avatar asked Jan 23 '13 16:01

jrm


2 Answers

You need to tell PDO to raise an error

$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Please note that the way you're handling exceptions is quite useless. It would be better to remove try-catch blocks from the code

like image 153
Your Common Sense Avatar answered Oct 19 '22 18:10

Your Common Sense


You are not making full use of PDO. Use parameters to insert your data

Example:

$bdd->exec('INSERT INTO dossiers(date, nom, numero, disp) VALUES(?, ?,?, ?)');
$bdd->bindParam(1, $datex);  
$bdd->bindParam(2, $nomx);  
$bdd->bindParam(3, $numx);
$bdd->bindParam(4, 'Y');

And use this to raise errors:

$bdd->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
like image 4
Ibu Avatar answered Oct 19 '22 17:10

Ibu