Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP + PDO: Bind null if param is empty

I'm trying this (and all PoST var are treated before user send it, no SQL Injection worries):

$stmt = $con->prepare($sql);
$stmt->bindParam(":1", $this->getPes_cdpessoa());
$stmt->bindParam(":2", $this->getPdf_nupessoa_def());

When any of those vars are NULL, PDO cries and don't let execute my statement, and on my Table, i DO allow these fields beign nullables.

Is there any way to check if the values are empty, pdo just bind NULL to then (and i mean, a smart way instead if(empty($_POST['blablabla')...) for every single param?

like image 581
alex Avatar asked Mar 15 '26 14:03

alex


2 Answers

Try:

$stmt = $con->prepare($sql);
$stmt->bindParam(':1', $this->getPes_cdpessoa(), PDO::PARAM_NULL);
$stmt->bindParam(":2", $this->getPdf_nupessoa_def(), PDO::PARAM_NULL);

Also, see:

  • How do I insert NULL values using PDO?
like image 70
karim79 Avatar answered Mar 18 '26 03:03

karim79


bindParam needs an actual variable to be passed to it, because it creates a reference. So, when your functions return null, bindParam doesn't really have anything valid to do.

You need to use bindValue instead. Note that bindValue will immediately use whatever value you pass to it, where bindParam waits until statement execution to actually retrieve the values to use.

like image 45
John Flatness Avatar answered Mar 18 '26 02:03

John Flatness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!