Textarea每行都是db中的新值

时间:2015-05-21 20:37:30

标签: php database insert textarea

我想知道如何使用textarea来使每一行成为我数据库中的新值。

例如,我将其放在文本区域中:

1
2
3

然后每个值(1,2,3)将作为不同的值出现。 我该怎么办呢?

以下是我目前正在做的事情:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

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

$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

1 个答案:

答案 0 :(得分:1)

假设您的文字是:

1\r\n
2\r\n
3\r\n

您可以根据标记行尾(在Windows中)的回车符(\r),新行(\n)字符进行分隔。或者只是New Line,因为Linux将仅使用New Line作为EOL。

http://php.net/manual/en/function.explode.php

例如,假设您从表单中获取以下数据:

"John\r\nDoe\r\njohn@example.com\r\n"

我们使用explode()将其分块为数组:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

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

$parts = explode("\n", $_POST['myTextBox']);

$sql = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$sql->bind_param($sql, 'sss', $parts[0], $parts[1], $parts[2]);

if ($sql->execute() === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: . $conn->error;
}

$conn->close();
?>

这很危险,因为您几乎无法控制表单输入。我会将这些分成3个独特的文本框。我还会在提交表单之前和之后,当PHP提取数据时验证输入。