开发者

PHP PDO MySql - Insert with an occasionally Undefined Variable

开发者 https://www.devze.com 2023-03-06 23:31 出处:网络
A simplified example of a开发者_如何学运维 much more complex issue... A variable is sometimes defined and sometimes isn\'t.WITHOUT checking if the variable is empty, is there a way to execute the inse

A simplified example of a开发者_如何学运维 much more complex issue...

A variable is sometimes defined and sometimes isn't. WITHOUT checking if the variable is empty, is there a way to execute the insert statement without the Query breaking?

    $stmt = $this->db->prepare("INSERT INTO employment (user_id, start_date, end_date) VALUES (:user_id, :start_date, :end_date) ");
    $stmt->bindParam(':user_id', $user->id, PDO::PARAM_INT);
    $stmt->bindParam(':start_date', $work->start_date, PDO::PARAM_STR);
    $stmt->bindParam(':end_date', $work->end_date, PDO::PARAM_STR);
    $stmt->execute();

Sometimes $work->end_date may be non-existent.

Why "WITHOUT checking if variable is empty"? The primary foundation of the site changed and there would be a ton of variable checking. Yes, I know that shouldn't be but it is the problem I inherited.


You could always try to write a wrapper to bindParam which would check your if you variable is defined. If it is then it goes ahead and bindParam otherwise it skips it.

Call it like

bindSafeParam(&$stmt, ':start_date', $work->start_date, PDO::PARAM_STR);


Have a default value if $work->end_date does not exist?

Something like this:

$end_date = empty($work->end_date)? 0 : $work->end_date
$stmt->bindParam(':end_date', $work->end_date, PDO::PARAM_STR);
0

精彩评论

暂无评论...
验证码 换一张
取 消