Why PHP inserts multiple rows to MySQL from one single data entry? - php

I have an HTML code that creates a template to collect 5 variables. These variables are posted to a php that process the info and forward it to a mySQL database.
Following is the HTML template:
<html>
<head>
</head>
<body>
<form action="insert.php" method="post">
<p>Value1 <input type="text" name="value1" /></p>
<p>Value2 <input type="text" name="value2" /></p>
<p>Value3 <input type="text" name="value3" /></p>
<p>Value4 <input type="text" name="value4" /></p>
<p>Value5 <input type="text" name="value5" /></p>
<input type="Submit" />
</form>
</body>
</html>
And here is the PHP form that interacts with MySQL (note that the # are substituted with the actual values in the original form):
<?php
$server="#####";
$username="#####";
$password="######";
$database="#####";
$val1=$_POST['value1'];
$val2=$_POST['value2'];
$val3=$_POST['value3'];
$val4=$_POST['value4'];
$val5=$_POST['value5'];
$con = new mysqli($server,$username,$password,$database);
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= "INSERT INTO test_table (value1, value2, value3, value4, value5) VALUES ('$val1','$val2','$val3','$val4','$val5')";
if (mysqli_query($con, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
mysqli_close($con);
?>
The two forms seem to work fine and there are no errors popping out. The problem is that when I switch to the mysql prompt and interrogate the database to see if it works it shows multiple entry rows instead of only one.
I am pretty confident that the issue is not related to the database's table which was previously created. Just in case I am posting the code I used to create the table.
mysql> create table test_table (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
value1 VARCHAR(10),
value2 VARCHAR(10),
value3 VARCHAR(10),
value4 VARCHAR(10),
value5 VARCHAR(10))
;
So for example, if I load the html form and I insert "a" "b" "c" "d" and "e" in the fields the output should be only 1 record in the mysql. Instead I get two.(I cannot post a picture of the output cause I do not have enough experience point). I have been trying to fix that but I couldn't find where the problem is.
Any help is greatly appreciated.

There's nothing in your code that would create a duplication. One form, if handled once by your PHP code would generate only one row on the db as you know, so either you are posting to a file and then importing another that handles the form more than once or you have some weird redirect going on.
For "a" "b" "c" "d" and "e" to be registered twice (two rows) the form contents are being sent twice to that PHP.
First, try to find out if you are submitting only once:
- In firefox install Live HTTP Headers, capture the POST and see if it goes just once;
Are you using jquery to validate or handle the form submit? if so are you preventing the normal event to occur? If not you might get the data posted twice, one by ajax and the other by normal browser post.

When you refresh your form you still have your POST variables stored from previous entry. Refreshing your browser (in chrome as far as I know) resubmits your POST variables. That is why you seem to get double entries.

In the case you didn't find an answer for this, as none of the answers are marked as a solution, I was having the same issue on my machine today, but it was inserting two random rows and the actual row I was inserting. The bizarre thing is, I was getting multiple entries even giving a single insert instruction on the php interactive mode. Not satisfied, I went directly to mysql console to see what would happen, and, instead of getting one entry I was getting the same three as before. So, the problem was on MySQL and what I thought was trying to drop the table and create it again... It magically solved my problem.

Related

How to access php from html?

I am sorry if this is a repeating question, but I can't find anyone who might have the same question as me yet. I am new in html and php, and I am trying to learn more by practising, basically creating a registration form and keep all the data in the MySQL database, by using xampp. I have created a registration form and saved it as a .html file format, but how can I use php to send the user input from html to the MySQL database? I have seen a lot of examples on Google, but most of them are using php file format, for example instead of registration.html, they use registration.php. I really do appreciate your help. Thank you very much StackOverflow community members.
P/S: I use Visual Studio Code to do this
Step 1: write this code in your html file
in form action redirect it to the php file
<!DOCTYPE html>
<html>
<head>
<title>form</title>
</head>
<body>
<form method="post" action="st.php">
<input type="text" name="text">
<input type="submit" name="submit_btn">
</form>
</body>
</html>
Step 2 create st.php file and call the action
<?php
if(isset($_POST['submit_btn'])){
//your code
header('Location:yourHTMLFile.html?status=success');//redirect to your html with status
}
?>
An example to insert some data in to the MySQL database using PHP
1. Create a Index.php page in a new folder(“764”) created under public_html folder present in your home directory
To use a PHP script on your web page, you just need to end the file name with .php and make sure the permissions on the file are set correctly. Any files to be accessed by the web server must be publically readable, but none of your PHP files (nor the directory containing them) may be group or publically writable. Following are the commands you can use for setting the permissions in linux:
chmod 755 public_html
chmod 644 public_html/764/index.php
The PHP page will have two simple text boxes for the user to enter some data in to it. Label them to be Firstname and Lastname.
INDEX.PHP
<html>
<body>
<h1>A small example page to insert some data in to the MySQL database using PHP</h1>
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
<input type="submit" />
</form>
</body>
</html>
We also need to make sure that the form method attribute is “post” so as to access the data being entered in a reliable way in the next page being directed “insert.php” so that the data being entered in the textboxes can then be saved to the database in the “insert.php” page.
To connect to MySQL :-
Before you can access your MySQL database, you must contact the system administrators to request an account.
Once the administrators have notified you that your account has been created, you may connect using the following instructions.
Go to http://localhost/phpmyadmin and type your MySQL ID and password being given.
Now enter the new table name “nametable” , number of fields in that table as “2” and hit GO button.
Enter the field names to be “firstname” and “lastname” and keep the length attributes to be “20” for both the fields. The default type of VARCHAR is kept as it is.
After the table fields are being created, the following screen will be shown to you.
Now we need to make a connection to the MySQL database and then send this entered data from our textboxes. For that we create a new PHP page “insert.php” and use the following connection strings to the connection variable $con
After making a connection, a SQL query is being written to enter this data in to the MySQL database being created (“nametable”)
To tell the user that the data is being entered we set the echo to "1 record added"
INSERT.PHP
<html>
<body>
<?php
$con = mysql_connect("localhost","cis_id","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cis_id", $con);
$sql="INSERT INTO nametable (fname, lname)
VALUES
('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
Now type the index page URL in your browser and enter some data in to the textboxes. Submit the Query.
For browsing the data, you need to click on Database: cis_id on top of the page (http://localhost/phpmyadmin) to get to the database tables page. Then click on the browse button as shown below, beside the “nametable” which you have already created to browse through the entered data.
the data being entered in to the MySQL database table being created.
Here is the reference.
http://people.cs.ksu.edu/~hankley/d764/tut06/GopisettyPHP.html
Note: Please write questions in proper way and internet is everything to get whatever you want. Hope you will search first and when you are helpless, post question with piece of code. Then only we can help in this forum.

PHP insert data into SQL Database Table produces blank row

I'm trying to insert data from the form created into the SQL Server Database Table that is connected through ODBC. After I submit the data it shows up as a blank row with only the ID that has a value. I am very new to PHP and got parts of code from tutorials. This is just a test project. Here's the code:
<html>
<header>
<title>
</title>
</header>
<body>
<form action="\INSERTCODE.php" method="POST">
<input type= "number" step="any" name="sepal_lengp" placeholder="Sepal Length">
<input type= "number" step="any" name="sepal_widthp" placeholder="Sepal Width">
<input type= "number" step="any" name="petal_lengp" placeholder="Petal Length">
<input type= "number" step="any" name="petal_widthp" placeholder="Petal Width">
<input type= "text" name="flower_type" placeholder="Flower Name">
<button type="submit" name="submit" >INPUT VALUES</button>
</form>
<?php
//display all results from table
include("C:\Users\Dshop\Desktop\php-7.3.3\Server1\connection.php");
$i=1;
$sql = "SELECT * FROM dbo.textcsv";
$result = odbc_exec( $connection, $sql );
while($all =odbc_result_all($result,$i) ){
echo $all;
}
?>
</body>
</html>
This part includes the form. The filename is index1.php.
<?php
include("C:\Users\Dshop\Desktop\php-7.3.3\Server1\connection.php");
$sepal_lengp = $_POST['sepal_lengp']??'';
$sepal_widthp = $_POST['sepal_widthp']??'';
$petal_lengp = $_POST['petal_lengp']??'';
$petal_widthp = $_POST['petal_widthp']??'';
$flower_typep = $_POST['flower_typep']??'';
$dbinsert = "INSERT INTO dbo.textcsv (sepal_leng, sepal_width, petal_leng, petal_width, flower_type) VALUES ('$sepal_lengp', '$sepal_widthp', '$petal_lengp', '$petal_widthp', '$flower_typep');";
odbc_exec( $connection, $dbinsert );
HEADER("Location: ../index1.php?=success");
This part inserts data into the database table, using $_POST to obtain the data from index1.php. This file is called INSERTCODE.php. $connection and connection.php is the file that includes the connection to ODBC.
For this test project I used the Iris dataset. I believe that I had to use ODBC and SQL Server instead of mysql. Sql server is the 2014 version, PHP is 7.33, using node.js to run the server. Help is greatly appreciated!
EDIT I found out that the $_POST isn't getting any values from the form. Any ideas?
EDIT 2 I've tried using $_REQUEST, checking var_dump, and did all that stuff, but I still got nothing. After going to https://www.w3schools.com/php7/php7_forms.asp for an example form, I found out that the example did not work either. Now i'm not sure if the problem is from the code, or from something like the php configuration. Need help, please help.
you're treating your variables as strings, by th look of your database you want them as floats. Try using floatval( ) (http://php.net/manual/en/function.floatval.php) on your variables to make sure they are in the write format, this will also go some way to sanitising them until you update this to prepare statements so you can safely bind the values and specify the type
After rephrasing my issue to "node.js not taking post data" I found the issue. Node.js needs extra steps to process POST data. So, because of this, my input was ignored by node.js and the INSERTDATA.php ran without any data to insert anything. Turns out the solution of the problem was to use something like the body-parser or the other solution from another question.
The solution I took was to uninstall node.js and use XAMPP instead. It was much easier to use.
Also could someone flag my question for duplicate?

PHP INSERT INTO MySQL not working, no error given

I am currently trying to execute an INSERT INTO when a search button is clicked. Eventually I'd like to submit the search term into the database, however I'm currently just trying to submit a simple string to ensure the initial INSERT INTO works correctly, which it currently doesn't.
I have the following:
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="search" name="search" id="results" placeholder="Enter search">
<input type="submit" name="submit" class="frstBtn" value="searchterm"><br>
</form>
<?php
$searchterm = "";
?>
<?php
if(isset($_POST['submit']))
{
$sql = "INSERT INTO tableName (variableName) VALUES ('test')";
$results = mysqli_query($conn,$sql) or die(mysqli_error());
}
?>
The latter php function, search, works perfectly fine, but the former function including the INSERT INTO does not.
Here is the table itself in phpmyadmin.
I have successfully manually copied and pasted the actual INSERT INTO statement into the actual database and it has worked fine, so I know the issue isn't with the statement. Any help is much appreciated. Thanks.
Since the searchTerm column is defined as PRIMARY, I’m ready to bet that you are trying to insert the same value twice and you don't have enabled the error_reporting. To find out exactly what the problem is, first of all enable all errors by adding the following at the beginning of your script:
ini_set('error_reporting', -1);
ini_set('display_errors', 1);
Also, note that you must use mysqli_error($conn) instead of mysqli_error().
By the way, to ignore errors when inserting unique values, use:
INSERT IGNORE INTO searchHistory(searchTerm) VALUES ('test')

PHP & MySQL - Updating Query

I need some help with updating query (html, php, mysql).
So I tried updating mySQL query (signature) connected with HTML. But I often face some problems.
I'd like to update a query (signature) by typing new signature in a form and a button that will submit action and change.
So basically I want to update user's signature when he types new one in a field and submits (presses a button).
If anyone can make a basic system for me so we will look forward successfully making the system.
Edit:
Yeah I know that nobody will write the script for me but I'm just out of ideas how could it be made. I'm no professional at all. I apologize for that :)
Anyway, this is the code:
<form action="update_signature.php">
<input type="text" name="txt" />
<input type="submit" name="insert" value="insert" onclick="insert()" />
</form>
I'm not sure what should I type in update_signature.php so I wrote a simple query:
<?php
$myq = mysql_query("UPDATE userSignature FROM users WHERE userSignature='$signature'")
$row=mysql_fetch_array($myq);
?> `
Thanks :)
I like how StackOverflow does not allow comments under 50 reputation...
The HTML code should have a "method", but if you skip it, it just posts as a "get", so not really a problem. In the "onclick" parameter however, you give it a JavaScript function, which does not exist?
The PHP is a mess. First, you need to retrieve the sent value with
$something = $_GET['txt'];
This puts the value what was left in the input with the name txt into a variable.
Second, the UPDATE syntax is totally different, it's more like
"UPDATE table SET column = '$phpvariable', etc... WHERE column2 = '$phpvariable2'"
where column is the name of the column in your table, and the query is successful in the lines where the column2 value is equal to the $phpvariable2.
Third, the UPDATE returns with a yes or no (success or not), not with an array.

Inserting data from form into table using php

I just finished installing Xampp and trying it out.
I wrote a php script to connect to my database like this :
$mysqli = new mysqli("localhost","root","","triology");
$mysqli->select_db("triology");
$table ="users";
Now I want to insert data into my database table from a form I have created using php but I am getting an error message from mysql:
Table triology.users' doesn't exist.
Even though I have created the table in phpmyadmin.
The code to insert into my table is :
$mysql = "INSERT INTO $table VALUES('$_POST[firstname]','$_POST[lastname]')";
and my form code is:
<form action="index.php" method="post"/>
FirstName<input type="text" size="25">
LastName<input type="text" size="25"/>
<input type="submit" value="Submit" />
Please don't worry about sql injection as I am just trying it out.
The error message you get is pretty clear about your problem. When you see this message, you either misspelled table name when creating or your table is not there or the table is in a different database.
Also another thing after you initiate the connection with mysqli, you do not need the select database again with $mysqli->select_db("triology"); because you are already selecting your database when you create the connection with new mysqli("localhost","root","","triology");
i am not sure but i might cause duplication in your path and cause the problem.

Categories