SQL - Insert form into a database - php

I have a php script to insert form input into a database called XXXX_comments into the Table called Comments that has Name and Comment as columns.When a user hits Save button the form should be inserted into the DB. I connect to the database using connect.php :
<?php
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
$Dbconnect = "XXX_comments";
// Create connection
$conn = new mysqli($servername, $username, $password);
mysqli_select_db($conn,$Dbconnect);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
in my index.php file i have the following form:
<?php
include ('connect.php');
?>
<?php
if(isset($_POST['Save'])){
$sql = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $comment);
$firstname = $_POST['firstname'];
$comment = $POST['comment'];
$stmt->execute();
Echo "Succefully inserted to table";
}
?>
<div class="container">
<div class="row" id="post-review-box" style="display:none;">
<div class="col-md-12">
<form id="form" accept-charset="UTF-8" action="index.php" method="post">
<input type="text" class="form-control animated" id="firstname" type="hidden" placeholder="Enter your Name">
<br>
<input id="ratings-hidden" name="rating" type="hidden">
<textarea class="form-control animated" cols="50" id="comment" placeholder="Enter your review here..." rows="5"></textarea>
<br>
<div class="text-right">
<div class="stars starrr" data-rating="0"></div>
<a class="btn btn-danger btn-sm" href="#" id="close-review-box" style="display:none; margin-right: 10px;">
<span class="glyphicon glyphicon-remove"></span>Cancel</a>
<button class="btn btn-success btn-lg" type="submit" name="Save">Save</button>
</div>
</form>
</div>
</div>
</div>
<div class="display"></div>
</div>
</div>
</div>
The connection is successful but the data is not being inserted.

You need to assign values before you can use them as below code:
$firstname = $_POST['firstname'];
$comment = $_POST['comment'];
$sql = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
$stmt->bind_param("sss", $firstname, $comment);

You should give name to your inputs and textarea inside the form as
<input type="text" name="firstname" class="form-control animated" id="firstname" type="hidden" placeholder="Enter your Name">
<input id="ratings-hidden" name="rating" type="hidden">
<textarea class="form-control animated" cols="50" name="comment" id="comment" placeholder="Enter your review here..." rows="5"></textarea
and you are assigning values after the binding it to the query, you should assign values for $firstname and $comment before binding it to the query as
if(isset($_POST['Save'])){
$firstname = $_POST['firstname'];
$comment = $_POST['comment'];
$sql = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $comment);
$stmt->execute();
echo "Succefully inserted to table";
}
Edit: The code was using $POST instead of $_POST.

Few remarks:
First of all, in the connect.php file you're mixing OOP and Procedural styles, you can gain the same result by using the following code:
$conn = new mysqli($servername, $username, $password, $Dbconnect);
Next, in your index.php, you've created a prepared statement, but you assigned that to $sql variable, and later you tried to use the undefined $stmt variable, so in order to fix that just change the first 2 lines
$stmt = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
$stmt->bind_param("ss", $firstname, $comment);
Hope it will solve your little issue!

For any one intrested I have solved the issue, It seemed like the submit button wasn't responding So i added a javascript onclick function to force submit the form.
<input class="btn btn-default" onclick="myFunction()" value="Submit">
<script>
function myFunction() {
document.getElementById("form").submit();
}
</script>
Thanks for all the answers.

Related

html form radio buttons not saving string to database

I have a html form which includes a question involving three radio buttons. I want the word 'road', 'both' or gravel' to be saved to my database. This field is set up as a varchar in the database.
This is my html:
<div class="form-group">
<label>Do you prefer just road or gravel/trail cycling as well?</label>
<label for="road">Just road</label>
<input type="radio" name="bike_terrain" id="road" value="road" required/>
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="both">Both</label>
<input type="radio" name="bike_terrain" id="both" value="both" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="gravel">Just gravel/trail</label>
<input type="radio" name="bike_terrain" id="gravel" value="gravel" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
</div>
I am then using php to validate the input is not empty:
if(empty($_POST["bike_terrain"])){
$bike_terrain_err = "Please select a bike terrain.";
} else {
$bike_terrain = isset($_POST["bike_terrain"]);
}
And php to send it to my localhost database:
if(empty($username_err) && empty($email_err) && empty($bike_terrain_err)) {
// Prepare an insert statement
$sql = "INSERT INTO users (username, email, terrain) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $param_username, $param_email, $param_terrain);
// Set parameters
$param_username = $username;
$param_email = $email;
$param_terrain = $bike_terrain;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Oops! Something went wrong. Please try again later.248";
}
}
}
(Note: I have cut out some of the other fields that I am inserting for simplicity)
$bike_terrain has previously been initialised as a string.
The problem is that nothing is being saved to the terrain field in my database and I don't know why!
Thank you very much! All suggestions, thoughts or ideas are very welcome.
Something like this (untested) should do the trick. you save the same radio with the same name so it would look like a selection somehow.
Had to quickly code from my mobile device XD
<?php
if(isset($_POST['submit'])){
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db = 'people_db'
$con = mysqli_connect($host, $user, $pass, $db) or die ('Cannot connect'.mysqli_error());
$fullname = mysqli_real_escape_string($con,$_POST['fullname']);
$gender = mysqli_real_escape_string($con,$_POST['gender']);
$q = "insert into employeedb (fullname, gender) values ('".$fullname."', '".$gender."')";
mysqli_result($con,$q);
echo 'Data Saved to Database!';
}
?>
<html>
<head>
<title>Save Radio to DB</title>
</head>
<body>
<form name="people" method="POST" action="index.php"
<input type="text" name="fullname" placeholder="Enter your name"/><br/>
<input type="radio" name="gender" value="Male"/>
<input type="radio" name="gender" value="Female"/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

