Error messages when inserting data from form into sql - php

I have a small problem here...
I need to insert data into a database from a form. This works, but i have two problems.
When i launch the website, a blank row is added into the database.
when i launch the website and the whole time, i get a errormessage for each object i want to insert to the database. The errorcode i get is;
Notice: Undefined variable: start in C:\wamp\www\index.php on line 51
Notice: Undefined variable: start in C:\wamp\www\index.php on line 52
Notice: Undefined variable: start in C:\wamp\www\index.php on line 53
How can i fix this problem?
here is my code:
<html>
<head>
<title>ARbeidstimer</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h2>Arbeidstimer</h2>
<div id ="register">
<form action="index.php" method="post">
<p>
<label>Start: </label>
<input type="text" name="start" class="field">
</p>
<p>
<label>Slutt:</label>
<input type="text" name="slutt" class="field">
</p>
<p>
<label for="telefon">Timer:</label>
<input type="text" name="timer" class="field">
</p>
<p>
<input type="submit" name="submit" value="send">
</p>
</form>
</div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "timer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])) {
$start = $_POST['start'];
$slutt = $_POST['slutt'];
$timer = $_POST['timer'];
}
$sql = "INSERT INTO jobbing (id, start, slutt, timer)
VALUES ('', '$start', '$slutt', '$timer')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
</html>

You check your submit status with if, but you dont wrap the code around if brackets, which means, the insertion and connection is still made, even though there is no submission.
Correct code:
if(isset($_POST['submit'])) {
$start = $_POST['start'];
$slutt = $_POST['slutt'];
$timer = $_POST['timer'];
$sql = "INSERT INTO jobbing (id, start, slutt, timer)
VALUES ('', '$start', '$slutt', '$timer')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
ID (if its auto increment) doesn't need to be in your INSERT INTO query.

Your if condition is checking the submit is set or not but executing the query since closing braces of if is closed before the query. So just move the closing braces of if block at the end.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])) {
$start = $_POST['start'];
$slutt = $_POST['slutt'];
$timer = $_POST['timer'];
$sql = "INSERT INTO jobbing (id, start, slutt, timer)
VALUES ('', '$start', '$slutt', '$timer')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>

Related

Insert Data to MySQL db from HTML form using PHP

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";
}
}
?>

php mysqli inserting duplicate value

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

INSERT INTO with PHP $_POST

I'm new to database development, and really struggling with formatting. For the life of me, I can't seem to flush out the errors. I have a simple html form that I am passing to my php file to submit to my local host. For whatever reason, I can't seem to add $_POST in the values. I'm sure I'm missing something, maybe someone on here can help.
Thanks in advance!
<form method="post" action="demo.php">
<input type="text" id="fname">
<input type="text" id="lname">
<input type="text" id="email">
<input type="submit" value="Go!">
</form>
My demo.php is:
<html>
<body>
<?php
$servername = "localhost";
$username = "myuser";
$password = "";
$dbname = "my_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql =
'INSERT INTO
test_tb (firstname, lastname, email)
VALUES
(
"echo $_POST['fname']",
"echo $_POST['lname']",
"echo $_POST['email']"
)';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
</html>
First change your form..
Look at your inputs; take this one for example:
<input type="text" id="fname">
This is missing the name attribute therefore, it won't be correctly set when you submit the form; it must be like so:
<input type="text" id="fname" name="fname">
Secondly, if you want to concatenate a string, you don't use echo, echo is used for outputting text. To attach strings together in PHP you should read the manual page on string operators
Thirdly and most importantly;
Use prepare to input your data. Never pass $_POST directly into your query.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql =
'INSERT INTO
test_tb (firstname, lastname, email)
VALUES
(
?,
?,
?
)';
//use ->prepare in favour of ->query
if ($stmt = $conn->prepare($sql)) {
//bind your inputs
$stmt->bind_param('sss',$_POST['fname'],$_POST['lname'],$_POST['email']);
//execute the prepared query
if($stmt->execute()){
echo "New record created successfully";
}
//You had a random ';' here that I've commented out??
//;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo "</br>Stmt error: ".$stmt->error();
}

Why is my PHP / SQL generating duplicate database entries?

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;
}

PHP redirect to different page after form submit

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".

Categories