Data from PHP form is inserted into mysql database several times - php

I'm pretty new in PHP and MYSQL. I've got this form that I use to enter data into a database I created. I add up values from two fields in separate columns and insert the value into a third column (TOTAL_IN). Then I subtract another value (VALUE3) that's in another field from the value in a field in the third column (TOTAL_IN) and put that value in a different column. All these are in the same table. It works just fine, but the problem is that when I open up my database I see that the data has been inserted 20 or 100 times! How can I stop the data from being inserted so many times?
Please note that the submit button was clicked only once.
Here is what I use:
$sql="INSERT INTO $tbl_name (id, date, value1, value2, total_in, value3, value4)
SELECT '','$date','$value1','$value2',('$value1'+'$value2') AS SUM,
'$value3',(('$value1'+'$value2')-$value3) AS SUM
FROM $tbl_name";
$result=mysql_query($sql);
any help?
Thanks in advance!
EDIT::: Here is what my code looks like now after your suggestions:
//From Ruddy's post
$total_in=$value1+$value2;
$value4=($value1+$value2)-$value3;
//From Amit's post
$sql="INSERT INTO $tbl_name(id, date, value1, value2, total_in, value3, value4) VALUES ('', '.$date.', '.$value1.', '.$value2.', '.$total_in.', '.$value3.', '.$value4.')";
$result=mysqli_query($sql);
it works but it still enters the data many times.

$sql="INSERT INTO $tbl_name (id, date, value1, value2, total_in, value3, value4)
VALUES( '', '".$date."', ".$value1.", ".$value2.", ".$value1+$value2.",
".$value3.",".$value1+$value2-$value4.")";
$result=mysql_query($sql);
You need to concatenate the variables in php while writing in the query please see the syntax.
see here
What you were doing was select all the rows of the table and inserting into all.

$sum= $value1+$value2;
$sum2= ($value1+$value2)-$value4;
$sql="INSERT INTO $tbl_name (id, date, value1, value2, total_in, value3, value4) VALUES ('', '$date', '$value1', '$value2','$sum','$value3','$sum2')"
$result=mysql_query($sql);
I hate sums in the statement, so I took them out.

As it is, your query will INSERT as many rows as returned from the SELECT statement! Looks like your SELECT returns as many rows as there are in $tbl_name and you are re-inserting them in the same table!!

Related

PHP issue insert with auto_increment

I'm pretty new to PHP code.
I have a tabel that I want to insert in to but for some reason the insert statement does not work. The tabel has an ScanID column that AUTO_INCREMENT 's. I've tried a few things like just leaving the ScanID out of the statement but that didn't work either ( I also tried swapping the NULL with ' '). I was able to insert in to other tables where there isn't an ID that AUTO_INCREMENT's so my pretty sure that my connection works.
<?php
$xml=simplexml_load_file("someFile.xml");
$con =new PDO("mysql:host=localhost;dbname=testDB",'root','');
$ScanType="someType";
$start_date=$xml ->start_datetime;
$end_date=$xml ->finish_datetime;
$TargetTargetID="1";
$stmt=$con->prepare('insert into
Scan(ScanID, ScanType, start_date, end_date, TargetTargetID) values
(:ScanID, :ScanType, :start_date, :end_date, :TargetTargetID)');
$stmt->bindValue('ScanID',NULL);
$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();
$ScanID=$con->lastInsertId();
echo $ScanID;
?>
EDIT: this worked for me
$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');
$stmt->bindValue('ScanType',$ScanType);
$stmt->bindValue('start_date',$start_date);
$stmt->bindValue('end_date',$end_date);
$stmt->bindValue('TargetTargetID',$TargetTargetID);
$stmt->execute();
No need to pass auto increment column value in insert query just remove from columns and values to
$stmt=$con->prepare('insert into
Scan(ScanType, start_date, end_date, TargetTargetID) values
(:ScanType, :start_date, :end_date, :TargetTargetID)');
Remove from bind values
$stmt->bindValue('ScanID',NULL);

Insert data into table and immediately select ID number of the row

I have a MYSQL table called 'Buyers'. I am taking form data and inserting it into the table on a page called insert.php.
Now, along with the column names for the form fields, I have an Auto-increment ID column in the table. What I want is; once I send the form data to the table, I want to then execute some SQL to get the ID number for the row into which I just inserted the data into.
E.g, I have the SQL:
INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]');
This will create a row in the 'Buyers' table with the data from form fields 'name', 'email' and 'job'.
This row will have an ID number generated by Auto Increment.
How, then, can I then select that exact ID number? Is there some way to select the most recent row in the table, since that is the row which contains the ID number I want?
Mysqli : mysqli_insert_id()
<?php
mysqli_query($con,"INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysqli_insert_id($con);
?>
PDO : PDO::lastInsertId()
<?php
$stmt = $con->prepare("INSERT INTO Buyers (name, email, job) VALUES (?,?,?)");
$stmt->bind_param("sss", $_POST['name'], $_POST['email'], $_POST['job']);
$stmt->execute();
$last_id = $con->lastInsertId();
?>
Assuming $con as connection.
Mysql : mysql_insert_id()
<?php
mysql_query("INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysql_insert_id();
?>
NOTE: [The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead ]
SELECT x.*
FROM messages x
JOIN
( SELECT from_id, MAX(time_sent) time_sent GROUP BY from_id ) y
ON y.from_id = x.from_id
AND y.time_sent = x.time_sent;
The last part of this puzzle is left as an exercise for the reader.
Use mysql_insert_id() to retrive ID. More details - http://php.net/manual/en/function.mysql-insert-id.php

only want to insert one row into other table

How do I get this to only insert one row of data, with selected fields inserted into another table by using the reference ?
so far I can only get all of the fields transferred when using the statement in phpmyadmin
$Reference=$_GET['Reference'];
$sql="INSERT INTO Triage (Reference, Forename)
SELECT Reference, Forename from `Instruction` WHERE Reference='$Reference'"
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
INSERT INTO prod_detail(prod_name,prod_code) select Name,Zip as data from info_tb where Name="mittal";
Try something like this:
$Reference=mysql_real_escape_string($_GET['Reference']);
$sql="INSERT INTO Triage (Reference, Forename)
SELECT Reference, Forename FROM `Instruction`
WHERE Reference='$Reference' LIMIT 1";

MySQL insert combo from php var and other table

i am trying to insert into my sql table a combination of php variables and 1 row data from another table. ive found examples that are similar but none that have this combination.
OTHERTABLE.liveDate would be where i need the single record from, but i would need to add a condition such as WHERE id='1' from OTHERTABLE
'$navid', '$loginid', '$total', '$where' are not from OTHERTABLE
INSERT INTO myTable (`navid`,`loginid`, `pageDisplayNum`, `whereFrom`, `liveDate`)
VALUES ('$navid', '$loginid', '$total', '$where', 'OTHERTABLE.liveDate')
INSERT INTO myTable (`navid`,`loginid`, `pageDisplayNum`, `whereFrom`, `liveDate`)
select '$navid', '$loginid', '$total', '$where', OTHERTABLE.liveDate
from OTHERTABLE
where OTHERTABLE.id='1'

How to Insert / Update a Row in MySQL / PHP At The Same Time

I want to insert into a MySQL row if the row doesn't exist, or update it if it does exist.
Something like this:
$sqlQuery = "INSERT INTO table (Value1, Value2) VALUES ('$var1', '$var2') WHERE UniqueKey='$id'";
Is something like that possible?
INSERT INTO table (UniqueKey,Value1, Value2) VALUES ('$id','$var1', '$var2')
ON DUPLICATE KEY UPDATE Value1 = '$var1',Value2 = '$var1';
User MySQL's REPLACE command:
$sqlQuery = "REPLACE INTO table (id, Value1, Value2) VALUES ('$id', '$var1', '$var2')";
It works the same as a normal INSERT, but if the primary key (in you case 'id') matches then it will replace all the values specified.
replace into table (UniqueKey,Value1,Value2) values ('$id','$var1','$var2');
replace is similar to insert, however if the unique key exists in table, it will delete first, and than insert.

Categories