PDO with empty variables

Hi I am using the following statement

    $stmt->bindValue(':atown', $_POST['ad_town'], PDO::PARAM_STR);

How can I run this if the post variable is empty. What is the easiest way? As it breaks the insert

Not 100% sure on this but worth a shot.

$ad_town = (isset($_POST['ad_town']) && !empty($_POST['ad_town']) ? $_POST['ad_town'] : null);
$stmt->bindValue(':atown', $ad_town, PDO::PARAM_STR);

That looks like it should work as long as the atown field accepts NULL.

Otherwise maybe do an INSERT IGNORE instead of an INSERT ??

Or just don’t perform the query altogether if there is no value


<?php
if (isset($_POST['ad_town']))
{
    $stmt = $db->prepare('....');
    $stmt->bindValue(':atown', $_POST['ad_town'], PDO::PARAM_STR);
    $stmt->execute();
}

Or, if empty values are allowed, go with @Drummin; 's suggestion :slight_smile: