简体   繁体   中英

Textarea each line is a new value in the db

I'm wondering how I could use the textarea in order to make each line a new value in my database.

So for example, I'd put this in a text area:

1
2
3

And then each value (1,2,3) would come up as different values. How can I proceed doing this?

Here is what I am currently doing:

<?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();
?>

Assuming your text is:

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

You can separate based on the Carriage Return ( \\r ), New Line ( \\n ) characters that marks the end of line (in Windows). Or just the New Line, since Linux will use just New Line for the EOL.

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

So let's say for example you get the following data from your form:

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

We use explode() to chunk this into an array:

<?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();
?>

This is rather dangerous since you have very little control over the form input. I would break these into 3 unique text boxes. I would also validate both the input before the form is submitted and after, when PHP ingests the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM