Foreach循环未按预期工作:数据库取值变量赋值问题
Problem Analysis
The core issue here is variable name collision in your foreach loop. You’re using the same variable name $session for both the loop’s current object and the value you’re trying to assign. When you run $session = $session->option_value, you overwrite the loop variable (which was an object) with a string. This breaks subsequent iterations because PHP can’t access the option_name property on a string—leading to unexpected behavior or errors.
Solution
Rename the variable you’re assigning the value to, so it doesn’t conflict with the loop variable. You can also structure the code to cleanly handle both options your query is fetching.
Corrected Code
$sql_session = $wpdb->get_results("SELECT option_name, option_value FROM $settings_table WHERE option_name='session' OR option_name='sch_session_start'"); echo "<pre>"; print_r($sql_session); echo "</pre>"; // Initialize target variables first (avoids undefined variable warnings) $active_session = ''; $session_start_date = ''; foreach ($sql_session as $session_obj) { // Use a distinct name for the loop object if ($session_obj->option_name === "session") { $active_session = $session_obj->option_value; } elseif ($session_obj->option_name === "sch_session_start") { $session_start_date = $session_obj->option_value; } } // Use your variables as needed echo "Active Session: " . $active_session . "<br>"; echo "Session Start Date: " . $session_start_date;
Key Fixes Explained
- Variable Name Separation: We renamed the loop variable to
$session_objto avoid overwriting it when assigning values to$active_sessionand$session_start_date. - Pre-Initialize Variables: Initializing your target variables before the loop prevents "undefined variable" warnings if the query doesn’t return a matching row.
- Handle Both Options: Added an
elseifclause to capture thesch_session_startvalue, since your query fetches two options. - Readable SQL: Replaced
||withOR(they’re equivalent in MySQL, butORis more readable for most developers).
Additional Tips
- If you only need a single value, use
$wpdb->get_var()for more efficient code:$active_session = $wpdb->get_var("SELECT option_value FROM $settings_table WHERE option_name='session'"); - Always sanitize and validate database results before using them in your application to avoid security risks.
内容的提问来源于stack exchange,提问作者Waeez
相关产品推荐
相关产品推荐

