html form radio buttons not saving string to database - php

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>

Related

PHP - Session variables with prepared statements and parameterized queries

I tried to write a registration form. On submition it suppose to:
Get the data from the inputs to the sql database - as a row in the table.
Add the users email address as a session variable.
Redirects them to a second page.
It all happens, but it adds two identical rows instead of one.
I'll appreciate any answer you can give me that will explain why my script adds the same row twice into the database.
PHP:
<?php
ob_start();
session_start();
if($_POST) {
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$error = "";
$link = mysqli_connect("xx", "xx", "xx", "xx");
if (mysqli_connect_error()) {
die("the connection was failed");
}
if ($email || $password || $name) {
$stmt = $link->prepare("INSERT INTO `Family` (email, password, name) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $email, $password, $name);
$stmt->execute();
if($stmt->execute()) {
$_SESSION['email'] = $email;
header("Location: session.php");
$stmt->close();
} else {
echo "it failed";
}
}
}
HTML:
<html>
<head>
</head>
<body>
<h1>Registration Form</h1>
<form method="post">
<p>Email:</p>
<input type="email" name="email">
<p>Password:</p>
<input type="password" name="password">
<p>Name:</p>
<input type="text" name="name">
<br><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>

SQL - Insert form into a database

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.

Can't insert new records through PHP into mysql database

When I press the submit button I get error.
object not found error.
And the page automatically adds empty entries with auto incremented primary key (without pressing the submit button).
I am still a beginner in PHP, I searched thoroughly but I can't find out what's wrong in code.
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="Name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="Code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="GPA" id="GPA">
</p>
<input type="submit" value="Submit">
</form>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "username", "password", "students");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
// attempt insert query execution
$sql = "INSERT INTO info VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
</body>
</html>
Try this:
$full_name = filter_input(INPUT_POST, 'Name');
$code = filter_input(INPUT_POST, 'Code');
$gpa = filter_input(INPUT_POST, 'GPA');
The reason why I wrote that is because your input names contain Name, Code and GPA so you need to write this exactly as your input names (case-sensitive).
Do with isset(). when the submit button clicks only the code runs.
Inside the php you should use the form input name field.
<?php
if(isset($_POST['submit'])){
$link = mysqli_connect("localhost", "username", "password", "students");
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
//to prevent sql injection attack
$full_name = mysqli_real_escape_string($link, $full_name);
$code = mysqli_real_escape_string($link, $code);
$gpa = mysqli_real_escape_string($link, $gpa);
// attempt insert query execution
$sql = "INSERT INTO info (Name,Code,GPA) VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
?>
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="full_name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="gpa" id="GPA">
</p>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
The problem is the input name. You named Full Name input with name="Name", but you declare $full_name = filter_input(INPUT_POST, 'full_name'); in php section. you must change full_name to Name. As well as the Code and GPA input.

PHP/MySQL Creates Blank Record In Database

I have a user input form(HTML) that is supposed to take the information and insert it into a MySQL database via PHP. The PHP apparently executes and echoes "Your registration has completed successfully". A record is created in the database but the columns are blank(I have removed my server, database, and password from the PHP code).
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>User Portal</title>
</head>
<div class="inputContainer">
<header>
User Information Portal
</header>
<form action="php/userPost.php" method="post">
<label for=firstName">First Name</label>
<input type="text" id=firstName" name="fname">
<br><br>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lname">
<br><br>
<label for="eMail">Email</label>
<input type="text" id="eMail" name="email">
<br><br>
<label class="labelRole" for="userRole">Role -</label><br>
<input type="radio" id="userRole" name="role" value="Instructor"> Instructor
<input class="submitButton" type="submit" name="submit" value="Register">
</form>
</div>
</body>
PHP:
<?php
$sname = "server-name";
$uname = "username";
$pword = "password";
$dbname = "web_tech_test";
$conn = new mysqli($sname, $uname, $pword, $dbname);
if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
$sql = "INSERT INTO users (first_name, last_name, email, role)
VALUES ('$fname', '$lname', '$email', '$role')";
if ($conn->query($sql) === TRUE) {
echo "Your registration has completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This creates a new record in the DB but all the columns are blank. Any ideas why this may be happening?
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
this code returns a boolean, not a string value...
Use !empty() just for validation
example
if(empty($_POST['eMail'])) {
die("Email cannot be empty");
}
You're confusing the id and the name tags on the inputs.
The name tags are the ones which will be submitted as keys to your server.
Try this in your server php script after submitting your form to see which key/values are actually received by the server:
var_dump($_POST);
Also, if you want to check that all fields have been filled out, use something similar as this:
if (empty($_POST['firstName'])) {
die("firstname is empty!");
}
In your current example you're actually saving a boolean to your variables.
And, last but not least, never insert variables from a potentially unsafe source (like a user input) directly into your SQL. Use pdo: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers for this
Full code example to get you started:
//prepare your values
if (empty($_POST['fname']) || empty($_POST['lname']|| empty($_POST['email']|| !isset($_POST['role'])) {
die ("some values were empty or not set");
}
//prepare your database
$db = new PDO('mysql:host=server-name;dbname=web_tech_test;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //throw an exception if there is an error
//create your query
$stmt = $db->prepare("INSERT INTO users (first_name, last_name, email, role) VALUES (:first_name,:last_name,:email,:role)"); //create a query statement
$stmt->bindValue(":first_name", $firstName); //put your values into your statement
$stmt->bindValue(":last_name", $lastName);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":role", $role);
if ($stmt->execute()) { //execute the query
echo "Your registration has completed successfully";
} else {
echo "Error :(";
}

how to fetch data from mysql and write it to innerhtml of a div in PHP

Apologies for the newbie question, I just started with PHP, trying to fetch data when the user writes ID, and get info from database and write it into innerhtml of div's inside the form. How can I do it? thanks.
<form action="read.php" method="post">
Bring Data of ID <input type="text" name="id" />
<br/>
<input type="submit" />
<br/>
<div id="username" style="font-weight:bold;" /></div>
<br/>
<div id="email" style="font-weight:bold;" /></div>
<br/>
<div id="password" style="font-weight:bold;" /></div>
</form>
<?php
$db_username = "root";
$db_password = "";
$con = new PDO('mysql:host=localhost;dbname=test', $db_username, $db_password);
if (!$con) {
echo "error";
}
else {
echo "connected";
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
}
else {
die("Die hacker!");
}
In your read.html, append your html code at the end:
<?php
[...]
$query = $con->prepare(" SELECT * FROM bucky (username, email, password) WHERE id=:id ");
$query->execute(array(
':id' => $_POST['id']
));
$result = $sth->fetchAll();
}
else {
die("Die hacker!"); // seriously?
}
?><html><body><?php
print_r($result); ?>
</body></html>
This will print you the result of your query.
You can also iterate over the result, but i think you should really just read the documentation on PDO and how to use it. Maybe a simple introduction to PHP as well. This is a VERY basic Question.

Categories