2017-07-18 82 views
-1

有! 我想做一個數據庫搜索,並以預填​​充的HTML表單將結果顯示回用戶。PHP代碼裏面的HTML值屬性

我找到了不工作的代碼中的確切部分,但我不明白爲什麼PHP不被服務器選中。我正在使用UwAMP。

要在這裏說明的問題是我的短的代碼片段,我需要幫助:

<form id="st_reg" action="" method="POST"> 
     Student Number: 
     <input type="number" name="s_num" min="1000000" max="3000000" > </br> 
     <input type="Submit" value="Search"> 
    </form> 
    <?php 
     if($_SERVER['REQUEST_METHOD'] == "POST"){ 
      if(empty($_POST['s_num'])){ 
       $errors[] = "You forgot to enter the Student No!"; 
      } 
      else{ 
       $st_no = trim($_POST['s_num']); 
      } 
      if(empty($errors)){ 
       //Open database connection 
       require('../../connect_to_database/mysql_connect.php'); 
       //Check if the student is already in the database 
       $query = "SELECT * FROM student WHERE student_no = $st_no"; 
       //Run the query 
       $result = mysqli_query($db_connection,$query); 
       if(!$result){ 
        echo "The student does not exist!"; 
        echo"Please <a href='index.html'>go back</a> and choose another action!"; 
       } 
       elseif($result){ 
        echo "<h2>Student Details:</h2>"; 
        while($row = mysqli_fetch_array($result)){ 
         echo '<form id="st_reg" action="" method="POST"> 
           <label>Student Number:</label> 
            <input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> "> 

與價值屬性中的PHP代碼是不是在它應該在現實中執行。不要打擾GLOBAL php標籤沒有關閉,因爲它們在文件中(我不是那個轉儲)。

請注意,所有這些代碼都在.php文件中,並帶有HTML代碼。這是表單提交後的處理部分。我通過使用單引號進行回聲節省了我的時間,並沿着需要訪問數據庫的方式逃脫了單引號。我在變量周圍嘗試了大括號,用雙引號轉義迴避其中的雙字節,但這些嘗試都沒有成功。 這很奇怪,因爲我可以在此上下文之外完美地回顯$ row ['student_no']並且運行良好。

我也查看了這個網站上的類似問題。他們很接近,但他們幾乎沒有接近這一背景。我願意接受任何建議,並且比解決方案更好。

+1

'當它應該在reality'不,應該不串內執行,尤其是單qutes –

+0

因爲人們花時間來回答,爲什麼,是什麼問題,請不要刪除你的代碼這樣? –

回答

2
echo '<form id="st_reg" action="" method="POST"> 
<label>Student Number:</label> 
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> "> 

應該是這樣的:

echo '<form id="st_reg" action="" method="POST"> 
<label>Student Number:</label> 
<input type="number" name = "st_number" min="1000000" max="3000000" value="' . (isset($row['student_no']) ? $row['student_no'] : '') . '"> 
CONTINUATION OF STRING... 
+0

@GheorgheDonciu這個錯誤來自你的代碼中的另一個地方 –

+0

該錯誤表明你的位後的下一行。下面是我之後,這是表格的其餘部分:

+0

@GheorgheDonciu好了,你的字符串繼續,只是刪除'';'結尾,然後 –

0

下面將做你想做的。

value="<?= (isset($row["student_no"]) ? $row["student_no"] : "") ?>" 

當你已經在PHP塊中時,你不需要擔心所有的轉義。

+0

與@IlyaBursov相似,但仍然有這樣的錯誤:解析錯誤:語法錯誤,意外的'student_no'。 student_no是DB中列的名稱,所以應該沒問題。 我不明白你在PHP塊內轉義的意思。我在一個單引號字符串中,通常如果我想使用單引號,我需要轉義它? –

+0

對不起!我沒有意識到整個事情被單引號迴應。你將不得不使用連接! –