PHP中从MSSQL数据库提取指定列数据并存储及表格展示的技术咨询
How to Store MSSQL Data and Display It in a Table with PHP
Hey there! Let's fix up your code to both store the product data for later use and display it in a clean HTML table. Here's what you need to do:
Step 1: Store Data in an Array
Right now, your loop overwrites $num and $des with each new row—so you only end up with the last product's data. Instead, we'll use an array to collect all products as we fetch them:
<?php $serverName = "your_server_name"; // Don't forget to fill in your actual server details! $connectionInfo = array( "Database"=>"your_db_name", "UID"=>"your_username", "PWD"=>"your_password"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn ) { echo "Connection established.<br />"; }else{ echo "Connection could not be established.<br />"; die( print_r( sqlsrv_errors(), true)); } // Only select the columns you need (better practice than SELECT *) $sql=" SELECT num_prod, designation_prod FROM produit"; $version = sqlsrv_query($conn,$sql); // Initialize an empty array to store all products $products = []; // Use SQLSRV_FETCH_ASSOC to get clean associative arrays while($row = sqlsrv_fetch_array($version, SQLSRV_FETCH_ASSOC)){ // Add each product to the array $products[] = [ 'num_prod' => $row['num_prod'], 'designation_prod' => $row['designation_prod'] ]; } sqlsrv_close($conn); // Now $products holds all your data for later use! // You can use this array anywhere else in your script (filtering, exporting, etc.) ?>
Step 2: Display Data in an HTML Table
Now that we have all the products stored in $products, we can loop through it to build a table:
<!-- Add this after the PHP code above --> <h2>Product List</h2> <table border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th>Product Number</th> <th>Product Designation</th> </tr> </thead> <tbody> <?php if(!empty($products)): ?> <?php foreach($products as $product): ?> <tr> <td><?php echo htmlspecialchars($product['num_prod']); ?></td> <td><?php echo htmlspecialchars($product['designation_prod']); ?></td> </tr> <?php endforeach; ?> <?php else: ?> <tr> <td colspan="2">No products found in the database.</td> </tr> <?php endif; ?> </tbody> </table>
Quick Tips to Remember:
- Fill in connection details: Make sure
$serverName,$connectionInfohave your actual database credentials (I added placeholders for you). htmlspecialchars(): This escapes special characters in your data to prevent XSS attacks when displaying it in HTML—always use this for user/database data!- Explicit column selection: Using
SELECT num_prod, designation_prodinstead ofSELECT *is more efficient and avoids pulling unnecessary data from the database.
Now you have your data safely stored in the $products array for any future use, plus a clear table to show it on your page!
内容的提问来源于stack exchange,提问作者Hamza El Alamy
相关产品推荐
相关产品推荐

