How to write an HTML dropdown menu data to MySQL database? - php

I am trying to write an HTML dropdown data onto the MySQL database.
I have the following HTML form:
<body>
<form method="post" action="test.php">
<h3>Name:</h3>
<input type="text" name="Name">
<h3>Choose an Interest</h3>
<select name="Interests" style="width: 400px !important; min-width: 400px; max-width: 400px;">
<option value="">Choose an option</option>
<option value="kings">Adroring Kings</option>
<option value="europe">Travelling Across Europe</option>
<option value="poland">Poland's Work of Art</option>
</select>
<input type="submit" name="Submit" id="Submit" value="Submit">
</form>
</body>
And the following PHP file to connect to my database:
<?php
// database connection code
// $con = mysqli_connect('localhost', 'database_user', 'database_password','database');
$con = mysqli_connect('localhost', 'root', '','test');
// get the post records
$name = $_POST['Name'];
$interests= $_POST['Interests'];
// database insert SQL code
$sql = "INSERT INTO `test_data` (`Name`, `Interests`) VALUES ('$name', '$interests')";
// insert in database
$rs = mysqli_query($con, $sql);
if($rs){
echo "Contact Records Inserted";
}
?>
My SQL is connected and working fine when I just enter a name. However, when I select an option from the dropdown box, the data I enter does not get through to the database anymore.
My database:

To store the selected values in the database using PHP you have to perform the tasks described below. I would strongly encourage to use PDO whenever possible rather than mysqli. I will show how to use both.
1. Read the submitted data
When a user submits a form the values will be populated in super global arrays. If your HTML form is set to POST method then the values will be present in $_POST. However, you should always make sure that the values were actually submitted when the script runs. You can check that using isset() function.
// method 1
if(isset($_POST['Name'], $_POST['Interests'])) {
// your code
}
2. Establish a connection to the database
Each time the script needs to perform some operations in the database it must have an open connection. This step is important to ensure that the data can be properly transferred. You must always ensure 3 things: enable error reporting, open connection, and set the correct charset.
Using PDO:
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'pass', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
Using mysqli:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$mysqli->set_charset('utf8mb4');
3. Execute prepared statement
Whenever you need to perform an operation you should always use prepared statements. The huge advantage of prepared statements is that they send the data separately from the command and the two can't mix accidently.
Using PDO:
$stmt = $pdo->prepare('INSERT INTO `test_data` (`Name`, `Interests`) VALUES (?, ?)');
$stmt->execute([
$_POST['Name'],
$_POST['Interests']
]);
Using mysqli:
$stmt = $mysqli->prepare('INSERT INTO `test_data` (`Name`, `Interests`) VALUES (?, ?)');
$stmt->bind_param('ss', $_POST['Name'], $_POST['Interests']);
$stmt->execute();
That is all that is needed to insert simple data into a MySQL table.

Related

Info does not submit into database

