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

PHP从MySQL转mysqli后,基于explode/implode的复选框回显失效求助

Fixing Checkbox State Not Showing Up with PHP mysqli

Hey there, let's troubleshoot why your checkbox checked states stopped working after switching to mysqli. I've gone through your code and spotted a few key issues that are likely causing the problem:

1. Variable Scope Issue with Database Connection

Your GetCheckboxes function uses $con directly, but if this connection variable is defined in koneksi.php (a separate file), the function doesn't have access to it by default. Unlike the old mysql_* functions which used the last open connection automatically, mysqli requires you to explicitly pass the connection or make it available in the function's scope.

2. Missing Quotes for Array Keys

When you access $r[user_course], you're using an unquoted string as an array key. While PHP allows this in non-strict mode, it can lead to unexpected behavior (PHP treats it as a constant first, falling back to a string only if no constant exists). This might be preventing you from correctly retrieving the stored checkbox values from the users table.

3. Lack of Error Checking

You're not validating if your mysqli queries succeed. If a query fails (e.g., wrong table name, connection glitch), you won't get any feedback, making it hard to debug why no checkboxes are checked.


Fixed Code Implementation

First, Update the GetCheckboxes Function

Pass the database connection as a parameter (better practice than relying on global scope for maintainability):

function GetCheckboxes($con, $table, $key, $Label, $Nilai='') {
    // Add error checking for the query
    $s = "SELECT * FROM $table ORDER BY id_course";
    $r = mysqli_query($con, $s);
    if (!$r) {
        die("Query failed: " . mysqli_error($con));
    }

    $_arrNilai = explode(',', $Nilai);
    $str = '';
    while ($w = mysqli_fetch_array($r, MYSQLI_ASSOC)) { // Use associative array explicitly
        // Clean up value check with in_array()
        $_ck = in_array($w[$key], $_arrNilai) ? 'checked' : '';
        $str .= "<div>
            <input type='checkbox' name='".$key."[]' value='$w[$key]' $_ck> 
            $w[$Label]
        </div>";
    }
    return $str;
}

Then, Update the Profile Page Code

Fix array key quotes, add session start, and pass the connection to the function:

// Always start session before accessing $_SESSION
session_start();
include 'koneksi.php'; // Include your connection file

$sql = mysqli_query($con,"SELECT * FROM users WHERE user_email='{$_SESSION['emailuser']}'");
// Verify query success and user existence
if (!$sql || mysqli_num_rows($sql) === 0) {
    die("User not found or query failed: " . mysqli_error($con));
}
$r = mysqli_fetch_array($sql, MYSQLI_ASSOC); // Use associative array for clarity

// Render checkboxes, pass $con as the first parameter
echo "<label><h4>Course you are applying for:</h4></label>";
$d = GetCheckboxes($con, 'main_course', 'course_seo', 'course_name', $r['user_course']);
echo $d;

Additional Notes

  • Don't forget session_start() at the top of any page using $_SESSION variables (I added this since it was missing in your original code).
  • Using MYSQLI_ASSOC instead of MYSQLI_BOTH keeps your code cleaner by only returning associative keys, avoiding confusion with numeric indexes.
  • in_array() is a more straightforward alternative to array_search() for checking if a value exists in an array.

Content of the question comes from Stack Exchange, question author: putu mega

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:31:46