Insert Data to MySQL db from HTML form using PHP - 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";
}
}
?>

Related

Store the data in mysql

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();
?>

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

PHP SQL : How to save data to multiple database from one html form OR how to copy data from one database to another database automatically

I have a html form, say example
<form action="form.php" method="post">
First name:<br>
<input type="text" id="fname" name="fname">
<br>
Last name:<br>
<input type="text" id="lname" name="lname">
<br><br>
<input type="submit" value="Submit">
</form>
and form.php
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The form.php is saving that data to database1 .
I want that data to be saved to another database database2 along with database1.
Is it possible ?? If yes then what changes should be made in the code ?
If it is not possible then is it possible to copy data from database1 to database2 automatically? Whenever a new row is added in database1 then it should automatically copied to database2.
I want the same data to be in two different database. How can I achieve any of the above said ??
From php you just have to create new connection to DB.
<?php
$servername = "localhost";
$username = "database1";
$password = "xxxxxxxx";
$dbname = "database1";
$servernameS = "localhost";
$usernameS = "database2";
$passwordS = "xxxxxxxx";
$dbnameS = "database2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$connS = new mysqli($servernameS, $usernameS, $passwordS, $dbnameS);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($connS->connect_error) {
die("Connection failed: " . $connS->connect_error);
}
//escape variables for security
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$sql = "INSERT INTO mytable (fname,lname)
VALUES ('$fname','$lname')";
if ($conn->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $conn->error;
}
if ($connS->query($sql) === TRUE) {
echo "Successfully Saved";
} else {
echo "Error: Go back and Try Again ! " . $sql . "<br>" . $connS->error;
}
$conn->close();
$connS->close();
?>
What it sounds like you need is to setup replication.
Here is the official documentation on replication. Here is a simpler step-by-step guide setting it up.
If replication isn't what you wanted, you could accomplish the same thing by connecting to database2 in addition to database1 then running the query once on both.
You can use something like using mysqli::selectDB method:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Check out the manual.
Similar question as yours at SO.

Submit post echo but does not write information in database

I'm having problem with updating information in database. The echo pops out as successful but the database row stays blank - why? PHP code:
<?php
if (isset($_POST['gender'])) {
// Sanitize and validate the data passed in
$gender = filter_input(INPUT_POST, 'gender', FILTER_SANITIZE_STRING);
if ($stmt) {
$stmt->bind_param('s', $gender);
$stmt->execute();
$stmt->store_result();
if ($insert_stmt = $mysqli->prepare("INSERT INTO members gender VALUE ?")) {
$insert_stmt->bind_param('s', $gender);
}
}
echo "<div class='notemarg'> Your gender has been submitted</div>";
}
?>
and input form:
<form action="" method="POST">
<input type="radio" name="gender" value="male"> Male <br>
<input type="radio" name="gender" value="female"> Female <br>
<input type="submit" name="gender" value="Set gender" class="button">
</form>
I want to use mysqli->prepare to prevent SQL injection.
I fixed it with alternative way, where there is pre-defined input by button.
<?php
$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);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$sql = "UPDATE members SET gender = '$gender' WHERE username = '".$_SESSION['username']."'";
if ($conn->query($sql) === TRUE) {
echo "<div class='notemarg'> Your gender has been submitted</div>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
And simple form:
<form action="" method="POST">
<input type="submit" name="Female" value="Female" class="button">
</form>
Thanks to all who wanted to help me, especially to anant kumar singh. I could not get that alter idea without his suggestions. Thanks!
UPDATE #1
It just pops out that echo "error"
<?php
if(isset($_POST['Female'])){
$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);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$stmt = $conn->prepare('UPDATE members
SET gender = ?
WHERE username = ?');
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
if ($conn->prepare === TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " . $conn->prepare . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
Don't know where is problem...
UPDATE #2
if(isset($_POST['Female'])){
$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);
}
if (isset($_POST['Female'])) {
$gender = $_POST['Female'];
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
$stmt->execute();
if ($mysqli->prepare($sql) === TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " . $conn->prepare . "<br>" . $conn->error;
}
$conn->close();
}
}
UPDATE #3
I added also some notes in code so
<?php
// I had here twice the ifisset here and
if(isset($_POST['Female'])){
$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);
}
//here the second one so I deleted that ifisset here...
$gender = $_POST['Female'];
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $_POST['Female']);
$stmt->bind_param('s', $_SESSION['username']);
$ok = $stmt->execute();
if ($ok == TRUE) {
echo "<font color='#00CC00'>Your gender has been updated.</font><p>";
} else {
echo "Error: " .$stmt->error; // This is the line that shows the error
}
$conn->close();
}
?>
I'm not sure what is problem... It pops the error on echo "No data supplied for parameters in prepared statement"
Following an answer being posted with a huge security vulnerability, it is worth taking a moment to fix this. There is a way to fix it so you can use your string concatenation approach, but it is generally not as good as parameterisation.
All you need to do is to take your working query, and convert it to a parameterised form. Something like this:
// Expects valid $mysqli object here
$sql = "
UPDATE members
SET gender = ?
WHERE username = ?
";
$stmt = $mysqli->prepare($sql);
// ** As we discovered, the binding needs to happen in one
// ** call, not across several
$stmt->bind_param('ss', $_POST['Female'], $_SESSION['username']);
$stmt->execute();
Looking at your original code, there seems to have been two problems: the statement wasn't prepared at all (and so the program should have exited with a fatal error) and there was a syntax error in the original SQL statement.
In your new code, you're missing the execute() call.

Categories