Search code examples
phppdopaypalpaypal-ipn

PDO in ipn doesnt insert


Hey there i have a problem inserting custom data in my databse during the ipn process, this is the scenario, i am using http_build_query to send data:

require_once 'classes/Crypt.php';
$crypt = new Crypt();
$crypt->Mode = Crypt::MODE_HEX;
$crypt->Key  = '!@#$%&*()_+?:';

$test = array('cmd'=>'_xclick',
                'business'=>'my_email',
                'notify_url'=> $home_url.'/ipn/ipn.php',
                'item_name'=>'name',
                'amount'=>'1.00',
                'currency_code'=>'USD',
                'lc'=>'US',
                'custom'=>$crypt->encrypt(serialize(array("username" => $username))));


                $url = "https://www.sandbox.paypal.com/cgi-bin/webscr?".http_build_query($test);
                header("Location:".$url);
                exit();

My ipn-script where i use PDO bindParam to insert data:

require_once '../classes/Crypt.php';

$crypt = new Crypt();
$crypt->Mode = Crypt::MODE_HEX;
$crypt->Key  = '!@#$%&*()_+?:';

$custom = unserialize($crypt->decrypt($_POST["custom"]));

$username = $custom['username'];

try
{
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->prepare("INSERT INTO products(product_name)
                    VALUES(:productName)");
    $stmt->bindParam(':productName', $productName);

    $productName = $username;

    $stmt->execute();
}
catch(PDOException $exception)
{
    $body .= "Fail: " . $exception->getMessage() . "\n";
}

There is no insert, but i get this error in my log:

Fail: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'product_name' cannot be null

Data is send for sure, i checked it using echo before directing to paypal. My table products:

CREATE TABLE products (
    id int(11) NOT NULL auto_increment,
    product_name varchar(55) NOT NULL,

    PRIMARY KEY (id),
    UNIQUE KEY product_name (product_name)
);

At the moment i really have no idea why the query isnt executed, anybody know´s this specific problem or where my mistake? thanks for help! greetings!


Solution

  • $stmt = $dbh->prepare("INSERT INTO products(product_name)
                    VALUES(:productName)");
    $stmt->bindParam(':productName', $productName);
    
    $productName = $username;
    

    You bind $productName while it has NULL, then after binding, you assign value to it. Assign value to productName before binding:

    $productName = $username;
    
    $stmt = $dbh->prepare("INSERT INTO products(product_name)
                    VALUES(:productName)");
    $stmt->bindParam(':productName', $productName);
    

    EDIT:

    //check $username
    var_dump($username);
    $test = array('cmd'=>'_xclick',
                     ....
                    'custom'=>$crypt->encrypt(serialize(array("username" => $username))));
                     ....
    
    ...
    $custom = unserialize($crypt->decrypt($_POST["custom"]));
    //check $custom
    var_dump($custom);