I am trying to bulk insert some data in PHP from a textarea form, and then prevent duplications from already existing data. I tried to code something but right now it just inserts everything that I insert in the textarea in same "value" in the column. But I want each line from the textarea separated in each and own column.
Here is what I have so far, and this works but it inserts the whole row:
<?php
include '../includes/config.php';
if (isset($_POST["data"])) {
$_POST["ban"] = $value;
$line_data = explode("\n", $_POST["data"]);
foreach ($line_data as $key => $value) {
$checkQuery = "SELECT ip FROM blacklist WHERE ip='" . $_POST["ip"] . "'";
$checkResult = mysqli_query($con, $checkQuery);
if (mysqli_num_rows($checkResult) != 0){
// do nothing
} else {
$sql = "INSERT IGNORE INTO blacklist (ip) VALUES ('{$value}')";
$result = mysqli_query($con, $sql);
}
}
}
?>
<form action="bulk.php" method="post">
<textarea type="text" name="data" placeholder="IP address"></textarea><br/>
<button type="submit" name="ban">Ban</button>
</form>
So my question is, what am I doing wrong and is there good way to handle this? If so, how?
Edit: It inserts into it's own column now, but it still duplicates. Like it's still possible insert same thing many times even if data exists in database.
You can function explode for splitting values in field ip into lines. Save each line with ip address as separate record in your db table blacklist
Related
I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.
you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'
You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.
use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)
I have a form that asks the user to enter in an exam id that they want to delete from the exam table in the DB.
The problem I am having is that even if the user enters in an id that does not match in the DB the script fires the else block completely ignoring the condition.
I may have implemented this wrong but as far as I am aware of i cannot see where I am wrong but I suspect that there is something I have done wrong in my if statment.
Here is my form that requires the user to enter an exam id for deletion
<form method = "post" action = "examDeleted.php">
<h1 class = "title">Delete Exam</h1>
<div class = "formContent">
<labeL for = "id">ID</labeL>
<input type = text name = "id" class = "input">
<br><br>
<br><br><br>
<input type = "submit" value = "Delete">
</div>
</form>`
This is passed to the function that contains the sql query to delete the record from the table
<?php
include('dbLogin.php');
$id = trim($_POST['id']);
if($id != "")
{
$delete = "DELETE FROM exams WHERE id = '$id'";
$results = mysql_query($delete);
if(!$results)
{
die ("Cannot delete data from the database! " + mysql_error());
echo '<br><br>';
echo 'Return';
}
else
{
echo"Exam: $id has been deleted";
}
}
else
{
echo "No data entered! " . mysql_error();
}
?>
As you can see the condition !$results, to me it is saying if the record does not exist then kill the query else confirm the deletion. Is there an obvious reason why the inner if statment dosent get fired?
DELETE statements are considered successful even if no rows were deleted. (This is how SQL works in general; it's not MySQL-specific.)
I would say that you should use mysql_affected_rows to find out how many rows were deleted, but as others have pointed out, you shouldn't be using the mysql_ functions at all, anyway.
Your code as it stands is highly vulnerable to SQL injection attacks. If someone were to POST the following ID to examDeleted.php (remember, they don't have to use your form to do that, so any client-side checks can be bypassed):
' OR 1 = 1 OR id = '
...I think it would probably delete every exam in your table, as your SQL statement would end up as:
DELETE FROM exams WHERE id = '' OR 1 = 1 OR id = ' '
...which is a valid DELETE statement whose WHERE clause matches all your rows.
Using parameterised queries (available in the non-deprecated MySQL drivers like mysqli or PDO) would combat this issue.
I have troubles about php & mysql. I've to retrieve all records from DB1's table and then I have to insert them again to DB2's table.
<?php
require_once 'includes/config.php';
include 'includes/header.php';
if(isset($_POST['go'])){
$query = mysql_query("SELECT id,username,password FROM $db_database1.account")
or die(mysql_error());
echo "Record ".mysql_num_rows($query)." retrieve";
while($result_row = mysql_fetch_array($query, MYSQL_ASSOC)){
$account_ID = $result_row['id'];
$username = $result_row['username'];
$password = $result_row['password'];
$query = mysql_query("INSERT INTO $db_database2.account(uid,username,password) VALUES('$account_ID','$username','$password')")
or die(mysql_error());
$selectId = mysql_insert_id();
}
}
mysql_close($conn);
?>
<div class="wrapper">
<div class="content">
<form method="post" action="<?PHP $_SERVER['PHP_SELF'];?>">
<input type="submit" name="go" value="Go" />
</form>
</div>
<?php include 'includes/footer.php';?>
According to this code just one record was inserted. How can I insert all retrieved records?
To insert records into another table you need one single query, run from mysql console without PHP:
INSERT INTO db_database2.account SELECT id,username,password FROM db_database1.account
Notes on your code
you have to escape strings you are adding to the query
for some reason you are inserting into the same database
asking for the mysql_insert_id() makes no sense as you are apparently inserting a_i id already
there is no use for storing second mysql_query result into variable
yet this variable gets overwritten <- here is the reason your code runs once.
there is no use for echoing $_SERVER['PHP_SELF'] here. just leave form action blank.
yet you are actually leaving form action blank as you just forgot to echo this variable
I see no use for all the form and HTML here. Can't you just run this code without forms?
as it seems that whole mess is just to hash passwords, you need no extra tables then
just simple
UPDATE account SET password = md5(concat(id,username,password));
always have a database backup before such manipulations
First time question, long time reader :)
I am building forms dynamically from Columns in a MYSQL DB. These columns
are created/ deleted etc.. elsewhere on my App. My form runs a query against a
SQL View and pulls in the column names and count of columns. Simple! build the form,
with the HTML inputs built with a PHP for loop, and it echos out the relevant HTML for the new form fields. All very easy so far.
Now i want a user to update these dynamically added fields and have the data added to the relevant columns - same table
as existing columns. So, as the input fields are named the same as the columns, they are posted to a PHP script for processing.
Problem is, while i have the actual field names inserted in to the SQL INSERT query, i cannot figure out how to extract the POST
data from the POST dynamically and add this to the VALUEs section of the query.
Here is my attempt....
The Query works without the variables added to it.
It works like this, first section/ is to retrieve the columns names from earlier created VIEW - as these are identical to POST names from the form. Then output to array and variable for insertion to Query. It looks like the implode function works, in that the relevant column names are correct in the statement, but i fear that my attempt to inject the column names on to the POST variables is not working.
$custq = "SELECT * FROM customProperties";
$result = $database->query($custq);
$num_rows = mysql_numrows($result);
while (list($temp) = mysql_fetch_row($result)) {
$columns[] = $temp;
}
$query = '';
foreach($columns as $key=>$value)
{
if(!empty($columns[$key]))
{
$values .= "'".'$_POST'."['".$value."'], ";
}
}
$q = "INSERT INTO nodes
(deviceName,
deviceInfo,
".implode(", ", $columns).",
nodeDateAdded,
status
)
VALUES
('" . $_POST['deviceName'] . "',
'" . $_POST['deviceInfo'] . "',
".$values."
CURDATE(),
'1'
)";
$result = $database->query($q)
Any help is much appreciated. I will feed back as much as i can. Please note, relativity new to PHP, so if i am all wrong on this, i will be glad for any tips/ advice
Regards
Stephen
If you want to get the values of every POST input without knowing the input names then you can do it this way:
//get all form inputs
foreach($_POST as $name => $value)
{
echo $name . " " . $value . "<br>";
}
If you want to get the value of certain POST inputs where you know the name of the input field then you can do it this way:
if(isset( $_GET["deviceName"]))
{
$deviceName = $_POST["deviceName"];
}
if(isset( $_GET["deviceInfo"]))
{
$deviceInfo = $_POST["deviceInfo"];
}
To connect to a database and insert the info then you have to do something like this:
$host = "localhost";
$dbuser = "username";
$pass = "password";
$datab = "databasename";
//Create DB connection
$con=mysqli_connect($host, $dbuser, $pass,$datab);
if (mysqli_connect_errno($con))
{
echo "ERROR: Failed to connect to the database: " . mysqli_connect_error();
}
else
{
echo "Connected to Database!";
}
//insert into database
mysqli_query($con, "INSERT INTO nodes (deviceName, deviceInfo) VALUES ('$deviceName', '$deviceInfo')");
(Don't forget to add mysql_real_escape_string to the $_POST lines after you get it working.)
I have one form which need to submit data into two different tables in same DB.
at past time, i have asked how to submit form into two tables, but it impossible.
Then, I try to submit this form use two submit buttons with different destination.
Could you give some advise to submit this form after click them?
Javascript:
function button1click() {
yourForm.action = "ajax1.php";
yourForm.submit();
}
function button2click {
yourForm.action = "ajax2.php";
yourForm.submit();
}
HTML:
<form action='' method='post'>
<input type='input' id='blah' name='blee' />
<button type='button' onclick='button1click()'>Button 1</button>
<button type='button' onclick='button2click()'>Button 2</button>
</form>
why dear ?
if($_POST['submit'])
{
$sql1="insert into table 1";
mysql_query($sql1);
$sql2="insert into table 2";
mysql_query($sql2);
}
This should work..
one submit button only. OK!
You can do this many different ways. Just because the data is on one form, doesn't mean it has to go into one table. Basically you need to learn how to write some server side code that parses the incoming data and puts it where it needs to be.
So the simplest way is to just submit your form, and then on the server save the data to where it needs to go.
Having 2 buttons could be clunky, unless thats how it was designed...
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("MYDB") or die(mysql_error());
// Insert a row of information into the table "example"
$sql="INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
// Insert a row of information into the table "example"
$sql=mysql_query("INSERT INTO example1
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
?>
You can insert into different tables like this:
EDIT (new code):
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("double") or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example1
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
?>
Hope this answers you question because toy cant have double destination (i think) but this inserts into two different MySQL tables...
Good luck
To summarize what others have said above,
You could submit to two different locations, using javascript to change the action attribute of the form. You might wanna use it if the two destinations are not on the same server.
Or you could submit it to one destination only, massage your data, and then insert into two tables using php. It'll be particularly advantageous as you wouldn't need to sanitize or validate the data twice on server-side.
Very Very Simple...
You can insert in two tables by only one submit button..
Example:
<?php
if(isset($_POST['submit']))
{
$value1 = (!empty($_POST['form_name_value1']))?$_POST['form_name_value1']:null;
$value2 = (!empty($_POST['form_name_value2']))?$_POST['form_name_value2']:null;
$str = "INSERT INTO table_name1(db_value1, db_value2)VALUES('$value1','$value2')
$sql = mysql_query($str) or die(mysql_error());
$str1 = "INSERT INTO table_name2(db_value1, db_value2)VALUES('$value1','$value2')
$sql1 = mysql_query($str1) or die(mysql_error());
if($str)
{
echo "Successful";
}else{
echo "Unsuccessful";
}
if($str1)
{
echo "Successful";
}else{
echo "Unsuccessful";
}
}
This question was asked 4 years ago. Not the time to answer now I know. But
still answering to help others searching for the same problem.
Vote Up if you find this helpful. :D