MYSQL insert into database using php and html form - php

I'm trying to insert into an MYSQL database using php and an html form. When I press submit it says an item inserted successfully but when I log into phpmyadmin the table is empty?
My html form code is creon.html.
<form name="bmr_calc" action="https://cs1.ucc.ie/~lmm12/Project/creon.php" method="POST" id="BMRform">
<h1 id="info">Creon Calculator</h1>
<table>
<tr>
<td colspan="2" align="center">I take one: <br>
<input type="radio" name="creon1" value="10" required> Creon 10,000
<input type="radio" name="creon1" value="25" required> Creon 25,000
<br>per <input type="text" name="creon3" required>g of fat
</td>
</tr>
<br>
<tr>
<td>There are:</td>
<td><input type="text" name="creon4" required>g of fat in the item I'm about to eat</td>
</tr>
</table>
<td><input type="submit" value="Submit" style="float:center">
<br>
<img src="img/regpic.jpg" alt="reg" id="reg">
<br>
</td>
</form>
My php code is creon.php and it's saved on my college server;
<?php
$creon1 = $_POST['creon1'];
$creon3 = $_POST['creon3'];
$creon4 = $_POST['creon4'];
if (!empty($creon1) || !empty($creon3) || !empty($creon4)) {
$host = "cs1.ucc.ie";
$dbUsername = "lmm12";
$dbPassword = "----";
$dbname = "mscim2018_lmm12";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$INSERT = "INSERT Into creon (creon1, creon3, creon4) values(?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("sss", $creon1, $creon3, $creon4);
$stmt->execute();
echo "New record inserted sucessfully";
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}

This seems to be either a type issue in MySQL or a Type issue in your PHP code
To be sure, upload your data types from the table creon aka are the fields varchars, text etc.
Notice the if/else statement around bind_param you need to do that too just in case something isn't quite right, also capitalize INTO in your statement.
I ran the following:
<?php
$creon1 = $_POST['creon1'];
$creon3 = $_POST['creon3'];
$creon4 = $_POST['creon4'];
if (!empty($creon1) || !empty($creon3) || !empty($creon4)) {
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "quick";
//create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'. mysqli_connect_error());
} else {
$test = "INSERT INTO testing (creon1, creon3, creon4) values(?, ?, ?)";
//Prepare statement
$stmt = $conn->prepare($test);
if ($stmt != false)
$stmt->bind_param("sss", $creon1, $creon3, $creon4);
else
print("Returns false");
$stmt->execute();
echo "New record inserted sucessfully";
$stmt->close();
$conn->close();
}
} else {
echo "All field are required";
die();
}
?>
It gave me this result after submitting the form:
In my database it inserted the row:

Related

"php not inserting in to mysql server in xampp"

"I have read a lot of problem been solved in stackoverflow similar to my problem, and have seen a lot of example, yet still my code is not inserting in to mysql. however if i hard feed the php it would insert. my info is coming as submit from html post.I have good server connection and also connection to the database, can any one help me if i miss any thing. here is my code below."
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="image";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $db); // Establishing Connection with Server
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully";
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$image = $_POST['image'];
echo $name;
echo $image;
if($name !=''||$image !=''){
//Insert Query of SQL
$query = mysqli_query("INSERT INTO image (id, name, imagename) VALUES ('NULL', '$name', '$image')");
echo "Data Inserted successfully...!!";
}
else{
echo "Insertion Failed <br/> Some Fields are Blank....!!";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
<form action = "test2.php" method="POST" enctype="multipart/form-data">
<label>name: </label><input type="text" name="name" />
<label>File: </label><input type="text" name="image" />
<input type="submit" />
</form>
</body>
</html>
" i expect output of 5/2 to be 2.5"
Write the name for submit button
<input type="submit" name="submit" />
then in php file
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
}
this if statement will run
you not given name attribute to button so give name="submit" and if you want to upload file then change type="file"
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db="image";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $db); // Establishing Connection with Server
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully";
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$image = $_POST['image'];
echo $name;
echo $image;
if($name !=''||$image !=''){
//Insert Query of SQL
$query = mysqli_query("INSERT INTO image (id, name, imagename) VALUES ('NULL', '$name', '$image')");
echo "Data Inserted successfully...!!";
}
else{
echo "Insertion Failed <br/> Some Fields are Blank....!!";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
<form action = "test2.php" method="POST" enctype="multipart/form-data">
<label>name: </label><input type="text" name="name" />
<label>File: </label><input type="file" name="image" />
<input type="submit" name="submit" />
</form>
</body>
</html>
You're checking isset($_POST['submit']) but there is no input field which is posted with submit name.. you need to add the name attribute in the submit button. also you're not passing the $connection in the mysqli_query.
$servername = "localhost";
$username = "root";
$password = "";
$db="image";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $db); // Establishing Connection with Server
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
else{
echo "Connected successfully";
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$name = $_POST['name'];
$image = $_POST['image'];
echo $name;
echo $image;
if($name !=''||$image !=''){
//Insert Query of SQL
$query = mysqli_query($connection, "INSERT INTO image (id, name, imagename) VALUES ('NULL', '$name', '$image')");
if($query !== false){
echo "Data Inserted successfully...!!";
}
else{
echo "Query failed";
}
}
else{
echo "Insertion Failed <br/> Some Fields are Blank....!!";
}
}
mysqli_close($connection); // Closing Connection with Server
?>
<form action = "test2.php" method="POST" enctype="multipart/form-data">
<label>name: </label><input type="text" name="name" />
<label>File: </label><input type="text" name="image" />
<input type="submit" name = "submit" />
</form>
</body>
</html>
One more suggestion always use PDO in code to prevent SQL injection. Your code is vulnerable to sql injection.

