Reputation: 364
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', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Upvotes: 0
Views: 243
Reputation: 30893
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\[email protected]\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.
Upvotes: 1