I created a website where you insert radio button data to the database after you click submit button.
However, the problem is that whenever I click the submit button it inserts two duplicate values instead of one.
My code is the following:
<form action="test.php" method ="post" >
<b> what is you fav sport ؟ </b>
</br>
<input type="radio" name="sport1" value="football"> football
<input type="radio" name="sport1" value="basketball"> football
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
mysqli_query($conn, "set names 'utf8'");
?>
<input type="submit" name="submit" value="submit"/>
<?php
if(isset($_POST['submit']) && !empty($_POST)){
$sport1 = $_POST['sport1'];
$SQL = "INSERT INTO userTable (user_q1) VALUES ('$sport1')";
$result = mysqli_query($conn, $SQL);
if ($conn->query($SQL) === TRUE) {
echo "New record created successfully";
}else{
echo "Error: " . $SQL . "<br>" . $conn->error;
}
$conn->close();
}
?>
</form>
Any help would be be appreciated.
you are doing the same thing twice
Just use either
$result = mysqli_query($conn, $SQL)
//or
$conn->query($SQL)
mysqli_query and $conn->query() are used fro same purpose.
just remove any one of the statement, you will get what you need
Related
I am trying to input data into a MySQL Database using PHP and a HTML Form but the data isn't saved into the database even though it shows that it has. Please show me how to ensure the form entries save to the database.
HTML
<form action="newproduct.php" method="post">
<table>
<tr>
<td>Username</td>
<td><input name="user" type="text"></td>
</tr> ...
<button type="submit">Go</button>
</form>
PHP
<?php
$servername = "localhost";
$username = $_POST["user"];
$password = $_POST["pass"];
$dbname = "bakefree_products";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO ".$_POST["range"]." (productname, image, frompricesize, paypalcode, productdesc, allergystandard, allergyglutenfree, allergyvegan, allergygfvegan)
VALUES ('".$_POST["productname"]."', '".$_POST["image"]."', '".$_POST["frompricesize"]."', '".$_POST["paypalcode"]."', '".$_POST["productdesc"]."', '".$_POST["allergystandard"]."', '".$_POST["allergyglutenfree"]."', '".$_POST["allergyvegan"]."', '".$_POST["allergygfvegan"]."')";
if (mysqli_query($conn, $sql)) {
echo "New product created successfully.";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
//show new number of products
$sql = "SELECT * FROM".$_POST["range"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "There are ".$result->num_rows ." products.";
} else {
echo "<br><br>There are no products in ".$_POST["range"];
}
mysqli_close($conn);
?>
RESULT
New product created successfully.
There are no products in TEST
Actually insertion should be working fine but you need to check the syntax of the select query here,
//show new number of products
$sql = "SELECT * FROM ".$_POST["range"]; // Added a space after `FROM`
And it should fetch data properly and show you the string, There are X products.
I'm trying to insert new record to SQL database using PHP from a HTML form.
I made a form using Post method
<form name="CreatNewMCQ" action="create.php" method="POST">
with a button to submit
<button type="submit" form="CreateNewMCQ">CREATE</button>
what I want to do is when I press the button, it will call create.php which is
<?php
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
// Create connection
$conn = new mysqli($servername, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, $name, $year)";
if ($conn->query($sql) === TRUE) {
echo "Tạo mới thành công";
} else {
echo "Lỗi: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
then insert data from form to SQL database (id, name, year from the form).
I got some errors in SQL syntax. What mistake did I make?
Make sure all post values are getting correctly. You should make a condition check before inserting the data, For ex:
$id = isset($_POST['id']) ? $_POST['id'] : '';
$name = isset($_POST['name']) ? $_POST['name'] : '';
$year = isset($_POST['year']) ? $_POST['year'] : '';
if($id && $name && $year){
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
}else{
return "required fields are missing";
}
NB: Please post your html if possible.
try this:
<?php
/* Attempt MySQL server connection.*/
$servername = "localhost";
$user = "admin";
$pass = "admin";
$dbname = "examples";
$link = mysqli_connect($servername, $user, $pass, $dbname);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$id = $_POST['id'];
$name = $_POST['name'];
$year = $_POST['year'];
$sql = "INSERT INTO cars (id, name, year)
VALUES ($id, '$name', '$year')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
HTML Form :
<html>
<form name="test" method="post">
Enter name:<input type="text" name="name"/> <br>
Enter year :<input type="text" name="year"/><br>
<input type="submit" name="save" value="save" />
</form>
</html>
php code :
<?php
$conn=mysql_connect("localhost","root","passward");
$select_db=mysql_select_db("Atul",$conn);
if($conn)
{
echo "connected";
}
else
{
echo "Please try again";
}
if(isset($_POST['save']))
{
$name=$_POST['name'];
$year=$_POST['year'];
$insert_record="insert into test (name,year) values("$name","$year");
$result=mysql_query($insert_record);
if($result)
{
echo "Record inserted successfully";
}
else
{
echo "please try again";
}
}
?>
i want to store a data to the mysql database but if i press the submit button it display the php page.
form:
<div id="test">
<form action="demo.php" method="post">
please enter the number(1 to 100) : <input type="text" name="value">
<input type="submit">
</form>
</div>
demo.php
<?php
$value=$_POST['value'];
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
if ($conn->query($input) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Replace $input with $sql in the if statement:
From
if ($conn->query($input) == TRUE) {
To
if ($conn->query($sql) == TRUE) {
Note: Since you are storing $_POST['value'] in $value, you don't need to use $_POST['value'] in the query, instead make use of $value.
There is one correction:
Change
if ($conn->query($input) == TRUE) {
To:
if ($conn->query($sql) == TRUE) {
Along with that, following are suggestions:
$sql = "INSERT INTO input VALUES (".$_POST['value'].")";
This query is OK, is value of $_POST['value'] is integer, but, for strings, it will create SQL Syntax Error.
Please correct this to:
$sql = "INSERT INTO input VALUES ('".$_POST['value']."')";
Observe, enclosed semi colon.
2) You are inserting only one field value and not specifying fields. This means you table has only field. Normally we do not have tables with only one field.
Please specify field names:
$sql = "INSERT INTO input (field_one) VALUES (".$_POST['value'].")";
Get values like this
$value=$_REQUEST['value'];
change the query to
$sql = "INSERT INTO input VALUES ('$value')";
1st : Add name attribute to submit button name="submit"
<input name="submit" type="submit">
2nd : use isset like this if(isset($_POST['submit'])){ //rest of code here }
3rd : Try to use prepared statement or pdo to avoid sql injection
demo.php
<?php
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "clock";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$stmt = $conn->prepare("INSERT INTO input(value) VALUES (?)");
$stmt->bind_param('s',$_POST['value']);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
if ($stmt->execute() == TRUE && $stmt->affected_rows>0) {
echo "New record created successfully";
} else {
echo "Error: <br>" . $conn->error;
}
}
$conn->close();
?>
I'm quite new to PHP and an absolute beginner when it comes to SQL. I'm just learning the basics and I can't get my head around why my code is generating a duplicate entry every time the form is submitted, e.g.
Name: Joe Blogs Email: info#email.co.uk
Name: Joe Blogs Email: info#email.co.uk
The database has a table called user and two columns, name and email.
My index file looks like this, it has a simple form for name and email, and inserts the data on submit:
<form method="post" action="insert.php">
<input name="name" type="text">
<input name="email" type="email">
<input type="submit" value="Submit Form">
</form>
<?php
$servername = "localhost";
$username = "DB_USER";
$password = "PASSWORD";
$dbname = "DB_NAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlout = "SELECT name, email FROM user";
$result = $conn->query($sqlout);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<b>Name:</b> " . $row["name"]. " <b>Email:</b> " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<form method="post" action="wipe.php">
<input type="submit" value="Wipe ALL Data">
</form>
This insert.php file is called when the form is submitted:
<?php
$servername = "localhost";
$username = "DB_USER";
$password = "PASSWORD";
$dbname = "DB_NAME";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Back
I've probably made some basic mistakes but I'm not sure why it is adding duplicates. Is it something to do with connecting twice to the database in each file? Is there a better way to connect only once? Or is it caused by the form submission itself?
Because you call query twice:
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
You should rewrite is as
$insert = $conn->query($sql);
if ($insert === TRUE) {
Also, you should really be using prepared statements.
Your code Call $conn->query twice
$insert = $conn->query($sql);// first time
if ($conn->query($sql) === TRUE) {// second time
if ($insert === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You need change:
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$insert = $conn->query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
to
$sql = "INSERT INTO user ( name, email ) VALUES ( '{$conn->real_escape_string($_POST['name'])}', '{$conn->real_escape_string($_POST['email'])}' )";
$status = $conn->query($sql);
if ($status === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Here's the first bit of my form code
<form action="PHP/form.php" id="msform" method="post">
<fieldset id="owner_service">
<h2> ARE YOU A DOG OWNER OR SERVICE PROVIDER?</h2>
<legend>owner_service</legend>
<div class="owner_service">
<input type="radio" id="service" name="owner_service" value="service">
<label for ="service"><h5>SERVICE PROVIDER</h5></label>
<input type="radio" id="owner" name="owner_service" value="owner">
<label for ="owner"><h5>DOG OWNER</h5></label>
</div>
<input type="button" name="next" class="next action-button" id="next" value="NEXT" />
</fieldset>
and here's the PHP
<?php
session_start();
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO pets (owner_service, Gender, Age, Size, Location, idealLocation, Service)
VALUES ('{$_POST['owner_service']}', '{$_POST['gender']}', '{$_POST['age']}', '{$_POST['size']}', '$locationCommaString', '{$_POST['ideal_location']}', '{$_POST['service']}')";
if($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I've got my form running, so the results are in the database but what I want to do is bring the user to a new page depending on whether they clicked 'service provider' or 'dog owner'. I have no idea where to put the header because if I replace the if statement that I already have then the results won't show in my database.
The if statement goes after your query execution. Similar to what #laimingl suggested
if(isset($_POST['next'])) {
// your code to save data
// after submit without db error
if($_POST['owner_service'] == 'service') { // redirect page; }
else if($_POST['owner_service'] == 'owner') { // redirect page; }
}
Put it in same Scope of echo "New record created successfully";
<?php
session_start();
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO pets (owner_service, Gender, Age, Size, Location, idealLocation, Service)
VALUES ('{$_POST['owner_service']}', '{$_POST['gender']}', '{$_POST['age']}', '{$_POST['size']}', '$locationCommaString', '{$_POST['ideal_location']}', '{$_POST['service']}')";
if($conn->query($sql) === TRUE) {
echo "New record created successfully";
$serv = $_POST['owner_service'] ;
switch($serv){
case 'case 1':
// Page redirection code here
break;
case 'case 2':
// Page redirection code here
break;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Just change input type="button" to input type="submit".