Burco Burco - 2 months ago 6
MySQL Question

when parameter is empty set own value php mysql

I have this query, which is inserting data to my table:

$stmt = $db->prepare("INSERT INTO reservations
(name, start, end,room_id, status, paid, customer, name_ship, equipment, port,
ETA, ETD, service_id, service_classification, job, active)
VALUES (:name, :start, :end, :room, :status, 0, :customer, :name_ship, :equipment, :port,
:ETA, :ETD, :service_id, :service_classification, :job, 1)");
$stmt->bindParam(':start', $_POST['start']);
$stmt->bindParam(':end', $_POST['end']);
$stmt->bindParam(':name', $_POST['name']);
$stmt->bindParam(':room', $_POST['room']);
$stmt->bindParam(':status', $_POST['status']);
$stmt->bindParam(':customer', $_POST['customer']);
$stmt->bindParam(':name_ship', $_POST['name_ship']);
$stmt->bindParam(':equipment', $_POST['equipment']);
$stmt->bindParam(':port', $_POST['port']);
$stmt->bindParam(':ETA', $_POST['ETA']);
$stmt->bindParam(':ETD', $_POST['ETD']);
$stmt->bindParam(':service_id', $_POST['service_id']);
$stmt->bindParam(':service_classification', $_POST['service_classification']);
$stmt->bindParam(':job', $_POST['job']);

class Result {}

$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
$response->id = $db->lastInsertId();

header('Content-Type: application/json');
echo json_encode($response);

And I would like to chceck if :port has some value and if not, set static value.
So probably like this should go before execute
if (:port =="") {port='9999';} else {:port} or if(empty(:port){}else{}
Am I right?


Just use the ternary operator ?::

$stmt->bindParam(':port', empty($_POST['port']) ? '9999' : $_POST['port']);

empty() is true if either 'port' element is not set in $_POST or if it is set but false or 0 or an empty string.