I am using php & Charts.js to generate a chart of data based off an html <select>
My issue is that even if nothing is selected from the html <select>
a blank chart is displayed at the bottom of the page as opposed to displaying the echo
statement in my else {}
block.
How should I re-write this syntax so that a chart is ONLY created IF a selection is made from the html <select>
<body>
<form method="POST">
<p>Select Sales Name:
<select name="Name">
<option value="">Select A Name...</option>
<option value="Joe">Joe</option>
<option value="Jack">Jack</option>
<option value="Jerry">Jerry</option>
<option value="Jimmy">Jimmy</option></select></p>
<input type="submit" name="submit" value="Show Me">
</form>
</body>
<?php
if (isset($_POST['submit'])) {
$whatsalesprsn = $_POST['Name'];
if ($whatsalesprsn == "Joe") { $region = "East"; }
if ($whatsalesprsn == "Jack") { $region = "West"; }
if ($whatsalesprsn == "Jerry") { $region = "North"; }
if ($whatsalesprsn == "Jimmy") { $region = "South"; }
if (isset($region)) {
$query = "Select * from salesdata where salesregion = '$region'";
$db->setQuery($query);
$rows = $db->loadColumn();
$output = array();
for ($i = 0; $i <= 3; $i++) {
$column = $db->loadColumn($i);
array_push($output, $column);
}
$data = json_encode($output[0]);
} else { echo "PLease select a sales person to display data for."; }
}
?>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</head>
<body>
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div><script>
//JavaScript to generate chart
</script>
</body>
</html>
You need to add if statement
with empty()
function. SO if if statement
will check $whatsalesprsn
variable if is empty or not by using empty()
function
if(!empty($whatsalesprsn)){
$whatsalesprsn = $_POST['Name'];
if ($whatsalesprsn == "Joe") { $region = "East"; }
if ($whatsalesprsn == "Jack") { $region = "West"; }
if ($whatsalesprsn == "Jerry") { $region = "North"; }
if ($whatsalesprsn == "Jimmy") { $region = "South"; }
if (isset($region)) {
$query = "Select * from salesdata where salesregion = '$region'";
$db->setQuery($query);
$rows = $db->loadColumn();
$output = array();
for ($i = 0; $i <= 3; $i++) {
$column = $db->loadColumn($i);
array_push($output, $column);
}
$data = json_encode($output[0]);
}