Insert multiple email to mysql using single textarea - php

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 :

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>

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 :-

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.

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...

Related

"php not inserting in to mysql server in xampp"

"I have read a lot of problem been solved in stackoverflow similar to my problem, and have seen a lot of example, yet still my code is not inserting in to mysql. however if i hard feed the php it would insert. my info is coming as submit from html post.I have good server connection and also connection to the database, can any one help me if i miss any thing. here is my code below."
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="image";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $db); // Establishing Connection with Server
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully";
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$image = $_POST['image'];
echo $name;
echo $image;
if($name !=''||$image !=''){
//Insert Query of SQL
$query = mysqli_query("INSERT INTO image (id, name, imagename) VALUES ('NULL', '$name', '$image')");
echo "Data Inserted successfully...!!";
}
else{
echo "Insertion Failed <br/> Some Fields are Blank....!!";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
<form action = "test2.php" method="POST" enctype="multipart/form-data">
<label>name: </label><input type="text" name="name" />
<label>File: </label><input type="text" name="image" />
<input type="submit" />
</form>
</body>
</html>
" i expect output of 5/2 to be 2.5"
Write the name for submit button
<input type="submit" name="submit" />
then in php file
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
}
this if statement will run
you not given name attribute to button so give name="submit" and if you want to upload file then change type="file"
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="image";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $db); // Establishing Connection with Server
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully";
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$image = $_POST['image'];
echo $name;
echo $image;
if($name !=''||$image !=''){
//Insert Query of SQL
$query = mysqli_query("INSERT INTO image (id, name, imagename) VALUES ('NULL', '$name', '$image')");
echo "Data Inserted successfully...!!";
}
else{
echo "Insertion Failed <br/> Some Fields are Blank....!!";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
<form action = "test2.php" method="POST" enctype="multipart/form-data">
<label>name: </label><input type="text" name="name" />
<label>File: </label><input type="file" name="image" />
<input type="submit" name="submit" />
</form>
</body>
</html>
You're checking isset($_POST['submit']) but there is no input field which is posted with submit name.. you need to add the name attribute in the submit button. also you're not passing the $connection in the mysqli_query.
$servername = "localhost";
$username = "root";
$password = "";
$db="image";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $db); // Establishing Connection with Server
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully";
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$image = $_POST['image'];
echo $name;
echo $image;
if($name !=''||$image !=''){
//Insert Query of SQL
$query = mysqli_query($connection, "INSERT INTO image (id, name, imagename) VALUES ('NULL', '$name', '$image')");
if($query !== false){
echo "Data Inserted successfully...!!";
}
else{
echo "Query failed";
}
}
else{
echo "Insertion Failed <br/> Some Fields are Blank....!!";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
<form action = "test2.php" method="POST" enctype="multipart/form-data">
<label>name: </label><input type="text" name="name" />
<label>File: </label><input type="text" name="image" />
<input type="submit" name = "submit" />
</form>
</body>
</html>
One more suggestion always use PDO in code to prevent SQL injection. Your code is vulnerable to sql injection.

Cant Update SQL data using this code, checked code so many times

I wrote this code to update entry in my sql table, but i don't what is wrong.
Here is my form
<form action="" method="POST">
<center>
Alumni_ID :
<input type="text" name="valueh">
<br>
<input type="text" name="name" placeholder="name">
<input type="text" name="phone" placeholder="contact details">
<input type="text" name="details" placeholder="details">
<input type="text" name="address" placeholder="address">
<input type="submit" value="update data">
</center>
</form>
And this is php page,
<?php if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tssolutions";
$ab = $_POST['name'];
$bc = $_POST['phone'];
$cd = $_POST['details'];
$de = $_POST['address'];
$posted = $_POST['valueh'];
//create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "connected successfully";
$sql = " UPDATE phone SET name='".$ab."', phone='".$bc."', details='".$cd."', address='".$de."' WHERE name = '".$posted."' ";
if(mysqli_query($conn, $sql)) {
echo "<hr>";
echo "<h3 class='w3-center' style='text-color:black'>Record Successfully Updated</h3>";
} else {
echo "<hr>";
echo "<h3 class='w3-center' style='text-color:black'>Error While Updating, Try Again</h3>";
}
mysqli_close($conn);
} ?>
Both the code are on same page Update.php, i wish to send alumni_id so that i can update that record where alumni_id = name in table phone, and then send new values of the row .
You forgot to name the submit button
Instead of
<input type="submit" value="update data">
Try this
<input type="submit" name="submit" value="update data">
To debug your code you can echo your SQL statement
echo $sql = "UPDATE phone SET name='".$ab."', phone='".$bc."', details='".$cd."', address='".$de."' WHERE name = '".$posted."';
You can then see if you have correct syntax and your values are sent correctly
try this code, maybe this helps
$sql = " UPDATE phone SET `name` ='$ab', `phone` ='$bc', `details` ='$cd', `address`='$de' WHERE `name` = '$posted' ";

