Form to post into database table - php

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

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>

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.

mysqli prepared statement search form

Hello for a second time folks.
I asked a question recently about cleaning up some ugly code I had been cooking up and received the help I was asking for very quickly. Thanks for that!
original question thread is here: PHP - Search database and return results on the same page
I was quickly directed to use prepared statements in mysqli instead of what I had been doing to avoid SQL injections and such. I knew this advice would come my way, so it was no surprise. So I did some more digging and have re-written the original code accordingly. But now I have broken the form.
Anyone willing to take a look to see what I am missing? I am new at all of this and my searching on the internets has not helped me to debug this on my own.
<!DOCTYPE html>
<html>
<head>
<title>Client Search Results</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<form id="contact" action="" method="post">
<fieldset>
<h4>Search For Client</h4>
<input name="search" placeholder="Enter Name Here" type="text">
</fieldset>
<fieldset>
<button type="submit">Search</button>
</fieldset>
</form>
</div>
<div class='container'>
<form id='contact' action='edit.php' method='post'>
<fieldset>
<h4>Search Results</h4>
<select size="5" style="width:100%" name='id' >
<?php
// Include database communication info
include("../../comm/com.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Search
$search = "%{$_POST['search']}%";
$stmt = $db->prepare("SELECT client_id, firstname, lastname, city, state FROM client WHERE firstname LIKE ?");
$stmt->bind_param("s", $search);
$stmt->execute();
$stmt->store_result();
$numRows = $stmt->num_rows;
$stmt->bind_result($client_id, $firstname, $lastname, $city, $state);
if($result > 0) {
while ($stmt->fetch()) {
echo "<option value='$client_id'>$firstname $lastname - $city, $state</option>";
}
}
$stmt->close();
?>
</select>
</fieldset>
<fieldset>
<button type='submit' name='submit'>View Selection</button>
</fieldset>
</form>
<div>
</body>
</html>
After re-writing this code many times, and after receiving help from many different direction, this is the code that I settled on. Works like I want and seems to be solid.
<html>
<head>
<title>Client Search Results</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<form id="contact" action="" method="post">
<fieldset>
<h4>Search For Client</h4>
<input name="search" placeholder="Enter Name Here" type="text" autofocus>
</fieldset>
<fieldset>
<button type="submit">Search</button>
</fieldset>
</form>
</div>
<div class='container'>
<form id='contact' action='edit.php' method='post'>
<fieldset>
<h4>Search Results</h4>
<select size="5" style="width:100%" name='client_id' >
<?php
// Retrieve Search Term
if (isset($_POST['search'])) {
$search = "%{$_POST['search']}%";
}
// Include Connection Credentials
include("../../comm/com.php");
//Connection to Database
$link = mysqli_connect($servername, $username, $password, $dbname);
// Connection Error Check
if ($link->connect_errno) {
echo "Sorry, there seems to be a connection issue.";
exit;
}
// Prepared Statement For Database Search
if ($stmt = $link->prepare("SELECT client_id, firstname, lastname, city, state FROM client WHERE firstname LIKE ? OR lastname LIKE ?")) {
// Bind Search Variable
$stmt->bind_param('ss', $search, $search);
// Execute the Statement
$stmt->execute();
// Bind Variables to Prepared Statement
$stmt->bind_result($client_id, $firstname, $lastname, $city, $state);
// Fetch Values
while ($stmt->fetch()) {
// Display Results of Search
echo "<option value='$client_id'>$firstname $lastname - $city, $state</option>";
}
}
// Close Statment
$stmt->close();
// Disconnect from Database
mysqli_close($link);
?>
</select>
</fieldset>
<fieldset>
<button type='submit' name='submit'>View Selection</button>
</fieldset>
</form>
<div>
</body>
</html>

MYSQL ERROR when submitting form

Hi I'm having some problems when I'm trying to submit a form of mine, everything seems to look fine on my end but im not quite sure why it's still not working any help would be appreciated.
config.php
<?php
$servername = "localhost";
$username = "release";
$password = "";
$dbname = "release";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
submit.php
<?php
include('config.php');
$producers = $_POST['producers'];
$company = $_POST['company'];
$title = $_POST['title'];
if(!$producers or !$company or !$title) {
echo 'Please make sure to fill out all required feilds.';
} else {
// Insert into DB
$sql = "INSERT INTO release (id, producers, company, title)
VALUES ('null', '$producers', '$company', '$title')";
}
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}$con->close();
?>
index.php
<html>
<head>
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<style>
input[type="text"] {
height: 30px;
}
</style>
<title>RRP » Welcome!</title>
</head>
<body>
<div style="width: 1080px; margin-top: 50px;">
<h3>Welcome!</h3>
<h4>You can edit the basic release form info below. <br /> Once done hit the "Submit" button to carry on to the new form!</h4>
<div class="container">
<form class="contact-us form-horizontal" action="submit.php" method="post">
<div class="control-group">
<label class="control-label">Producers</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" class="input-xlarge" name="producers" placeholder="Producers(seperate by commas)">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Production Company</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-globe"></i></span>
<input type="text" class="input-xlarge" name="company" placeholder="Rolling Ridges Productions">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Title</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-pencil"></i></span>
<input type="text" class="input-xlarge" name="title" placeholder="Desperate Measures">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn">Cancel</button>
</div>
</div>
</form>
</body>
</html>
error
Error: INSERT INTO release (id, producers, company, title) VALUES ('null', 'lol', 'lol', 'lol')
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'release (id, producers, company, title) VALUES ('null', 'lol', 'lol', 'lol')' at line 1
Resolved: was as simple as adding ticks to release
release is a MySQL keyword, and should be enclosed in backticks: `release`
try to use backticks in table name if it is keyword release
$sql = "INSERT INTO `release` (id, producers, company, title)
VALUES ('null', '$producers', '$company', '$title')";
Also it is better to write your database in the following format
database name -> db_name eg db_release, and
table name -> tb_name eg tb_release
so as to avoid keywords errors
It seems to me that id should not be assigned the string value 'null'. Typically id columns are auto increment, in which case you should simply omit the column:
$sql = "INSERT INTO `release` (producers, company, title)
VALUES ('".addslashes($producers)."', '".addslashes($company)."', '".addslashes($title)."'";
The addslashes is to protect again SQL injection. You should also sanitize your inputs:
$producers = strval($_POST['producers']);
$company = strval($_POST['company']);
$title = strval($_POST['title']);

adding jquery dates to mysql

My form is capturing date from jquery date picker, the form works fine without the date picker but with it, it just gives this error:
Error: Unknown column '$time' in 'field list'
Below is my php & html code
<?php
//form submitted
if (isset($_POST['create'])) {
//require db details
require_once '../dblogin.php';
//set flag
$OK = false;
// create database connection
$conn = new mysqli ($host, $user, $password, $database) or die("Connection Failed");
// initialize prepared statement
$stmt = $conn->stmt_init();
// create SQL to insert task
$sql = 'INSERT INTO tasks (task_name, task_project_id, task_assignee_id, datepicker, task_created_by, task_schedule, task_duration, task_end_date, task_creation_date, task_notes, task_status)
VALUES(?, ?, ?, ?, '.$_SESSION['id'].', ?, ?, $time, NOW(), ?, ?)';
if ($stmt->prepare($sql)) {
// bind parameters and execute statement
$stmt->bind_param('siissss', $_POST['task_name'], $_POST['task_project_id'], $_POST['task_assignee_id'], $_POST['datepicker'], $_POST['task_duration'], $_POST['task_notes'], $_POST['task_status']);
// execute and get number of affected rows
$stmt->execute();
if ($stmt->affected_rows > 0) {
$OK = true;
}
}
// redirect if successful or display error
if ($OK) {
header('Location: task_confirmation.php');
exit;
} else {
$error = $stmt->error;
}
}
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8” />
<title>Create new task</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker({dateFormat: 'yy-mm-dd' });
});
</script>
<link rel="stylesheet" type="text/css" href="../allcss/style.css" />
</head>
<body>
<?php
require('../Login/includes/header.inc.php');
?>
<div id="content">
<?php if (isset($error)) {
echo "<p>Error: $error</p>";
} ?>
<form id="form1" method="post" action="">
<div id="add">
<p>
<label for="task_name"class="title">Task name:</label>
<input name="task_name" type="text" class="widebox" id="task_name">
</p>
<p>
<span class="title">Project: </span><select name="task_project_id" size "5">
<?php
require_once '../dblogin.php';
$conn = new mysqli ($host, $user, $password, $database) or die("Connection Failed");
$stmt2 = $conn->stmt_init();
//pulls project names for the select element//
$sql2 = 'select * from projects';
$stmt2->prepare($sql2);
$stmt2->execute();
$result = $stmt2->get_result();
while($resultRow = $result->fetch_array(MYSQLI_ASSOC))
{
var_dump($resultRow);
echo "<option value='".$resultRow[project_id]."'>".$resultRow[project_name]."</option>";
}
$result->close();
$stmt2->close();
?>
</select>
</p>
<p>
<span class="title">Assignee: </span><select name="task_assignee_id" size "5">
<?php
require_once '../dblogin.php';
$conn = new mysqli ($host, $user, $password, $database) or die("Connection Failed");
$stmt3 = $conn->stmt_init();
//pulls intern names for the select element//
$sql3 = "select * from users where user_role='INT'";
$stmt3->prepare($sql3);
$stmt3->execute();
$result = $stmt3->get_result();
while($resultRow = $result->fetch_array(MYSQLI_ASSOC))
{
var_dump($resultRow);
echo "<option value='".$resultRow[person_id]."'>".$resultRow[user_name]."</option>";
}
$result->close();
$stmt3->close();
?>
</select>
</p>
<p>
<label for="dates"class="title">Schedule for:</label>
<input name="datepicker" type="text" id="datepicker"/>
</p>
<p>
<span class="title">Duration: </span><select name="task_duration" size "1">
<option value="00:30:00">30 minutes</option>
<option value="01:00:00">1 hour</option>
<option value="01:30:00">1,5 hours</option>
</select>
</p>
<p>
<label for="task_notes"class="title">Additional notes:</label>
<input name="task_notes" type="text" class="widebox" id="task_notes">
</p>
<p>
<span class="title">task status: </span><select name="task_status" size "1">
<option value="Complete">Complete</option>
<option value="Incomplete">Incomplete</option>
</select>
</p>
<p class="submit">
<input type="submit" name="create" value="Create task" id="create">
</p>
</div>
</form>
</div>
<?php
require('../Login/includes/footer.inc.php');
?>
</body>
</html>
Could anyone help me solve this please
For some reason you are not using prepared statement for the $time value (and for $_SESSION['id'] as well).
It's either dangerous and being the very reason for the error you are getting.
$sql = 'INSERT INTO tasks (task_name, task_project_id, task_assignee_id,
datepicker, task_created_by, task_schedule, task_duration,
task_end_date, task_creation_date, task_notes, task_status)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?)';
if ($stmt->prepare($sql)) {
// bind parameters and execute statement
$stmt->bind_param('siisissss', $_POST['task_name'], $_POST['task_project_id'],
$_POST['task_assignee_id'], $_POST['datepicker'], $_SESSION['id'],
$_POST['task_duration'], $time, $_POST['task_notes'], $_POST['task_status']);
it should be, or something like that. You need to check placeholders, types string and corresponding values yourself.
You are using single quotes for your query. That way $time isn't expanded to the variable value. You should use double Quotes (") like this:
"INSERT INTO tasks (task_name, task_project_id, task_assignee_id, datepicker, task_created_by, task_schedule, task_duration, task_end_date, task_creation_date, task_notes, task_status)
VALUES(?, ?, ?, ?, ".$_SESSION['id'].", ?, ?, $time, NOW(), ?, ?)";
Also I think you should use a parameter for $_SESSION['id'] and $time, too, since everyting coming from the user can't really be trusted.

Categories