3

I want to insert multiple emails into the database using single text area.

This is my code :

PHP

error_reporting(E_ERROR | E_WARNING | E_PARSE);

$dbhost = "localhost";
$dbname = "emails_test";
$dbuser = "root";
$dbpass = "";

$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $conn);

if(isset($_POST['submit'])) {
    //$email = nl2br($_POST['email']);
    $email = explode("\r\n", $_POST['email']);

    foreach($email as $emails) {
        $query = mysql_query("INSERT INTO emails (email) VALUES ('$emails')");
        if($query) { echo "Inserted into the database"; } else { echo"Fail, please try again"; }
    }
}

HTML

<body>
    <form name="form1" method="POST">
        <textarea rows="5" name="email" cols="50" ></textarea><br>
        <input type="submit" name="submit" value="submit">
    </form>
</body>

I want table to be like this : [Pic Table in MySQL]

Que
  • 35
  • 7

4 Answers4

2

Use explode to get string into array by "\r\n"

don't use single quotes you need to use double quotes to explode the string by \r\n I just got to know that.

<?php
if(isset($_POST['submit'])) {
    //$email = nl2br($_POST['email']);
    $email = explode("\r\n", $_POST['email']);

    foreach($email as $emails) {
        $query = mysql_query("INSERT INTO emails (email) VALUES ('$emails')");
        if($query) {
            echo "Inserted into the database";
        } else {
            echo "Fail, please try again";
        }
    }
}
?>
<body>
    <form name="form1" method="POST">
        <textarea rows="5" name="email" cols="50" ></textarea>
        <br />
        <input type="submit" name="submit" value="submit">
    </form>
</body>
Prateik Darji
  • 2,297
  • 1
  • 13
  • 29
  • Only if you are assuming he's getting a list into the text area. – Forbs Jan 11 '18 at 04:51
  • yes it will works for text area, using enter key press after every email to saperate that email – Prateik Darji Jan 11 '18 at 04:53
  • Thanks. I already try to use this `$email = explode('\r\n', $_POST['email']);` but I still cant insert into database. It is anything I need to add or adjust? – Que Jan 11 '18 at 04:56
  • it should work how you are making entries in text area can u show that entries screenshot if possible? – Prateik Darji Jan 11 '18 at 05:01
  • Why can't you try to enter email ID separated by `commas (,)` and then at PHP end use `explode(',',$_POST['email'])` then insert them..? – GYaN Jan 11 '18 at 05:05
  • @Que I just updated my answer you need to use double quotes to cover `"\r\n"` – Prateik Darji Jan 11 '18 at 05:07
  • @PrateikDarji I tried both `"\r\n"` or `'\r\n'`. When I submit form, popup fail shown. No data insert to database. – Que Jan 11 '18 at 05:10
  • @GYaN just change `explode("\r\n", $_POST['email']);` with `explode(',',$_POST['email'])` then use insert query like I post? – Que Jan 11 '18 at 05:12
  • please make sure there is no error in database connection put this two lines just after ` – Prateik Darji Jan 11 '18 at 05:12
  • @Que have you checked? are you sure there is no database connection error in your code right? – Prateik Darji Jan 11 '18 at 06:14
  • @PrateikDarji Yeah i've checked. No error in database connection. I always use this `error_reporting(-1); ini_set('display_errors', true);` when I start doing something. – Que Jan 11 '18 at 06:42
  • ok so did you get fail alert of getting nothing after running this code – Prateik Darji Jan 11 '18 at 06:43
  • Yeah that's right. I follow everything but still cannot insert data to mysql – Que Jan 11 '18 at 06:51
  • can u please update the question with your current code also mention database connection if possible – Prateik Darji Jan 11 '18 at 06:52
  • haven't you set `ini_set("display_errors",true);` just after `error_reporting` once try that and let me know if you facing any error or not – Prateik Darji Jan 11 '18 at 07:00
  • seriously, I don't understand the problem, are you getting any fail message which you have defined if query is failed? or getting nothing ? – Prateik Darji Jan 11 '18 at 07:06
  • I don't know whats the real problem sir. But I tried to delete current page and retype everything without copy paste, now it's work. omg but why. XD – Que Jan 11 '18 at 07:15
2

You may try this way

<body>
    <form name="form1" method="POST">
        <textarea rows="5" name="email" cols="50" ></textarea>
        <br />
        <input type="submit" name="submit" value="submit">
    </form>
</body>


Note :- use "Enter" to put all email (one by one)

Insert into database

  <?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

if(isset($_POST["submit"])) {

        $str = $_POST["email"];
        $email  = preg_split('/\r\n|\n|\r/', $str);


    foreach($email as $emails) {

        $query = mysqli_query($conn, "INSERT INTO emails (email) VALUES ('".$emails."')");

        if($query) { ?>

            <script>alert("Inserted into the database");</script>

            <?php } else { ?>

                <script>alert("Fail, please try again");</script>
    <?php } } }

    mysqli_close($conn);

    ?> 

Example :-

enter image description here

Aman Kumar
  • 4,533
  • 3
  • 18
  • 40
0

Do this in your code...

HTML

<body>
    <form name="form1" method="POST">
        <textarea rows="5" name="email" cols="50" ></textarea><br>
        <small>Enter email IDs separated by comma(,)</small>
        <input type="submit" name="submit" value="submit"><br>
    </form>
</body>

PHP

if(isset($_POST['submit'])) {
    $email = explode(',',$_POST['email']);//convert into $email array
    $value = '';
    foreach($email as $r) $value .= '("'.$r.'"),';//concatenate email for insert
    $value = rtrim($value,',').';' //remove the last comma ;
    $query = mysqli_query('INSERT INTO emails (email) VALUES '.$value);// insert all email in database in single query in different rows
    if($query) echo 'Inserted into the database';
    else echo 'Fail, please try again";
}

You will get your output...

GYaN
  • 2,327
  • 4
  • 19
  • 39
  • Thanks GYaN. But sorry I'm confused with this two. `foreach($email as $r) $value .= '("'.$r.'"),';` and `$value = rtrim($value,',').';'`. It is correct? Seem like something wrong. – Que Jan 11 '18 at 05:57
  • I got the value but data still not insert into db. – Que Jan 11 '18 at 06:08
0

Your code will work as intended if you will just replace this

$email = nl2br($_POST['email']);

with this

$email = preg_split('/\r\n|\n|\r/', $_POST['email']);

The problem is, you just have replaced all \n\r with <br>\n\r. The nl2br returns a string with replacements, but you need an array for using it inside the foreach loop.

As an additional note, you're iterating through an array and every time you are adding this instruction:

<script>alert("Inserted into the database");</script>

If you will iterate through 10 emails, you will be alerted ten times in a row.

Also, mysql_query is deprecated. It's time to learn either PDO, or MySQLi, which will give you ability to use placeholders instead of unsafe direct injecting $_POST data into SQL query. Placehiolders are pretty easy to learn, and they can help you to build more reliable applications.

Ronin
  • 1,688
  • 1
  • 13
  • 23
  • Thanks @Sergey Ronin. I tried to replace `$email = preg_split('/\r\n|\n|\r/', $_POST['email']);` with my code. But still failed insert data. I also use `error_reporting(E_ERROR | E_WARNING | E_PARSE);` to avoid error `mysql_query is deprecated` – Que Jan 11 '18 at 06:54