douhoujun9304 2017-07-05 14:12
浏览 28
已采纳

PHP MySQL插入具有不同ID的多行

I have the following table:

id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4

I am sending data to a PHP file to add to the above table. My data is as follows:

messageid = "2" receiver id = "5,6,34"

I am trying to add multiple rows with different "receiver id", so the outcome of the above query should result in :

id | message_id | recevier_id
 1 |      8     |    2
 2 |      9     |    5
 3 |     14     |    4
 4 |      2     |    5
 5 |      2     |    6
 6 |      2     |   34

My current MySQL query looks like this:

<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
session_start();
include_once '../../../includes/database.php';
$uid = $_SESSION['usr_id'];
$sendername = $_SESSION['firstnames'].' '.$_SESSION['surname'];

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s
", mysqli_connect_error());
        exit();
    }

    foreach ($inputvalues as $key => $value) {
        if(isset($value) && !empty($value)) {
            $inputvalues[$key] = $mysqli->real_escape_string( $value );
        } else {
            $errors[$key] = 'The field '.$key.' is empty';
        }
    }

    if( !$errors ) {
        $mysqli->query("
            INSERT INTO `message_receiver_map` (`message_id`, `receiver_id`) VALUES ('".$messageid."', '".$inputvalues['receiverid']."');
        ");
        $returnResult = "Success";
    }
    mysqli_close($mysqli);
    echo json_encode(['result' => $returnResult, 'errors' => $errors]);
    exit;
?>

How can I achieve this?

  • 写回答

2条回答 默认 最新

  • dougou5844 2017-07-05 14:38
    关注

    Assuming 2 field in $_POST exist called

    $_POST['messageid'] = "2" 
    $_POST['receiver id'] = "5,6,34"
    

    Then the creation of the 3 rows can be done like this

    Remember that once a query with parameters has been prepared, it can be reused any number of times, with new parameter values each time it is executed.

    <?php
        session_start();
        include_once '../../../includes/database.php';
    
        // this if should probably be in your database.php script
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s
    ", mysqli_connect_error());
            exit();
        }
    
        if ( isset($_POST['messageid'],$_POST['receiver id']) ){ 
            // proceed to create the new rows
    
            //create a query
            $sql = "INSERT INTO `message_receiver_map` 
                            (`message_id`, `receiver_id`) 
                    VALUES (?,?)";
    
            // prepare the query (send to server and compile it)
            // now this query can be run multiple times with different 
            // parameter set each time it is executed
            $stmt = $mysqli->prepare($sql);
    
            // now for each receiver_id run the query
            $rec_ids = explode($_POST['receiver id']);
    
            foreach ($rec_ids as $rec_id) {
                // bind the 2 parameters from this iteration to the query
                $stmt->bind_value('ii', 
                                    $_POST['messageid'],
                                    $rec_id);
                // run query with these new params
                $result = $stmt->execute();
            }
        }
    }
    ?>
    

    If you are using a INNODB database you could also wrap a transaction around this so the you get all 3 rows created or none at all if an error occurs somewhere while creating the 3 new rows.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型