How do I insert values from a form using php and sql using my own script?

Hi first time user and beginner when it comes to using php,
How do I go about inserting values from a form using php and sql.
Ive created the following code using php and sql.
here is my form.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
?>
<form action="/t.php" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
<?php
// set parameters and execute
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$stmt->execute();
$stmt->close();
$conn->close();
?>
the t.php file is simply saying entries were added successfully even though there is no logic there, just a simple echo comment.
I just want to know how to insert data using forms with php and sql.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<form action="/t.php" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
// set parameters and execute
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
$stmt->execute();
$stmt->close();
$conn->close();
}
?>
You can do it like this:
To prevent duplication, save the db connection in a file called db.php.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Then, include it in the main.php file. Here's the main.php file written with prepared statement errors prevented.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
# check if all the params are set
if (
!empty($_POST['firstname']) &&
!empty($_POST['lastname']) &&
!empty($_POST['email'])
) {
$firstname = htmlspecialchars(trim($_POST['firstname']));
$lastname = htmlspecialchars(trim($_POST['lastname']));
$email = htmlspecialchars(trim($_POST['email']));
include_once 'db.php';
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
if (
$stmt &&
$stmt->bind_param("sss", $firstname, $lastname, $email) &&
$stmt -> execute()
) {
echo "Yay! Inserted.";
} else {
throw new Exception("Error in MYSQLI Statement");
}
} else {
throw new Exception("Some data is not set");
}
} catch (Exception $e) {
die($e -> getMessage());
}
} else { ?>
<form action="" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
<?php } ?>
The strings should be validated before inserted into the database. Here I have used htmlspecialchars() to prevent XSS and trim() to remove unnecessary white spaces.
Thanks.
Form action will call t.php, but you dont have it!
Create two files: myHtml.html and t.php in the same folder
myHtml.html
<html>
<form action="t.php" method="post">
First name:
<input type="text" name="firstname">
<br> Last Name:
<input type="text" name="lastname">
<br>Email:
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
</html>
t.php
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "datab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind with form attached.
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$stmt->execute();
$stmt->close();
$conn->close();

Combine separate HTML and PHP MYSQL form into one file

The reasons behind my needing this are complicated but I have a currently working HTML form that inserts a row into my MYSQL database. However... I need to combine the two separate processes into one HTML file but after many attempts at arranging the code cannot come to a working solution. Hopefully someone can point me in the right direction.
Here is the HTML file:
<form method="post" action="process.php">
<input type="text" name="id" placeholder="Enter ID" /><br />
<input type="hidden" name="user_text" id="hiddenField" value="x" /><br />
<input type="submit" value="Submit" />
</form>
Here is the related process.php file:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//mysql credentials
$mysql_host = "localhost";
$mysql_username = "*";
$mysql_password = "*";
$mysql_database = "*";
$u_name = $_POST["id"];
$u_text = $_POST["user_text"];
if (empty($u_name)){
die("Please enter your id");
}
//Open a new connection to the MySQL server
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$statement = $mysqli->prepare("INSERT INTO users_data (contractor_id, status) VALUES(?, ?)"); //prepare sql insert query
$statement->bind_param('ss', $u_name, $u_text); //bind values and execute insert query
}
?>
I know this isn't the right way to do things but it isn't for a public site, more a personal logging project. Thank you in advanced!
You can simply have a file like this:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
process();
}
else {
show_form();
}
function show_form () {
?>
<form method="post">
<input type="text" name="id" placeholder="Enter ID" /><br />
<input type="hidden" name="user_text" id="hiddenField" value="x" /><br />
<input type="submit" value="Submit" />
</form>
<?php
}
function process () {
//mysql credentials
$mysql_host = "localhost";
$mysql_username = "*";
$mysql_password = "*";
$mysql_database = "*";
$u_name = $_POST["id"];
$u_text = $_POST["user_text"];
if (empty($u_name)){
die("Please enter your id");
}
//Open a new connection to the MySQL server
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$statement = $mysqli->prepare("INSERT INTO users_data (contractor_id, status) VALUES(?, ?)"); //prepare sql insert query
$statement->bind_param('ss', $u_name, $u_text); //bind values and execute insert query
}
If you do not set theaction for form, by default, it submits to itself