Form to post into database table

I'm trying to make a form that posts the index.php input to my database table using index.php and connection.php. Also I'm trying to specify everything else to be in letter format except the phone number (puhelinnumero) in numeric format using bind_param, but it gives me this error:
Here is the index.php.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="lomake-container">
<form action="connection.php" method="POST">
<h2>Ilmoittautumis lomake</h2>
<div class="lomake-block">
<label for ="nimi">Etunimi</label>
<input type="text" name="etunimi" id="nimi" placeholder="Etunimi">
</div>
<div class="lomake-block">
<label for ="sukunimi">Sukunimi</label>
<input type="text" name="sukunimi" placeholder="Sukunimi">
</div>
<div class="lomake-block">
<label for="male">Mies</label>
<input type="radio" id="male" name="sukupuoli">
</div>
<div class="lomake-block">
<label for="female">Nainen</label>
<input type="radio" id="female" name="sukupuoli">
</div>
<div class="lomake-block">
<label for="other">Muu</label>
<input type="radio" id="other" name="sukupuoli">
</div>
<div class="lomake-block">
<label for ="sähköposti">Sähköposti</label>
<input type="text" name="sähköposti" id="sähköposti" placeholder="Sähköposti">
</div>
<div class="lomake-block">
<label for ="salasana">Salasana</label>
<input type="text" name="salasana" id="salasana" placeholder="Salasana">
</div>
<div>
<label for ="puhelinnumero">Puhelin numero</label>
<input type="text" name="puhelinnumero" id="puhelinnumero" placeholder="Puhelin num.">
</div>
<input type="submit" value="Lähetä">
</form>
</div>
</body>
</html>
Here is the connection.php
<?php
$etunimi = $_POST["etunimi"];
$sukunimi = $_POST["sukunimi"];
$sukupuoli = $_POST['sukupuoli'];
$sähköposti = $_POST['sähköposti'];
$salasana = $_POST['salasana'];
$puhelinnumero = $_POST['puhelinnumero'];
$servername = "localhost";
$username = "root";
$password = '';
$database = 'palvelu';
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else {
echo "Yhteys onnistui";
$stmt = $conn->prepare("insert into lomake($etunimi, $sukunimi, $sukupuoli, $sähköposti, $salasana, $puhelinnumero)
values(?, ?, ?, ?, ?, ?)");
}
$stmt->bind_param("sssssi",$etunimi, $sukunimi, $sukupuoli, $sähköposti, $salasana);
echo "onnistui jea";
$stmt->execute();
$stmt->close();
$conn->close();
?>
Here is the table:
You can't parameterise column names, but anyway I'm pretty sure that's not actually your intention, and you've possibly slightly misunderstood how to build an INSERT query. You need to specify the column names you want to insert into. The variable values you're currently trying to use in place of column names will be automatically assimilated into the query via the ? placeholders when MySQL receives the query.
Also you forgot to put the last value into the bind_param command.
Lastly your logic is a tiny bit flawed - if the connection fails, then your code will die. There's no need for the else. If it doesn't die, just carry on.
Try this instead:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Yhteys onnistui";
$stmt = $conn->prepare("insert into lomake(`nimi`, `sukunimi`, `gender`, `email`, `password`, `number`) values(?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssi",$etunimi, $sukunimi, $sukupuoli, $sähköposti, $salasana, $puhelinnumero);
echo "onnistui jea";
$stmt->execute();
$stmt->close();
$conn->close();
P.S.
Here is the MySQL documentation reference for INSERT: https://dev.mysql.com/doc/refman/8.0/en/insert.html

Updating records in database using a pre populated form

Looks like I have 1 last issue that I can't solve due to the fact of being too unexperienced with this matter. This last issue that I can't get to work or basically I don't understand the order in how to do this.
Been able to do the following:
Form that writes records to database
Page that shows database records in a table
Added an edit button to the table that takes you to an edit.php page with a form that has all values pre filled.
What I'm trying to get to work now is to edit one of the inputs on the form so it get's updated in the database.
So far I have this on the edit.php page:
<?php
$servername = "localhost";
$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 = "SELECT id, name, email, age FROM members WHERE id =" .$_GET['id'];
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$id = $row['id'];
$name = $row['name'];
$email = $row['email'];
$age = $row['age'];
?>
<form action=" <?=$_SERVER['PHP_SELF']?> " method="POST">
<div align="center">
<div class="container">
<div class="row">
<div class="col-25">
<label for="#"></label>
</div>
<div class="col-75">
<h2>ID: <?php echo $row['id']; ?></h2>
</div>
</div>
<br>
<div class="row">
<div class="col-25">
<label for="name">Name:</label>
</div>
<div class="col-75">
<input type="text" name="name" value="<?php echo $row['name']; ?>" id="my-input" class="input-res">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="email">Email:</label>
</div>
<div class="col-75">
<input type="text" name="email" value="<?php echo $row['email']; ?>" class="input-res">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="age">Age:</label>
</div>
<div class="col-75">
<input type="text" name="age" value="<?php echo $row['age']; ?>" class="input-res">
</div>
</div>
<div class="row"><br>
<input type="submit" name="submit" value="Save updates" class="button">
</div>
</div>
</div>
</form>
</body>
</html>
Have tried adding this code below the form:
<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
$sql="UPDATE name, email, age SET name, email, age WHERE name = ".$name.", email = ".$email.", age = ".$age.";
$conn->query($sql) or die("Cannot update");//update or error
}
?>
But the the page doesn't work anymore, tried changing from single quotes to double qoutes etc. but no success and a few other solutions (that unfortunatelly didn't work).
Need $_POST to get posted value
Use prepare for security
note: die is a wrong idea here
Correct code will be:
<?php
if (isset($_POST['Submit'],$_POST['name'],$_POST['email'],$_POST['age'],$_GET['id'])) { //if the submit button is clicked
$stmt = $conn->prepare('UPDATE name, email, age SET name = ?, email = ?, age = ? WHERE id=?');
$stmt->bind_param('ssii', $_POST['name'], $_POST['email'], $_POST['age'], $_GET['id']);
$stmt->execute();
echo "Updated successfully"; // Updated Successfully
}