We have an assignment for school and I've tried to build the application, however some text that I want to have inserted into a database doesn't get submitted.
I've tried different things, but the page does not show an error either.
This is the code of my insert page
<head>
</head>
<body>
<form action="index.php" method="post">
ID: <input type="text" name="id"><br/>
Server: <input type="text" name="Server"><br/>
Student: <input type="text" name="Student"><br/>
Docent: <input type="text" name="Docent"><br/>
Project: <input type="text" name="Project"><br/>
Startdatum: <input type="text" name="Startdatum"><br/>
Einddatum: <input type="text" name="Einddatum"><br/>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$con = mysqli_connect("localhost", "root", "usbw", "serverruimte");
if(!$con) {
die(mysqli_connect_error());
}
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
$result = mysqli_query($con, $sql);
if($result) {
echo "Opslaan voltooid!";
} else {
echo mysqli_error($con);
}
mysqli_close($con);
}
?>
</body>
</html>
Basically, what happens is: https://i.imgur.com/aUOx5yj.mp4
Does anyone know what the problem is and why the inserted data does not show up on the index page? The data does show on the page when I submit it directly into the MYSQL database.
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!
When working with MySQLi you should enable automatic error reporting instead of checking for errors manually. Checking for errors manually is a terrible practice, very error prone and should be avoided at all costs. Let MySQLi throw exceptions and do not catch them. See How to get the error message in MySQLi?
When opening MySQLi connection you must specify the correct charset. The recommended one is utf8mb4.
if (isset($_POST['submit'])) {
// Enable automatic error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create new instance of MySQLi class
$con = new mysqli("localhost", "root", "usbw", "serverruimte");
// Set correct charset. Important!
$con->set_charset('utf8mb4');
$stmt = $con->prepare('INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES (?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss', $_POST['id'], $_POST['Server'], $_POST['Student'], $_POST['Docent'], $_POST['Project'], $_POST['startdatum'], $_POST['einddatum']);
$stmt->execute();
echo "Opslaan voltooid!";
mysqli_close($con);
}
Change this line:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
to:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('".$_POST['id']."','".$_POST['Server']."','".$_POST[Student]."','".$_POST['Docent']."','".$_POST['Project']."','".$_POST['Startdatum']."','".$_POST['Einddatum']."')";
Reason behind this change is because your query is wrong for the following reasons:
You were using strings instead of concatenating your real values coming from $_POST
Some of your indexes in $_POST were misspelled. For example:
$_POST[einddatum] should be $_POST['Einddatum']
Also, consider that this code is vulnerable to SQL Injection

adding new mySQL table row with PHP doesn't work

