我有下表:
id | message_id | recevier_id
1 | 8 | 2
2 | 9 | 5
3 | 14 | 4
我将数据发送到PHP文件以添加到上表中。我的数据如下:
messageid =“2” 接收者id =“5,6,34”
我正在尝试添加具有不同“接收者ID”的多行,因此上述查询的结果应该导致:
id | message_id | recevier_id
1 | 8 | 2
2 | 9 | 5
3 | 14 | 4
4 | 2 | 5
5 | 2 | 6
6 | 2 | 34
我当前的MySQL查询如下所示:
<?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;
?>
我怎样才能做到这一点?
答案 0 :(得分:1)
您可以这样做:
$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();
答案 1 :(得分:0)
假设$ _POST中存在2个名为
的字段$_POST['messageid'] = "2"
$_POST['receiver id'] = "5,6,34"
然后可以像这样创建3行
请记住,一旦准备好带参数的查询,它就可以重复使用任意次,每次执行时都会有新的参数值。
<?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();
}
}
}
?>
如果你正在使用INNODB数据库,你也可以围绕这个包装一个事务,这样你就可以创建所有3行,或者如果在创建3个新行时某处发生错误则根本没有。