gpt4 book ai didi

php - 如何使用explode implode从数据库中选中和取消选中复选框

转载 作者:行者123 更新时间:2023-11-29 17:34:24 25 4
gpt4 key购买 nike

这是一个与复选框相关的经典问题,我试图找到答案但找不到。请帮忙。

我尝试使用 php mysqli 在数据库中发布和编辑复选框。这就是我所做的。

首先,我创建了连接并将其另存为 koneksi.php

$con = mysqli_connect("localhost","username","password","database_table");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

接下来我创建了profile.php

**// I created a function to call different tables**

function GetCheckboxes($table, $key, $Label, $Nilai='') {
$s = "select * from $table order by id_course";
$r = mysqli_query($con, $s);
$_arrNilai = explode(',', $Nilai);
$str = '';
while ($w = mysqli_fetch_array($r)) {
$_ck = (array_search($w[$key], $_arrNilai) === false)? '' : 'checked';
$str .= "<div>
<input type='checkbox' name='".$key."[]' value='$w[$key]'
$_ck>
$w[$Label]

</div> ";
}
return $str;
}


**// I called the user's checked checkboxes from 'users' table on 'user_course' column **

$sql = mysqli_query($con,"SELECT * FROM users WHERE user_email='$_SESSION[emailuser]'");
$r = mysqli_fetch_array($sql,MYSQLI_BOTH);


**// and displayed them associated from 'main_course' table.
//The checkboxes lists are taked from 'main_course' table
//and the checked value are taken from 'users' table on 'user_course' column**

echo"<label><h4>Course you are applying for:</h4></label>";
$d = GetCheckboxes('main_course', 'course_seo', 'course_name', $r[user_course]);

echo " $d ";

这是我的表,我将从中检索数据类(class)。在本例中,它是“main_course”表。 http://prntscr.com/jjgoqm

这是“用户”表,我使用 implode() http://prntscr.com/jjhnu7 获取并保存复选框选中的值。

这是选中复选框并将其保存到“user_course”列中的“users”表中后的结果。 http://prntscr.com/jjhrbe它可以在 php mysql 上运行,但是当我将其更改为 mysqli 时,它不起作用,它变成了这样 http://prntscr.com/jjhv82它消失了。它可以在 mysql 上运行,但不能在 mysqli 上运行

请问这是怎么回事?

感谢您的帮助。

最佳答案

我可以看到两个问题。第一个(这很可能导致您的代码无法工作)是 $con 超出了 GetCheckboxes 函数的范围。您需要将其添加为参数或将 global $con; 语句添加到该函数的开头,即

function GetCheckboxes($table, $key, $Label, $Nilai='') {
global $con;
$s = "select * from $table order by id_course";
$r = mysqli_query($con, $s);
...

第二个(不太重要,因为它只会导致 NOTICE 级别错误),在调用 GetCheckboxes 时,$r[user_course]应为 $r['user_course']

如果您打开PHP error reporting (error_reporting(E_ALL);) 您会看到导致代码无法运行的错误。

关于php - 如何使用explode implode从数据库中选中和取消选中复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50410752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com