I got a little form:
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen">
</form>
As you can see there is the action="save.php" and method="post" on the text-input there is name="plannername".
And thats my php:
$con = mysql_connect("myHost","myUser","myPW");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB", $con);
$sql="INSERT INTO anmeldungen (FR_PM)
VALUES ('$_POST[plannername]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
The FR_PM is one column of my table. But when I press submit, not even a new row gets created. Nothing happens.
But when I call my php with "mywebsite.com/save.php" it adds a new row in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
one of the things that you need to learn if you are a beginner, you should try by all means to stay away from using mysql_* function this is depreciated and its no longer supported in php. instead use mysqli_* with prepared statements, or use PDO prepared statements.
prepared statments make you code looks clean and its easy to debug.
this is you example with prepared statements.
<form id="plannerform" action="save.php" method="post">
<input id="plannername" placeholder=" " type="text" autocomplete="off" name="plannername">
<input id="plannersubmit" type="submit" value="eintragen" name="submit">
</form>
save.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// 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'])) {
if (empty($_POST['plannername'])) {
die("Enter plannername");
} else {
// prepare and bind
$stmt = $conn->prepare("INSERT INTO anmeldungen (FR_PM) VALUES (?)");
$stmt->bind_param("s", $_POST['plannername']);
if ($stmt->execute()) {
echo "New records created successfully";
} else {
echo "Could not insert record";
}
$stmt->close();
}
}
?>
The reason I used prepared statements :
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
But when I call my php with "mywebsite.com/save.php" it adds a new row
in my table (with no value at "FR_PM", what's pretty obvious)
What do I do wrong?
Well do prevent that from happening you need to check if the form was submitted before you can actual process any thing.
Note: If we want to insert any data from external sources (like user input from a form ), it is very important that the data is sanitized
and validated. always treat input from a form as if its from a very
dangerous hacker
change your insert query:
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$_POST["plannername"]."')";
Or
$plannername = $_POST["plannername"];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('".$plannername."')";
Also, use "name"= and not "id"= in the HTML form.
This is usually misleading when working with forms and HTTP POST method.
you may try
$value = $_POST['plannername'];
$sql="INSERT INTO anmeldungen (FR_PM) VALUES ('{$value}')";

PHP code for a HTML form sending data to a MySQL database?

I have this form:
<form action="contactus.php" method="post">
<select name="formTitle">
<option value="">Select...</option>
<option value="M">Mr</option>
<option value="F">Mrs</option>
</select>
<p><b>Name</b></p>
<input type="text" name="formName" maxlength="50"/>
<p><b>Enquiry</b></p>
<input type="text" name="formEnquiry" maxlength="500"/>
</select>
<p><input type="submit" name="formSubmit" value="Submit"/></p>
And I have a MySQL database (called 'contacts') with a table (called 'enquiries') with three columns; 'Title', 'Name', 'Enquiry'.
The database has no password or anything. It's just a localhost with a 'root' password.
What kind of PHP would I need to send the data from this HTML form to the MySQL database?
I can help you in this problem.
So, just add the following code to your php file contactus.php.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "contacts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['formSubmit'])) {
$formTitle = $_POST['formTitle'];
$formName = $_POST['formName'];
$formEnquiry = $_POST['formEnquiry'];
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES ('$formTitle', '$formName', '$formEnquiry')";
$conn->query($sql);
?>
I hope this will solve your problem.
SIMPLE ANSWER: MySQL
A LITTLE BIT MORE DEVELOPED ANSWER:
MySQL is in basic terms the combination of PHP and SQL to create an easy way to do various actions to a database, which include:
Create table
Query table
Update table
and much more
There are variations of MySQL, including MySQLi and MySQL (PDO).
an example of connecting to your database via MySQL (PDO) would be:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$myDB = "databasename";
try {
$conn = new PDO("mysql:host=$servername;dbname=$myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
//insert code there that you want to execute...
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
you mentioned that you don't have a password, so you might just leave the "password" slot empty ("") I suppose, though this is very insecure and I recommend you place a password.
In the code above, there is a comment that says:
//insert code there that you want to execute...
Here you would include code that would probably do actions similar to the ones mentioned above (query table, update table, etc). An example of code similar to that would be:
//htmlspecialchars takes out special characters that might
//exist in the posted information if someone were trying
//to hack your site via sql injection
$formTitle = htmlspecialchars($_POST['formTitle']);
$formName = htmlspecialchars($_POST['formName']);
$formEnquiry = htmlspecialchars($_POST['formEnquiry']);
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES (formTitleBinded, formNameBinded, formEnquiryBinded)";
$sqlPrepared = $conn->prepare($sql);
$sqlPrepared->bindParam(':formTitleBinded',$formTitle);
$sqlPrepared->bindParam(':formNameBinded',$formName);
$sqlPrepared->bindParam('formEnquiryBinded',$formEnquiry);
$sqlPrepared->execute();
The previous code both sanitizes your input and inserts a row into your table with that information.
Let me know if that helped!
EDITED: My answer has been edited with parameter binding included to prevent SQL Injection.

Pushing a comment to my database on localhost

So, I'm trying to push a comment to my database (icposts, below), and I'm not getting any results. I can pull and display the comments I directly insert into the database table fine, but when I try to send a comment from the html form, it doesn't seem to work at all.
<?php
$connect=mysqli_connect("localhost","root","");
$database=mysqli_select_db("icposts");
$username=$_POST['poster'];
$title=$_POST['postTitle'];
$body=$_POST['postText'];
$date=$_POST['currentDate'];
$submit=$_POST['submit'];
if($submit)
{
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
}
?>
Here's the form's html, for reference:
<form name="input" action="comments.php" method="POST">
Username: <input id = "poster" type="text" name="poster"value="Guest" /><br>
Tite: <input id = "postTitle" type="text" name="postTitle" /><br>
Comment: <br> <textarea id = "postText" name = "postText"rows="4" cols="50"></textarea>
<input id = "submit" name = "submit" type="submit" value="Submit" />
<input id = "currentDate" name = "currentDate" type = "hidden" value = "" />
</form>
I've been looking at various examples, and I don't see anything wrong with what I've got there, when I compare it to what other people have posted online.
First, you need to pass connection to $database=mysqli_select_db("icposts");.
Then you're starting to mix MySQL APIs with mysql_query. They just don't intermix.
$database=mysqli_select_db($connect,"icposts");
then you're using the wrong identifiers for your table and columns, being quotes.
Either use ticks, or remove them (quotes) and also pass connection to the query:
$query=mysqli_query($connect,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
Also add or die(mysqli_error($connection)) to mysqli_query() to check for DB errors, which is the reason why you are not getting errors; you're not checking for them. Error reporting is another you should look into.
Example:
if (!mysqli_query($connection,"INSERT INTO `posts` (`id`, `username`, `title`, `body`, `date`)
VALUES ('','$username','$title','$body','$date')");
)
{
echo("Error description: " . mysqli_error($connection));
}
else{
echo "Success!";
}
You can also use all 4 parameters instead:
$connect=mysqli_connect("localhost", "root", "", "icposts");
You may also want to replace if($submit) with
if(isset($_POST['submit']))
You can then get rid of $submit=$_POST['submit'];. It's best to use isset().
Nota: You will need to make sure that your currentDate column allows for blank data, otherwise you will need to give it some form of value.
Another note about the "id" column. If it is an auto_increment, you can just omit it from the query.
The database will increase on its own.
Sidenote:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
In the meantime till you get into using prepared statements, change your code using:
$username = stripslashes($_POST['poster']);
$username = mysqli_real_escape_string($connection, $_POST['poster']);
and do the same for all your variables.
Here is a prepared statements primer:
<?php
$link = new mysqli('localhost', 'root', '', 'database');
if ($link->connect_errno) {
throw new Exception($link->connect_error, $link->connect_errno);
}
// Check that the expected value has been provided via a POST request
if (!isset($_POST['input1'])) {
throw new Exception('Missing POST request parameter [input1]');
}
// now prepare an INSERT statement
if (!$stmt = $link->prepare('INSERT INTO `your_table` (`name`) VALUES (?)')) {
throw new Exception($link->error, $link->errno);
}
// bind parameters
$stmt->bind_param('s', $_POST['input1']);
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$connect=mysqli_connect("localhost","root","");
Should be (the select db can simply be removed)
$connect=mysqli_connect("localhost","root","", "icposts");
And
$query=mysql_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')");
Should be
$query=mysqli_query("INSERT INTO 'posts'('id', 'username', 'title', 'body', 'date') VALUES ('','$username','$title','$body','$date')", $database);
Please do keep in mind that this is a really bad aprouch, also looking at your query it seems like the id is an auto incremented column. If that's the case, you don't even have to write it in the query itself.
You might wanna look further into Parameterizing queries.
This is a nice post for that.
How can I prevent SQL injection in PHP?

php code working incorrectly and not querying database

I'm using php and a database to add books to a database.
HTML
<form method="POST" action="addbook.php">
<p>Enter Book title :<input type="text" name="bookname"></p>
<p>Enter Book Author :<input type="text" name="bookauthor"></p>
<p><input type="submit" value="addbook"></p>
</form>
PHP
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbcon = mysqli_connect('localhost','root','password','bookstore') or die('asd');
$dbquery = "INSERT INTO books (title,author) VALUES ($bname,$bauthor)";
mysqli_query($dbcon,$dbquery) or die('not queryed');
echo "Your book has been added to your online library";
I'm getting the reply ' not queryed'
try putting single quotes around the values
ie
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
You should be using PDO and prepared statements in order to prevent SQL injection. The resultant PHP would be something like this:
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); //Fill in these variables with the correct values ('localhost' for host, for example)
$st = $dbh->prepare("INSERT INTO books (title,author) VALUES (?,?)");
$data = array($bname, $bauthor);
$st->execute($data);
You can then add logic to check if the statement executed successfully.
Also, I think you just gave us your root password?
For more information about PDO, see this tutorial.
Check the Column names in the table,whether they match with the one in the query.also check whether they are varchar itself.
I dont find any problem in the query, and also try putting
or die(mysqli_error());
and tell what exactly you can see.
If the type is varchar , you have to use single quotes around the values.
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";

Categories