Display Mysql table field values in Select box

前端 未结 6 1288
失恋的感觉
失恋的感觉 2021-02-06 06:16

I want to display the Mysql table Filed values in selectbox. I tried the following code to display. But it normally display the specified field values in echo function and not i

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 06:55

    There a few tips to offer that will condense the code block for this task -- too many to just comment under the accepted answer.

    Tested Code:

    if (!$con = new mysqli("localhost", "root", "root", "Time_sheet")) {
        echo "Database Connection Error: " , $con->connect_error;  // don't show actual error in "production" stage
    } elseif (!$result = $con->query("SELECT Emp_id FROM Employee ORDER BY Emp_id")) {
        echo "Syntax Error: " , $con->error;  // don't show actual error in "production" stage
    } else {
        echo "";
    }
    
    • The if line is both declaring $con and checking it for a falsey return value in one step.
    • Never provide the raw connection or query errors to your users. It is okay during development, but you don't want strangers to have access to critical/informative errors that your server will provide. This is a basic best practice for security.
    • The elseif line is both declaring $result and checking it for a falsey return value in one step.
    • The else block will process the zero or more rows of data that were generated as a result of the successful SELECT query.
    • The mysqli result is "traversable" which means you can iterate it using foreach() and enjoy direct access to the row data via associative keys. PHP Manual Reference Another StackOverflow Post
    • When writing an array element into a literal string via interpolation, it is good practice (though not always necessary) to wrap the element in curly braces. This will often trigger helpful highlighting in IDEs and ensure that the characters that follow the array are not accidentally coupled to the variable name itself.
    • You ONLY need to write a value attribute inside of the tag IF the value is different from text between the opening and closing tags (). Form submissions and javascript implementations will all work the same if you omit the redundant value attribute.
    • If you DO wish to submit a different value in the select field rather than the text, here is what the syntax can look like:

      echo "";
      
    • If you want to write a selected attribute on one of the options based on a pre-existing variable (e.g. $selected_id), it can look like this:

      echo "{$row['Emp_name']}";
      
    • If you wanted to combine the two previous processes, it can look like this:

      echo "";
      

提交回复
热议问题