Insert database not working

Hi Im working on a school project and i cant insert this into the database
What am I doring wrong? I dont have any error`s so I im stuck. Please help me. I do have a connection to the database. But the things I insert into the form do not show in to the databse.
$servername = "localhost";
$username = "root";
$password = "root123";
$dbname = "ToetsPro";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "INSERT INTO `opleiding` (`id`,
`opleiding`,
`locatie`)
VALUES (NULL,
'".$_POST["opleiding"]."',
'".$_POST["locatie"]."');";
//echo $query; exit();
$result = mysqli_query($conn, $query);
$id = mysqli_insert_id($conn);
?>
<!DOCTYPE HTML>
<form id="register" action="" method="post">
<table>
<tr>
<td>Opleiding: </td>
<td><input type="text" name="opleiding"></td>
</tr>
<tr>
<td>Locatie: </td>
<td><input type="text" name="locatie"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
Terug naar de homepage
What am I doring wrong? I dont have any error`s so I im stuck.
well there are few things you doing wrong.
one of the very first things I have noticed is that you are mixing up Object oriented style and Procedural style
doing so might confuse you in the long run.
here your db connection
$conn = new mysqli($servername, $username, $password, $dbname);
You using mysqli object oriented style
Then here : $result = mysqli_query($conn, $query); You using procedural style. I suggest that you only stick with one style, in that way you can easily read,organize and maintain your code.
two : You might be making an error with your insert statement, id then inserting a null on the ID that might be the problem, if your id is an auto_increment better not even include it within your query.
three You are writing a dangerous code, that will harm your application in the long run. you are directly inject $_POST values in your query, that might dangerous and it leave your application wide open to sql injections
You should learn to use prepared statements, with mysqli or PDO prepared statements.
This is how your code should look :
<?php
$servername = "localhost";
$username = "root";
$password = "root123";
$dbname = "ToetsPro";
// 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'])) {
//check and validate your inputs
$opleiding = $_POST['opleiding'];
$locatie = $_POST['locatie'];
$query = $conn->prepare("INSERT INTO `opleiding` (opleiding,locatie)VALUES(?,?)");
$query->bind_param("ss", $opleiding, $locatie);
if ($query->execute()) {
echo "success";
$id->insert_id;
} else {
echo "Error :" . $conn->error;
}
}
?>
<!DOCTYPE HTML>
<form id="register" action="" method="post">
<table>
<tr>
<td>Opleiding: </td>
<td><input type="text" name="opleiding"></td>
</tr>
<tr>
<td>Locatie: </td>
<td><input type="text" name="locatie"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
Terug naar de homepage
I think first of all you should use mysqli_real_escape_string() for every variable data filtering then your query should like this way:
$query = "INSERT INTO `opleiding` (`id`,`opleiding`,`locatie`) VALUES (NULL,'".$_POST['opleiding']."','".$_POST['locatie']."')";

Why this code inserts blank?

I´m trying to create a form connected to a database but when I fill out the form and I refer to the table in phpMyAdmin I see that it have entered a blank record instead of form data. I´m using PhpStorm.
I think all this code is correct...
That is the form of the .html:
<form id="form1" name="form1" method="post" action="index.php">
<label for="userSignUp">Email</label>
<input type="text" name="userSign" id="userSignUp" />
<label for="passwordSignUp">Password</label>
<input type="password" name="passwordSign" id="passwordSignUp" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
</form>
I have the following .php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db_selected = mysqli_select_db($conn, $dbname);
$userSignUp = ""; // If I substitute "" with characters at this time the table is well updated
$passwordSignUp = ""; // Same as before
if(isset($_POST['userSign'])){
$userSignUp = $_POST['userSign'];
}
if (isset($_POST['passwordSign'])) {
$passwordSignUp = $_POST['passwordSign'];
}
$sql = "INSERT INTO test.person (FirstName, Password) VALUES ('$userSignUp', '$passwordSignUp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

Categories