如何在PHP的try-catch语句中输出SELECT查询结果
Hey there! Let's get your SELECT query results showing up properly. The issue you're running into is that you haven't actually retrieved and processed the result set from your database query yet—just using echo or print directly at that spot won't work because there's no result data being passed to those functions. Let's break down the fix step by step:
第一步:修正字符集设置的错误
First, I notice a mistake in your charset configuration. The mysqli_set_charset() function only takes the character set name as its second parameter. Your second call to it uses a full SQL string, which won't work. Instead, set it up like this:
// Set connection charset (utf8mb4 is recommended for full Unicode support) mysqli_set_charset($polaczenie, 'utf8mb4'); // If you specifically need Polish collation, run this separate query $polaczenie->query("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_polish_ci'");
第二步:执行SELECT查询并输出结果
Now, at the spot where you wrote echo "HERE"????, you need to run your query, retrieve the results, and then output them. Here's how to integrate this into your existing code:
try { $polaczenie = new mysqli($host, $db_user, $db_password, $db_name); if ($polaczenie->connect_errno != 0) { throw new Exception($polaczenie->connect_error); // Fixed: use mysqli's native error property } else { // Fixed charset setup mysqli_set_charset($polaczenie, 'utf8mb4'); $polaczenie->query("SET NAMES 'utf8mb4' COLLATE 'utf8mb4_polish_ci'"); // -------------------------- // Replace echo "HERE"???? with this section // -------------------------- // 1. Define your actual SELECT query $sql = "SELECT column_name1, column_name2 FROM your_table_name"; // Update with your table/columns // 2. Execute the query $result = $polaczenie->query($sql); if (!$result) { throw new Exception($polaczenie->error); // Catch SQL syntax/permission errors } // 3. Output results based on expected row count // For multiple rows: while ($row = $result->fetch_assoc()) { // Access columns by their names from the SELECT query echo "Column 1: " . htmlspecialchars($row['column_name1']) . "<br>"; echo "Column 2: " . htmlspecialchars($row['column_name2']) . "<br><br>"; } // For a single row (remove the while loop above if using this): // $row = $result->fetch_assoc(); // if ($row) { // echo "Result: " . htmlspecialchars($row['column_name1']); // } // Free up memory after using the result set $result->free(); // -------------------------- $polaczenie->close(); } } catch (Exception $e) { echo "Error occurred: " . $e->getMessage(); }
关键细节说明
fetch_assoc(): This function pulls each row of your result set into an associative array, where the keys match your column names from the SELECT query.htmlspecialchars(): Adding this around your output prevents XSS vulnerabilities if you're displaying user-provided data.- Error checking: Always verify that
$resultis valid—this helps catch typos in your SQL or database permission issues quickly.
内容的提问来源于stack exchange,提问作者Marko sean

