0

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?

10
  • 3
    insert into table (..) values(messageid,reciverid[0]),(messageid,reciverid[1]),(messageid,reciverid[2]) of course as prepared Statements to prevent SQL injection Commented Jul 5, 2017 at 14:15
  • 1
    Show us all the PHP code you are using to process that input into a query Commented Jul 5, 2017 at 14:16
  • 1
    @bruno php has functions like explode Commented Jul 5, 2017 at 14:21
  • 1
    Your script is at risk of SQL Injection Attack Have a look at what happened to Little Bobby Tables Even if you are escaping inputs, its not safe! Use prepared parameterized statements Commented Jul 5, 2017 at 14:21
  • 1
    @Bruno yes explode your string and for every entry add the values to insert Commented Jul 5, 2017 at 14:24

2 Answers 2

1

You can do something like this:

$messageid = "2";         // received value
$receiverids = "5,6,34";  // received value
$receiverid = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO `table` (`message_id`, `receiver_id`) VALUES (?, ?)");
$stmt->bind_param("ss", $messageid, $receiverid);

foreach($rid in explode($receiverids)) {
   // set parameters and execute
   $receiverid = $rid;
   $stmt->execute();
}

$stmt->close();
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, edited your question instead of mine. Beg your pardon
0

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.

1 Comment

Thank you for taking the time to comment the code, it really helped me understand what was going on, much appreciated sir!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.