<html>
<form method="POST" action="insertlines.php">
<textarea name="url" rows="10" ></textarea>
<input type="submit" name="submit" value="Enter">
</form>
</html>
How can i put every single row of the textarea into a MySQL row ?
The thing I want is when I input:
John
Peter
Steven
in the textarea, I want them in my database with different ids each.
You have to parse the text, looking for the "enter" character:
<?php
if(isset($_POST['url'])){
if(strpos($_POST['url'], "\n")){
$entries = explode("\n", $_POST['url']);
} else {
$entries = array($_POST['url']);
}
// connect to DB here
// then iterate over entries
foreach($entries as $e){
// build some type of Prepared Statement to protect from SQL Injection
$q = "INSERT INTO table (col1) VALUES (?)";
// bind $e to statements
// Execute SQL statements
}
// close DB connection
}
?>
Try this:
$textarea=$_POST['url']
$sql = 'INSERT INTO YourTable(field1,field2,name) VALUES';
foreach(explode("\n", $textarea) as $row) {
$sql.='("field1","field2",.'$row'.)';
}
$conn->query($sql)
Related
I have four fields. Two name fields and two email fields. I have to insert all fields data by foreach loop but when I insert data through foreach loop, a blank entry also inserts in database.
sample code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="post">
Name : <input type="text" name="name[]"><br>
Email : <input type="text" name="email[]"><br>
Name : <input type="text" name="name[]"><br>
Email : <input type="text" name="email[]"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
[![<?php
if(isset($_POST['submit']))
{
$conn = mysqli_connect("localhost", "root", "", "practice");
$i=0;
foreach($_POST as $val)
{
$name=$_POST['name'][$i];
$email=$_POST['email'][$i];
$sql = "insert into interview (Name, Email) values ('$name', '$email')";
$result = mysqli_query($conn, $sql);
$i++;
}
}
?>
Can anybody help me ?
First, see here How can I prevent SQL injection in PHP? Do your query differently or you're screwed.
Since name and email are indexed the same, just loop one and reference the other by key:
foreach($_POST['name'] as $key => $val) {
$name = $val;
$email = $_POST['email'][$key];
// prepared statement query
}
Or you could do inputs like this to get arrays more like database rows:
Name : <input type="text" name="data[0][name]"><br>
Email : <input type="text" name="data[0][email]"><br>
Then loop it easily:
foreach($_POST['data'] as $val) {
$name = $val['name'];
$email = $val['email'];
}
#Simple Answer!
foreach($_POST['name'] as $index => $val) {
$name = $val;
$email = $_POST['email'][$index];
$sql = "insert into interview (Name, Email) values ('$name', '$email')";
$result = mysqli_query($DB_Connection, $sql);
}
We note that 'submit' is also a value in $_POST.
It looks like the code will go through the loop three times, one time for each of 'submit', 'name' and 'email'. (It might be going through the loop five times, not sure? I'd just echo $val in the loop to see what's going on.)
It looks like you are attempting to loop through either $_POST['name'] or $_POST['email'], rather than just $_POST.
As long as you get an equal number in each of those, it shouldn't matter which.
Code appears to be vulnerable to SQL Injection.
If there is some (unfathomable) reason you can't use prepared statement with bind placeholder, any potentially unsafe values need to be properly escaped. PHP has a mysqli_real_escape_string function which is expressly designed for this purpose.
Also, there doesn't appear to be any check for an error being returned from mysqli_query. It looks like the code is putting its figurative pinky finger to the corner of its mouth, Dr.Evil style, and saying "I just assume it will all go to plan. What?"
Here I'm stored some array values into database successfully. But, I have a problem here. For example : I have four input textfields. Assume if user filled three textfields and remaining one field is empty. When I execute this code I got 4 rows in my db table. 3 rows with values and one row without a value (empty field). (I DONT NEED THAT ONE ROW WITHOUT A VALUE)
But, I need if user didn't entered one field that field should not be stored in database. How to do that? I have posted my codes and image below.
<?php
include('config.php');
if(isset($_POST['submit']))
{
$cqty = $_POST['qty'];
foreach( $cqty as $key => $n )
{
echo $n ."<br/>";
try
{
$stmt = $conn->prepare("INSERT INTO testing ( qty ) VALUES ( :n )");
$conn->errorInfo();
$stmt->bindParam(':n', $n, PDO::PARAM_STR);
$stmt->execute();
}
catch (PDOException $e)
{
$e->getMessage();
}
}
if($stmt)
{
echo "inserted";
}
else
{
die(mysql_error());
}
}
?>
and
<form action="db.php" method="post">
qty : <input type="text" name="qty[]" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
Use empty to check if $n is empty. Use continue to skip the rest of the instruction in the foreach loop for that iteration.
foreach( $cqty as $key => $n )
if (empty($n)) continue;
echo $n ."<br/>";
try ...
im working on a project but first i would to understand one thing.
i have 2 input type text field with name="firstname[]" as an array (in the example im working with no jquery but it will be generated dinamically with it) and cant make it to mysql.
here is what i have: index.php
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname[]"> <br>
Firstname 2: <input type="text" name="firstname[]">
<input type="submit">
</form>
</body>
</html>
insert.php
<?php
$con=mysqli_connect("localhost","inputmultiplicad","inputmultiplicado","inputmultiplicado");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO input_field (firstname)
VALUES
('$_POST[firstname]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
the question is: how can i send the firstname[] array to the mysql database?
thanks for your time
This should work:
//Escape user input
$names = array_map('mysql_real_escape_string', $_POST[firstname]);
//Convert array to comma-delimited list
$names = rtrim(implode(',', $names), ',');
//Build query
$sql="INSERT INTO input_field (firstname) VALUES ('$names')";
Note: In general, it's better to use parameterized queries than mysql_real_escape_string(), but the latter is much safer than no escaping at all.
The following should generate the SQL statement you need. Remember to use mysql_escape_string before putting it into your database, though! Or even better, use PDO and bind the values. :)
$values = array();
$sql = "INSERT INTO table (firstname) VALUES ";
foreach ($_POST['firstname'] as $name) {
$values[] = "('".mysql_real_escape_string($name)."')";
}
$sql .= implode(",", $values);
I have several forms on a page called dispatch.php that each submit PHP code to INSERT into a database table and also UPDATE another database table. The main value that is INSERTED and UPDATED is the bolNum and containerNum.
Note: There can be more than 1 bolNum or containerNum at any time. You'll see the array and how I broke it down.
Here is 1 form (I shortened this as much as possible):
<form action="" method="POST"
id="serviceForm" name="serviceForm">
<label>Container Selected</label>
*** js populates bolNum & containerNum and displays it in these inputs ***
<input type="text" name="containerNum" id="containerNum" class="containerNum" />
<input type="text" name="bolNum" id="bolNum" class="bolNum" />
*** there are more form inputs, I just want to focus on the above 2 ***
<input type="submit" id="modal-form-submit" name="submit" value="Save" />
<?php
if(isset($_POST['submit'])){
$bolArray = explode(',', $_POST['bolNum']);
$containerArray = explode(',', $_POST['containerNum']);
$count = count($bolArray);
for($i = 0; $i < $count; $i++){
$bolService = $bolArray[$i];
$containerService = $containerArray[$i];
*** here is the first query ***
$sqlQuery = "INSERT INTO serviceTable (bol, container)
VALUES ('$bolService', '$containerService')";
*** here is the second query ***
$updateService = "UPDATE dispatchTable SET serviceColumn = 'Y'
WHERE CONTAINER_NUM = '$containerService' AND BOL_NUM = '$bolService'";
$updateServiceQuery = #mysql_query($updateService) or die ('error');
if(mysql_query($sqlQuery)){
$success = true;
}
else{
$success = false;
}
}
}
if($success){
echo "saved";
}
else{
echo "not saved";
}
?>
</form>
Here is another form. Basically, they are both the same, except for the names of the forms, and the names of the queries in the PHP.
<form class="well-small" action="" method="POST"
id="storageForm" name="storageForm">
<label>Container Selected</label>
*** js populates bolNum & containerNum and displays it in these inputs ***
<input type="text" name="containerNum" id="containerNum" class="containerNum" />
<input type="text" name="bolNum" id="bolNum" class="bolNum" />
*** there are more form inputs, I just want to focus on the above 2 ***
<input type="submit" id="modal-form-submit" name="submit" value="Save" />
<?php
if(isset($_POST['submit'])){
$bolArray = explode(',', $_POST['bolNum']);
$containerArray = explode(',', $_POST['containerNum']);
$count = count($bolArray);
for($i = 0; $i < $count; $i++){
$bolStorage = $bolArray[$i];
$containerStorage = $containerArray[$i];
*** here is the first query ***
$sqlQuery = "INSERT INTO storageTable (bol, container)
VALUES ('$bolStorage', '$containerStorage')";
*** here is the second query ***
$updateStorage = "UPDATE dispatchTable SET storageColumn = 'Y'
WHERE CONTAINER_NUM = '$containerStorage' AND BOL_NUM = '$bolStorage'";
$updateStorageQuery = #mysql_query($updateStorage) or die ('error');
if(mysql_query($sqlQuery)){
$success = true;
}
else{
$success = false;
}
}
}
if($success){
echo "saved";
}
else{
echo "not saved";
}
?>
</form>
If you'll notice the 2 queries per form, you will see the INSERT query updates to a different table. Whereas both forms have an UPDATE query that updates the same table, only different columns.
Again, I am having no problem with the INSERT queries. The problem lies with the UPDATE queries. Basically, if you complete the serviceForm, it should update the column in dispatchTable called serviceColumn, which it does. But it also updates the storageColumn which is also in dispatchTable. Vice versa for the completion of the storageForm.
When a form is complete, it should ONLY update the specified column for that form, not both columns for both forms.
I am not sure if it has something to do with the action of the forms being blank. Although I do believe the action may be the key to getting this to work correctly. I am not sure where to start.
Please advise.
* NOTE : I WILL BE USING PDO OR MYSQLI FOR THE NEXT APPLICATION *
Try to rename submit buttons in your forms:
....
<input type="submit" id="modal-form-submit" name="service_submit" value="Save" />
<?php
if(isset($_POST['service_submit'])){
....
and
....
<input type="submit" id="modal-form-submit" name="storage_submit" value="Save" />
<?php
if(isset($_POST['storage_submit'])){
....
Both fields are updated because both parts of PHP code are executed. The reason is you check the same post field $_POST['submit'] that is set when you submit any form on your page.
P.S.
Try to change your queries to make one query instead a lot of queries in a loop. Your application will work faster.
http://dev.mysql.com/doc/refman/5.0/en/update.html
http://dev.mysql.com/doc/refman/5.6/en/insert.html
Your code have one big hole named SQL injection. Try at least to escape values passed in query, even better use parameterized queries: http://php.net/manual/en/pdostatement.bindparam.php
I am reading a tutorial on how to insert and update data into a MySQL table using PHP, the code is listed below. My problem is when i click update but I have not modified any data, rowCount() returns 0 and breaks the code.
My question is, If I am simply updating the database with the same values that are in the database, why does rowCount() return zero? My thoughts were that even though it was the same data it would be inserted anyway and return a count of the updated rows? I am guessing that it check the data before it try's the update? Can anyone shed some light on this for me and suggest a workaround? I have been starring at the code for hours and have been unable to come up with anything, thanks.
<?php
require_once('../includes/connection.inc.php');
// initialize flags
$OK = false;
$done = false;
// create database connection
$conn = dbConnect('write', 'pdo');
if (isset($_GET['article_id']) && !$_POST) {
// prepare sql query
$sql = 'SELECT article_id, title, article FROM blog WHERE article_id = ?';
$stmt = $conn->prepare($sql);
// bind the results
$stmt->bindColumn(1, $article_id);
$stmt->bindColumn(2, $title);
$stmt->bindColumn(3, $article);
// execute query by passing array of variables
$OK = $stmt->execute(array($_GET['article_id']));
$stmt->fetch();
}
// if form has been submitted, update record
if (isset($_POST['update'])) {
//prepare update query
$sql = 'UPDATE blog SET title = ?, article = ? WHERE article_id = ?';
$stmt = $conn->prepare($sql);
// execute query by passing array of variables
$stmt->execute(array($_POST['title'], $_POST['article'], $_POST['article_id']));
$done = $stmt->rowCount();
}
// redirect page on sucess or if $_GET['article_id'] not defined
if ($done || !isset($_GET['article_id'])) {
header('Location: http://localhost/PHP_Solutions/admin/blog_list_pdo.php');
exit();
}
// store error message if query fails
if (isset($stmt) && !$OK && !$done) {
$error = $stmt->errorInfo();
if (isset($error[2])) {
$error = $error[2];
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Update Blog Entry</title>
<link href="../styles/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Update Blog Entry</h1>
<p>List all entries </p>
<?php if (isset($error[2])) {
echo "<p class='warning'>Error: $error[2]</p>";
echo '<pre>';
print_r($_POST);
print_r($error);
echo '</pre>';
}
if ($article_id == 0) { ?>
<p class="warning">Invalid request: record does not exist.</p>
<?php } else { ?>
<form id="form1" method="post" action="">
<input name="article_id" type="hidden" value="<?php echo $article_id; ?>">
<p>
<label for="title">Title:</label>
<input name="title" type="text" class="widebox" id="title" value="<?php echo htmlentities($title, ENT_COMPAT, 'utf-8'); ?>">
</p>
<p>
<label for="article">Article:</label>
<textarea name="article" cols="60" rows="8" class="widebox" id="article"><?php echo htmlentities($article, ENT_COMPAT, 'utf-8'); ?></textarea>
</p>
<p>
<input type="submit" name="update" value="Update Entry" id="update">
</p>
</form>
<?php } ?>
</body>
</html>
My question is, If I am simply updating the database with the same values that are in the database, why does rowCount() return zero?
rowCount is counting the affected rows by a query. As you haven't changed anything, there are zero affected rows.
PDOStatement->rowCount — Returns the number of rows affected by the last SQL statement
It has nothing to do with PHP - it's just how MySQL works.
MySQL documentations says:
For UPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is the number of rows “found”; that is, matched by the WHERE clause.
When you're using the UPDATE statement, and you submit the same values that are in database, it will always return zero, because it doesn't affected any row.
A way to resolve this problem is:
$done = $stmt !== false ? true : false;
What i did?
I did that:
if($stmt !== false){
$done = true;
} else{
$done = false;
}
Because if rowCount() is zero, but $stmt has executed without errors, $stmt was executed, but didn't change anything.
It's how MySQL works and has nothing intrinsically to do with the PDO extension; performing a regular mysql query would produce the same results. There is a workaround I found using the mysql functions, although I'm not sure if you can do anything similar with a PDO object.
$q = 'UPDATE etc...';
$r = mysql_query($q, $con);
$info = mysql_info(); // Returns info about last query.
list($matches, $changed, $warnings) = sscanf($matched, "Rows matched: %d Changed: %d Warnings: %d");
if ($matches > 0) {} // etc
Hope this helps a little.