May11
May11

Reputation: 155

PHP PDO silently not inserting

This is driving me crazy... I'm trying to insert using prepared statement and the thing fails silently. Here's the code:

$sql = 'INSERT INTO payments (id_fix, name, date, comment, timestamp) VALUES (:id_fix, :name, :date, :comment, :timestamp)';
$q = $this->PDO->prepare($sql);

$a = array(
'id_fix' => $r['id'],
'name' => $r['name'],
'date' => $r['evt_date'],
'comment' => $this->comment,
'timestamp' => $r['timestamp']);

$q->execute($a) or die ('NAPAKA');

$r is from another query. I know I should do simple subquery but I'd like to solve this thing.

If I change

'id_fix' => 0

it works! If I echo $r['id'] it's a valid number.

'id_fix' => intval($r['id'])

won't work.

Any ideas? :-S

Upvotes: 1

Views: 398

Answers (3)

user2560539
user2560539

Reputation:

$sql = 'INSERT INTO payments (id_fix, name, date, comment, timestamp) VALUES (:id_fix, :name, :date, :comment, :timestamp)';
$q = $this->PDO->prepare($sql);

$q->bindParam(':id_fix',$r['id_fix']);
$q->bindParam(':name',$r['name']);
$q->bindParam(':date',$r['date']);
$q->bindParam(':comment',$r['comment']);
$q->bindParam(':timestamp',$r['timestamp']);

$q->execute() or die ('NAPAKA');

Upvotes: 1

LSerni
LSerni

Reputation: 57453

If I change

 'id_fix' => 0

it works! If I echo $r['id'] it's a valid number.

 'id_fix' => intval($r['id'])

won't work.

A simple explanation that would account for these symptoms is this: the table you are inserting in has a PRIMARY INDEX AUTO_INCREMENT on id_fix. Sending 0 has the effect of nulling the parameter, which means the a new ID is generated automatically. And it works.

The other ids you are trying to insert are already existing, and cause an error.

I'm not saying - I can't guarantee - that this is the explanation, but it is an explanation, and without a more detailed error message, I'm afraid that's the best that can be done.

You need to activate error reporting, use PDO exceptions, and surround your queries with try/catch.

Upvotes: 0

meda
meda

Reputation: 45500

the thing fails silently - OP

You need to check for errors, read up On Errors and error handling

try {
    $this->PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = '
    INSERT INTO payments 
                (id_fix, 
                 NAME, 
                 date, 
                 comment, 
                 timestamp) 
    VALUES      (:id_fix, 
                 :name, 
                 :date, 
                 :comment, 
                 :timestamp) 
    ';
    $q = $this->PDO->prepare($sql);

    $a = array(
    'id_fix' => $r['id'],
    'name' => $r['name'],
    'date' => $r['evt_date'],
    'comment' => $this->comment,
    'timestamp' => $r['timestamp']);

    $q->execute($a);

} catch (PDOException $e) {
    echo 'Query failed: ' . $e->getMessage();
}

Upvotes: 0

Related Questions