2017-07-19 62 views
1

我正在使用php & Charts.js生成基於html的數據圖表我的問題是即使沒有從html <select>中選擇任何內容,空白圖表顯示在而不是在我的else {}區塊中顯示echo聲明。只生成圖表如果PHP變量具有值

如何使圖表是ONLY創建如果選擇從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> 
+0

'如果{...}'試試這個 –

+0

@ Mr.Developer - 你在哪裏建議我將此檢查添加到我當前的語法中? – BellHopByDayAmetuerCoderByNigh

+0

在這之後'$ whatsalesprsn = $ _POST ['Name'];' –

回答

0

您需要添加if statementempty()函數。 (!空($ whatsalesprsn)),所以如果if statement將檢查$whatsalesprsn變量,如果是空的或不使用empty()功能

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]); 
} 
0

某處你必須調用new Chart(...)做我應該重寫此語法。如果你這樣做而不傳遞有效的數據,那麼Chart.js將創建一個空的圖表(因爲這是你告訴它做的)。

如果你沒有得到有效的數據(即什麼也沒有選擇在該<select>元素),不要實例chart.js之。例如:

if (data.length) { 
    new Chart(...); 
}