First SQL Database not working

I am working on a personal project of mine and I am accepting a name and email so I created a database called:
emailtemp with columns of "name" and "email"
PHPMyAdmin Page
HTML Form:
<form method="post" action="connect.php" class="contact100-form validate-form">
<div class="wrap-input100 m-b-10 validate-input" data-validate = "Name is required">
<input class="s2-txt1 placeholder0 input100" type="text" name="username" placeholder="Your Name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 m-b-20 validate-input" data-validate = "Email is required: ex#abc.xyz">
<input class="s2-txt1 placeholder0 input100" type="text" name="emailAddress" placeholder="Email Address">
<span class="focus-input100"></span>
</div>
<div class="w-full">
<button class="flex-c-m s2-txt2 size4 bg1 bor1 hov1 trans-04">
Subscribe
</button>
</div>
</form>
PHP File:
<?php
$connect = mysqli_connect("mysql.*****.net","*****","****>","emailtemp");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO posts (customerName, customerEmail)
VALUES ('$_POST[username]', '$_POST[emailAddress]')";
?>
Based off everything I read and looked at it it should work but after I click "subscribe" it pulls up connect.php and says "is currently unable to handle this request.
HTTP ERROR 500"
Is there a way to have this process in the background and stay on the same page and just say successful?
http://php.net/manual/en/mysqli.prepare.php
$connect = mysqli_connect("mysql.*****.net","*****","****>","emailtemp");
if ($stmt = $mysqli_prepare($connect,"INSERT INTO posts (customerName, customerEmail) VALUES (?, ?)")) {
mysqli_stmt_bind_param($stmt, "ss", $_POST['username'],$_POST['emailAddress']);
mysqli_stmt_execute($stmt);
}
Looks like you're missing a ) at the end of your mysqli_query() call.
If your DB is really like this:
emailtemp with columns of "name" and "email"
.. then you should match those in your query:
mysqli_query($connect,"INSERT INTO emailtemp (name, email)
VALUES ('$_POST[username]', '$_POST[emailAddress]')");
Recommended to check for user/email first, if they're somehow empty that will throw an exception.
like this:
$username = $_POST[username];
$email = $_POST[emailAddress];
if ($username && $email) {
// stuff here
} else {
// other stuff here
}
You forgot to close the mysqli_query function with an ) and you forgot the brackets around username and emailAdress
mysqli_query($connect,"INSERT INTO posts (customerName, customerEmail)
VALUES ('$_POST[username]', '$_POST[emailAddress]')");
Also this code makes you vulnerable to an SQL injection
Users can inject other commands to the SQL server and they get executed with admin rights.
You can use PDO, a secure implementation of SQL in PHP (if used right of course)
In your example it would be:
$dbhost = "your-host";
$dbname = "your-db-name";
$dbusername = "your-username";
$dbpassword = "your-password";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$statement = $conn->prepare("INSERT INTO posts (customerName, customerEmail)
VALUES (:username, :emailAddress");
$statement->execute(array(
"username" => $_POST['username'],
"emailAdress" => $_POST['emailAdress']
));

Storing data entered when signing up

I need to create a sign up page that will store user name email passwords and put them in a database so that the user can then login and access a profile etc.
I have made a database database however nothing will go into it. I input one manually but anything I try to do from the webpage won't go to the database.
Code for the webpage: Signup is the page I want displayed and adduser is the code for adding the data to the database.
Signup:
<?php include '../view/header.php';
?>
<br>
<br>
<h1 class="light white-text text-lighten-3">Sign up!</h1>
<br>
<br>
<form class="form" id="signup" action="addUser.php" method="post">
<div class="form-group ">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Your Email">
</div>
<br>
<div class="form-group ">
<input id="user_name" type="text" class="validate" name="user_name"required="required">
<label for="user_name">User Name</label>
</div>
<br>
<div class="form-group col s6">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter a Password">
</div>
<br>
<br>
<button type="submit" class="orange btn btn-primary">Submit</button>
</form>
<?php
include '../view/footer.php';
AddUser:
<script src="../js/materialize.js" type="text/javascript"></script>
<script src="../js/materialize.min.js" type="text/javascript"></script>
<script src="../js/init.js" type="text/javascript"></script>
<?php
$server = "localhost";
$username = 'root';
$Password ="";
$database = 'commish';
$con = mysqli_connect($server, $username, $Password, $database);
$email = filter_input(INPUT_POST, 'email');
$user_name = filter_input(INPUT_POST, 'user_name');
$password = filter_input(INPUT_POST, 'password');
new_user( $user_name, $password,$email, $con);
function new_user($user_name, $password, $email,$con)
{
global $con;
$query = "INSERT into users (user_name, password, email) VALUES (:user_name, :password, :email)";
$statement = $con->prepare($query);
$statement->bindValue(":user_name", $user_name);
$statement->bindValue(":password", $password);
$statement->bindValue(":email", $email);
$statement->execute();
echo 'Successfully created new user';
}
There's no bindValue() method in mysqli, PDO has. So here are the two approaches to solve your problem:
1)mysqli method:
Use bind_param() method to bind variables to your prepared statement. So your new_user() function should be like this:
function new_user($user_name, $password, $email,$con){
$query = "INSERT into users (user_name, password, email) VALUES (?, ?, ?)";
$statement = $con->prepare($query);
$statement->bind_param("sss", $user_name, $password, $email);
if($statement->execute()){
echo 'Successfully created new user';
}else{
// query failed
}
}
NOTE: Since you're passing the connection handler $con to this function, there's no need to use global $con;. Plus Globals are evil.
2)PDO method:
Keep your new_user() function as it is and change this line
$con = mysqli_connect($server, $username, $Password, $database);
to
$con = new PDO("mysql:host=$server;dbname=$database",$username,$Password);
Sidenote: Never store password as a plain readable text, always perform salted password hashing on raw password before inserting it into the table.
There's no bindValue() method in mysqli, you should use bind_param()
new_user function :
function new_user ($user_name, $password, $email)
{
global $con;
$stmt = $con->prepare("INSERT into users (user_name, password, email) VALUES (?,?,?)";
$stmt->bind_param("sss", $user_name, $password, $email);
$stmt->execute();
$stmt_error = $stmt->error;
$stmt->close();
if ($stmt_error)
echo 'Error on create new user: '.$stmt_error;
else
echo 'Successfully created a new user';
}

Categories