php - 用逗号(,)将数组数据存储到字符串中

标签 php mysql

[!]问题:每当我从前端获取数据并尝试插入数据库时​​...数据将作为单个字母插入到选修单元格中...但我真正需要的是插入整个数据在选修单元格中,用逗号(,)分隔

1

<?php
include_once '../../config/db_connection.php';
include_once '../../config/functions.php';
include "autho.php";
include('../db_mysqli.php');
if (isset($_POST['submit'])) {
$username1 = $_POST['username'];
$username1 = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $username1);
$rollno = $_POST['register_no'];
$rollno = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $rollno);

$subjectcode = implode(',', $_POST['subject']);   ;

date_default_timezone_set("Asia/Kolkata");

$today = date('g:ia \o\n l jS F Y');

$rollnos = array_map('strlen', $rollno);
$rollnos = min($rollnos);
if ($rollnos < 6) {
    $error = 'Roll Number is too short.';
} else {
}
if (!isset($error)) {
    for ($i = 0; $i < count($rollno); $i++) {
$sql = "UPDATE students SET elective='$subjectcode[$i]' WHERE register_number='$rollno[$i]'";
$result = mysqli_query($conn, $sql);
if ($result) {
header('Location:./?edu_camp=elective_student_update&success');

        } else {
             header('Location:./?edu_camp=elective_student_update&fail');
        }
    }

} else {
    //echo "Sorry! something Wrong.";
}

}
?>

最佳答案

正如评论中提到的,您可以将数组内爆到字符串中并将其插入( docs )。

此外,您正在使用 MySQLi,但没有使用您真正应该使用的绑定(bind)参数 ( docs )。

// Concatenate all values together
$commaSeparatedList = implode(',',$subjectcode);
// Prepare your statement
$stmt = $mysqli->prepare("UPDATE students SET elective=? WHERE register_number=?");
// Bind the relevant parameters (not sure what the where clause should be here)
$stmt->bind_param('si', $commaSeparatedList, $i);
// Check if rows were affected
if ($mysqli->affected_rows > 0) {
   // Success, rows were changed
}
// Execute and close the statement object
$stmt->execute();
$stmt->close();

关于php - 用逗号(,)将数组数据存储到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49751223/

相关文章:

python - Django queryset.query 和在 mysql 控制台中运行的查询没有给出相同的结果

mysql - LEFT JOIN 不会响应

php - 数组是空的,但它一直认为里面有东西

php - 按列对表格中的数据进行排序

php - Doctrine/Swagger-php 语法错误 : [Syntax Error] Expected PlainValue, 在位置得到 ')'

mysql - 使 View 永久化

PHP 循环数组直到索引改变

PHP/MySQL - 删除不工作

php - MYSQL数据库的问题

php - Mysql:检查范围时间冲突