You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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
  1. Variable Name Separation: We renamed the loop variable to $session_obj to avoid overwriting it when assigning values to $active_session and $session_start_date.
  2. Pre-Initialize Variables: Initializing your target variables before the loop prevents "undefined variable" warnings if the query doesn’t return a matching row.
  3. Handle Both Options: Added an elseif clause to capture the sch_session_start value, since your query fetches two options.
  4. Readable SQL: Replaced || with OR (they’re equivalent in MySQL, but OR is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:33:43