gpt4 book ai didi

php - 如何根据checkbox值将数据存储到多个MySQL表中?

转载 作者:行者123 更新时间:2023-11-29 05:16:19 26 4
gpt4 key购买 nike

我有一个 html 表单,有多个复选框(主题)当用户(学生)选择科目时,StudentID 与在不同列中所做的选择一起存储在 MySQL 表中,但在同一个表中。

我的问题是:如果复选框值“等于”某个值,我如何将学生 ID 存储在新表中,strpos 会这样做吗?

例如:

if (strpos($cc,'252000') !== false) {
mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb)
VALUES ('$studentid','$cc')");
}

完整代码:

<?php
$host = 'localhost';
$port = 8889;
$username="root" ;
$password="root" ;
$db_name="db1" ;
$tbl_name="courses" ;
$tbl_name="studentinfo";
$tbl_name="newtable";

$dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
mysqli_set_charset($dbcon, "utf8");


if (!$dbcon) {
die('error connecting to database'); }


$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']); //echo $studentid;

$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courses){
$cc=$cc. $courses.',';
}
}

if (strpos($cc,'252000') !== false) {

mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb)
VALUES ('$studentid','$cc')");

echo "$cc, trtue";
}

HTML

<form action="cdb.php" method="get">

<input name="studentid" type="text" id="studentid" maxlength="11"value="Student ID" />

<input type="checkbox" name="ckb[]" value="251000-1"/>
<input type="checkbox" name="ckb[]" value="251000-2"/>

最佳答案

好吧,如果你绝对必须忽略所有好的数据库设计实践,试试这个。

不是创建逗号分隔的列表并将其放入新表,而是使用 serialize() 函数将 $_GET['ckb'] 的内容放入其中新行。至少通过这种方式,您可以使用 unserialize() 取回一个数组,这使得操作数据更容易,即使它不会使搜索数据库更容易。

您可以用 json_encode()json_decode() 替换序列化/反序列化

引用资料:

serialize: http://php.net/manual/en/function.serialize.php

unserialize: http://php.net/manual/en/function.unserialize.php

<?php
$host = 'localhost';
// I assume you moved apache to port 8889.
// so its irrelevant to mysql connection,
// good job you are not actually using this variable anywhere
$port = 8889;
$username="root" ;
$password="root" ;
$db_name="db1" ;

// fix so you have 3 variables and are not overwriting the same one
$tbl_name1="courses" ;
$tbl_name2="studentinfo";
$tbl_name3="newtable";

// remove unnecessary double quotes
$dbcon = mysqli_connect($host,$username,$password,$db_name) ;

// add some error checking that reports the actual error
if ( ! $dbcon ) {
echo 'Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error();
exit;
}

mysqli_set_charset($dbcon, "utf8");



if(isset($_GET['ckb'])) {
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']);
$cc = serialize($_GET['ckb']);
$result = mysqli_query($dbcon,"INSERT INTO newtable
(studentid,ckb)
VALUES ('$studentid','$cc')");
if ( ! $result ) {
echo mysqli_error($dbcon);
exit;
}
}
?>

关于php - 如何根据checkbox值将数据存储到多个MySQL表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32271997/

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