when i insert data in db i get num1 in all column

i try to creat a table with html and php
when i insert data into my db i get num 1 like a values in all column
this my code
<html dir="rtl">
<form action="" method="post">
<label for="Nom">الاسم:</label>
<center><input type="text" name="Nom"></center>
<label for="Cin">البطاقة الوطنية:</label>
<center><input type="text" name="Cin"></center>
<label for="Tel">الهاتف:</label>
<center> <input type="text" name="Tel"></center>
<label for="DATE_donation"> تاريخ التبرع:</label>
<center><input type="date" name="DATE_donation"></center>
<center><input type="submit" value="إدخال"></center>
</form>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ikhlas";
$con= mysqli_connect($servername, $username, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$Name =isset($_POST['Nom']);
$CIN = isset($_POST['Cin']);
$TEL = isset($_POST['Tel']);
$date = isset($_POST['DATE_donation']);
$sql="INSERT INTO persone(Nom, Cin, Tel, DATE_donation) value ('$Name','$CIN','$TEL','$date')";
if (mysqli_query($con, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
?>
and this my ressult in dbenter image description here
Sure because you define all variable with $foo = isset($bar) instead of
if(isset($bar))
$foo = $bar;
Take a look to the doc about SQL injection too: http://php.net/manual/en/security.database.sql-injection.php
Remove your isset()
http://php.net/manual/en/function.isset.php
Replace to:
if(isset($_POST['إدخال']))
{
$Name = (!empty($_POST['Nom']))?$_POST['Nom']:"";
$CIN = (!empty($_POST['Cin']))?$_POST['Cin']:"";
$TEL = (!empty($_POST['Tel']))?$_POST['Tel']:"";
$date = (!empty($_POST['DATE_donation']))?$_POST['DATE_donation']:"";
}

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

No data insertion when button pressed

When i press the submit button to insert record, it pulls out no error but when i check the database i find no records submitted too. please what could be wrong with my script. just started with php
<?php
if (isset($_POST['submitted'])){
include('Connections/connect.php');
$term= $_POST['term'];
$details= $_POST['details'];
$sql = "INSERT INTO people (term,details) VALUES ($term,$details)";
$newrecord ="Inserted Successfully";
}
?>
connect.php
<?php
$hostname_speedapp = "localhost";
$database_speedapp = "mydb";
$username_speedapp = "root";
$password_speedapp = "password";
$mydb= mysqli_connect($hostname_mydb, $username_mydb, $password_mydb) or trigger_error(mysql_error(),E_USER_ERROR);
?>
HTML
<form id="form1" name="form1" method="post" action="page1.php">
<p>
<label for="term"></label>
<input type="text" name="term" id="term" />
</p>
<p>
<label for="details"></label>
<input type="text" name="details" id="details" />
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
<input name="submitted" type="hidden" value="submitted" />
</p>
</form>
<p>
<?php
$newrecord
?>
There is a lot wrong with your code
Let's take it step by step:
<?php
if (isset($_POST['submitted'])){
include('Connections/connect.php');
$term= $_POST['term'];
$details= $_POST['details'];
You are not escaping here. When I'm a bad man I could destroy your application
Read more about escaping here: How can I prevent SQL injection in PHP?
$sql = "INSERT INTO people (term,details) VALUES ($term,$details)";
You are defining a query here but you do not do anything with this query
read about executing query's on the php documentation page: http://php.net/manual/en/mysqli.query.php
$newrecord ="Inserted Successfully";
You are defining a variable $newrecord here but it does not have a function here. Add echo $newrecord; to echo the value of the variable $newrecord: http://php.net/echo
}
?>
Then you are not using the correct variables in your connect.php
<?php
$hostname_speedapp = "localhost";
$database_speedapp = "mydb";
$username_speedapp = "root";
$password_speedapp = "password";
$mydb= mysqli_connect($hostname_mydb, $username_mydb, $password_mydb) or trigger_error(mysql_error(),E_USER_ERROR);
?>
You are defining $hostname_speedapp and using $hostname_mydb in your mysqli_connect change that to $hostname_speedapp etc.. changing your connection string to:
$mydb= mysqli_connect($hostname_speedapp, $username_speedapp, $password_speedapp)
You are not selecting a database in your connectionstring. You are defining a variable with your database name called: $database_speedapp but you never use it.
Change your connectionstring to: $mydb= mysqli_connect($hostname_speedapp, $username_speedapp, $password_speedapp, $database_speedapp) and you should be good to go
add this
$sql = "INSERT INTO people (term,details) VALUES ($term,$details)";
if (mysqli_query($mydb, $sql))
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($mydb);
}
EDIT 01
$hostname_speedapp = "localhost";
$database_speedapp = "mydb";
$username_speedapp = "root";
$password_speedapp = "password";
$mydb= mysqli_connect($hostname_mydb, $username_mydb, $password_mydb) or trigger_error(mysql_error(),E_USER_ERROR);
and top of page1.php
include("connect.php");
You dont even have an insert query in your script.
$hostname_speedapp = "localhost";
$database_speedapp = "mydb";
$username_speedapp = "root";
$password_speedapp = "password";
$mydb= mysqli_connect($hostname_mydb, $username_mydb, $password_mydb) or trigger_error(mysql_error(),E_USER_ERROR);
$sql = "INSERT INTO people (term,details) VALUES ($term,$details)";
if (mysqli_query($mydb, $sql)) {
$newrecord ="Inserted Successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mydb);
}
mysqli_close($mydb);
use this:
` $sql = "INSERT INTO people (term,details) VALUES ($term,$details)";
$result=mysqli_query($mydb,$sql);`
Connect.php
<?php
$hostname_speedapp = "localhost";
$database_speedapp = "mydb";
$username_speedapp = "root";
$password_speedapp = "password";
$mydb= mysqli_connect($hostname_speedapp, $username_speedapp, $password_speedapp,$database_speedapp) or trigger_error(mysql_error(),E_USER_ERROR);
?>
page1.php
if (isset($_POST['submit'])){
include('Connections/connect.php');
$term= $_POST['term'];
$details= $_POST['details'];
$sql = "INSERT INTO people (term,details) VALUES ('".$term."' , '".$details."')";
if ($mydb->query($sql) === TRUE) { //can use connected database $mydb
$newrecord = "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $mydb->error;
}
}
?>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="term"></label>
<input type="text" name="term" id="term" />
</p>
<p>
<label for="details"></label>
<input type="text" name="details" id="details" />
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
<p>
<?php
if(isset($newrecord)){
echo "<h3>$newrecord</h3>";
}
?>
I think you need to quote the submitted data values in your sql query:
Change the following:
$sql = "INSERT INTO people (term,details) VALUES ($term,$details)";
to
$sql = "INSERT INTO people (term,details) VALUES ('$term','$details')";

Categories