PHP MySQL Inserts Multiple Lines with Different IDs

advertisements

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\n", 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?


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\n", 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.