Inserting data into database using html forms - php

Okay, guys. I am new at php and other server side codes.
I am able to connect successfully to my server and database. I am able to use the Insert data code to insert data with values. However, when I enter the values into the code, those are the values that get sent to the table. How do I use HTML forms to use custom data entered into text areas to show up in my database table?
For example,
when I use VALUE ('jon', 'doe') it sends those values into the database instead of the text I enter into the text areas. How do I fix this to say, enter my actual name when I fill out a web form?
Basically, I am asking how I would use web forms to manipulate data into the database. I'm so confused

You are encouraged to use PDO (or at least mysqli) prepared statements from the first day. This way you can relatively safely insert data into your SQL statements. Please read the official manual. Be aware that PDO will emulate prepared statements by default. That can result in a security hole. Therefore you should request to switch of emulated prepared statements.
$options = [PDO::ATTR_EMULATE_PREPARES => false];
$pdoConnection = new PDO($dsn, $user, $password, $options);
You can then create prepared SQL statements like:
SELECT `id`, `value` FROM `myTable` WHERE `value` = ?;
As long as the driver supports real prepared statements, the "?" will not be substituted directly, data will be separately sent after the statement. This avoids SQL injection via encoding attacks.
Please read documentation, try things out and come back if you have concrete questions.

You can build a form on one page that sends input to another page. For example:
index.php:
<!DOCTYPE html>
<html>
<head></head>
<body>
<form method="POST" action="action.php">
<input type="text" name="message">
<input type="submit" value="Submit">
</form>
</body>
</html>
Your php/MySQL code would then exist in a page called action.php which would be located in the same directory as index.php.
action.php:
<?php
$message = $_POST['message'];
/*now you can use the $message variable in your MySQL code to insert
it into the database*/
?>
Please remember to used prepared statements and to bind your parameters in your MySQL code to prevent hacker attacks (like sql injection).
Let me know if that worked for you!

When creating a form in html you may define the following input:
<input type="text" name="my_input">
To access the content of this particular input, after submission of the form. Use depending on what method your form is using $_GET['my_input'] or $_POST['my_input'] to retrieve the value entered in the form input.
Try to play arround with this example:
<form action="" method="get">
<input type="text" name="field" value="<?php print $_GET['field']; ?>">
<input type="submit" name="s" value="Go!">
</form>
<?php
if (isset($_GET['s'])) {
print "value of the text field: ".$_GET['field'];
}

Related

PHP insert data into SQL Database Table produces blank row

I'm trying to insert data from the form created into the SQL Server Database Table that is connected through ODBC. After I submit the data it shows up as a blank row with only the ID that has a value. I am very new to PHP and got parts of code from tutorials. This is just a test project. Here's the code:
<html>
<header>
<title>
</title>
</header>
<body>
<form action="\INSERTCODE.php" method="POST">
<input type= "number" step="any" name="sepal_lengp" placeholder="Sepal Length">
<input type= "number" step="any" name="sepal_widthp" placeholder="Sepal Width">
<input type= "number" step="any" name="petal_lengp" placeholder="Petal Length">
<input type= "number" step="any" name="petal_widthp" placeholder="Petal Width">
<input type= "text" name="flower_type" placeholder="Flower Name">
<button type="submit" name="submit" >INPUT VALUES</button>
</form>
<?php
//display all results from table
include("C:\Users\Dshop\Desktop\php-7.3.3\Server1\connection.php");
$i=1;
$sql = "SELECT * FROM dbo.textcsv";
$result = odbc_exec( $connection, $sql );
while($all =odbc_result_all($result,$i) ){
echo $all;
}
?>
</body>
</html>
This part includes the form. The filename is index1.php.
<?php
include("C:\Users\Dshop\Desktop\php-7.3.3\Server1\connection.php");
$sepal_lengp = $_POST['sepal_lengp']??'';
$sepal_widthp = $_POST['sepal_widthp']??'';
$petal_lengp = $_POST['petal_lengp']??'';
$petal_widthp = $_POST['petal_widthp']??'';
$flower_typep = $_POST['flower_typep']??'';
$dbinsert = "INSERT INTO dbo.textcsv (sepal_leng, sepal_width, petal_leng, petal_width, flower_type) VALUES ('$sepal_lengp', '$sepal_widthp', '$petal_lengp', '$petal_widthp', '$flower_typep');";
odbc_exec( $connection, $dbinsert );
HEADER("Location: ../index1.php?=success");
This part inserts data into the database table, using $_POST to obtain the data from index1.php. This file is called INSERTCODE.php. $connection and connection.php is the file that includes the connection to ODBC.
For this test project I used the Iris dataset. I believe that I had to use ODBC and SQL Server instead of mysql. Sql server is the 2014 version, PHP is 7.33, using node.js to run the server. Help is greatly appreciated!
EDIT I found out that the $_POST isn't getting any values from the form. Any ideas?
EDIT 2 I've tried using $_REQUEST, checking var_dump, and did all that stuff, but I still got nothing. After going to https://www.w3schools.com/php7/php7_forms.asp for an example form, I found out that the example did not work either. Now i'm not sure if the problem is from the code, or from something like the php configuration. Need help, please help.
you're treating your variables as strings, by th look of your database you want them as floats. Try using floatval( ) (http://php.net/manual/en/function.floatval.php) on your variables to make sure they are in the write format, this will also go some way to sanitising them until you update this to prepare statements so you can safely bind the values and specify the type
After rephrasing my issue to "node.js not taking post data" I found the issue. Node.js needs extra steps to process POST data. So, because of this, my input was ignored by node.js and the INSERTDATA.php ran without any data to insert anything. Turns out the solution of the problem was to use something like the body-parser or the other solution from another question.
The solution I took was to uninstall node.js and use XAMPP instead. It was much easier to use.
Also could someone flag my question for duplicate?

$_POST Form advanced security

I wanted to ask how can i secure my form from hackers who try to edit the input name? I mean... What i am trying to ask is the following:
<form action="?page=forumpost&action=posttopic">
<input type="hidden" name="parrentID" value="1">
<input type="text" name="post_name">
<input type="submit">
</form>
You see that form? Lets say i open the inspect element option, and i decide to change the
<input name="">
When i click the submit button after i edit the input name, i get redirected to the other page ?page=forumpost&action=posttopic where my form is proceeded. Of course, i get a PHP error "Undefined index: post_name". The server is searching for post_name, instead of that, a blank name was send to the server which resulted that error. This is the code that throws error.
if($_GET['action'] === "posttopic"){
posttopic($_POST['parrentID'],$_POST['postname']);
}
function posttopic($parrentID,$postname){
// Form code here
}
How can i prevent this from happening? Of course, i am using prepared statements, htmlspecialchars(), stripslashes(), strip_tags(), and additionally checking the min/max length of the input. But that doesn't prevent the user from making my server throw error. I can disable the errors but i don't find that as a good solution. A few security tips about forms will be welcome. Also is there a way for the user to somehow hack my website trough playing with fake forms or something... ?
Just check that all values are set before processing the data.
if (isset($_GET['action'], $_POST['parrentID'], $_POST['postname']) && $_GET['action'] === "posttopic") {
posttopic($_POST['parrentID'], $_POST['postname']);
}
http://php.net/isset
Also, you mention using htmlspecialchars(), stripslashes(), strip_tags() - are you aware what these functions are doing? You risk mangling the data in ways you didn't intend to.
htmlspecialchars() should only be called on output and not input. Storing values in the database with that function will make it a nightmare to search. Store clean text in the database, and instead do echo htmlspecialchars($myValue); when printing text around the website.
stripslashes() is not needed if you are using a prepared statement (this function that "could help" if you are not using a prepared statement (alternative, escape the input)). Just keep your prepared statement and ditch this function.
strip_tags() strips HTML tags, which could be useful - depends on your approach, but if you're using htmlspecialchars() on your output (again, not input!), it's redundant.

PHP - Do I need to validate this simple form for security?

I'm building a small website where I'll be the only user (let say my credentials are "myuser" with the password "mypassword"). In the login page I have this simple form:
<form method="post">
<p>Username: <input type="text" name="usr"></p>
<p>Password: <input type="text" name="passwd"></p>
<p><input type="submit" value="Login"></p>
</form>
Is it safe to just validate the form like this?
// After checking if the request is POST...
if($_POST["usr"]=="myuser"&&$_POST["passwd"]=="mypassword") {
// Set the cookie and go to admin page...
} else {
// Show login error...
}
Or do I need to apply some security measure to the two $_POST variables (e.g. by filtering them with htmlspecialchars or something like that)? As you can see, the credentials are not saved in a database, and also these variables are never called anywhere else in the code, so I don't see any danger even if a malicious user attempts to hack the form with SQL Injection or XSS.
So, did I miss something? Is there any potential danger in leaving the code like that?
I think it is fine, you can add a hashe function & something to prevent a brute force attack to secure a little more. :)
(Sorry can't comment yet)
With php we can use mysql_real_scape_string(), this function have a parameter that modify a string deleting the special chars. This function returns a secure string, now we can execute this string into a SQL query.

How can I insert HTML label in databse using PHP

I'm facing problem in inserting HTML label to database and found no way to do so. My code is as under
<html>
<body>
<form name = "myForm" >
<label name = 'q1'>Question 01: what Jorge do according to the story</label>
</form>
<?php
require "connection.php";
$qst = $_POST['q1'];
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
?>
any help will be appreciated please.
You have a slew of problems here. First let's talk about the things that are actually preventing this from working.
First, you need to set the method property of the <form> element to POST to have the form perform a POST action upon submittal instead of the default GET action.
<form name="myForm" method="post">
Note, that it is usually considered good form to also specify the action property of the form, though in this case the default behavior of posting to the currnet URI just happens to work for you.
Second, you need to actually create an input field in the form. This is where the data that is posted is input:
<label for="q1">Question 01: what Jorge do according to the story?</label>
<input type="text" name="q1" />
Third, You need a submit button to actually make the form POST:
<input name="submit" type="submit" value="submit" />
Now, let's talk about the stuff that should be fixed that doesn't actually prevent this from working, but just represents good programming practice.
First, you should not be using mysql_* functions. They are deprecated. I would suggest mysqli or PDO as widely used alternatives.
Second, you have a significant vulnerability to SQL injection. You should NEVER use user input data without validating and sanitizing it. This means you should probably check to see if a value was even POSTed (not an empty string) before trying to do the insert and then you need to escape the value before using it in SQL, or better yet, learn how to use parametrized prepared statements which prevents the need for input escaping.
Third, I would recommend getting in the habit of putting your code logic at the beginning of your script (before HTML) output. In your case this means moving the logic where you read in the PST content and perform the database insert before the HTML. WHy? Because this allow you to do things like conditionally print out error messages if the user did not provide input or to otherwise change the page in response to the POST. This also help build a good habit in that, when you start doing more complex things in PHP, you might need to do things like redirect users from one page to another, or totally separate out the logic form the display into separate files. This is not possible with code stuck at the end of the HTML output.
$_POST variables do not correspond to label elements, they correspond to input elements. The key to your post array is the name of your input element.
<input type="text" name="mytext" />
After post will be $_POST['mytext']
However, you're vulnerable to SQL Injection. You should not be using mysql_query() but rather PDO or Mysqli with prepared statements, but if you insist on using it, escape it first with mysql_real_escape_string()
$qst = mysql_real_escape_string($_POST['q1']);
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
Fred made a good point in the comments though. This bit of code is going to execute the first time you load the page before the form is submitted and throw an error (or warning) because $_POST['q1'] doesn't exist yet. You'll want to make sure it does exist before doing things with it.
if(!empty($_POST['q1'])){
$qst = mysql_real_escape_string($_POST['q1']);
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
}
Further, you need to tell the form where to submit to and what method to use:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for = 'q1'>Question 01: what Jorge do according to the story</label>
<input type='text' name='q1' value='' />
</form>
BTW, label does not have a name attribute, it has a "for" attribute.
Also, <form> elements use "GET" by default and submit to the current page if an action is not set, so it's technically not necessary to even have the action set in this case, but it's good practice.
You need add input field for your form and change form sumbit method. By default it's "GET", so you can't have input value in $_POST.
Or you can get input value from $_GET.
<html>
<body>
<form name = "myForm" method="post">
<label for = 'inp'>Question 01: what Jorge do according to the story</label>
<input type="text" name="q1" id="inp" />
<input type="submit" value="Submit">
</form>
<?php
require "connection.php";
$qst = $_POST['q1'];
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
?>
And also you need to have sumbit input field to submit form or can sumbit it with js or on keyup enter key.
<input type="submit" value="Submit">

Make a SQL Form Post Data Correctly

I am new to the php & mysql scene, and am trying to input data from an html form into a sql database via php. In the long run I will want to input/modify/delete such data, so if you have any links/tutorials, etc, it would be much appreciated.
The HTML Code :
<body>
<form action="addcustomer.php" method="post">
<font size="3">
Name :
<input type="text" name="Name">
<input type="submit" value="Add Customer">
</font>
</form>
The PHP Code :
<?php
//Connecting to sql db.
$database = "my_database";
$username="user";
$password="password";
$tName="customers";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
//Sending form data to sql db.
INSERT INTO '$database'.'$tName' ('Name');
VALUES ('$_POST[Name]');
?>
CRUD (Create Read Update Delete ) is a common thing and you can find other good tutorials online.
You can check W3Schools tutorial. They Have everything you need under PHP Database section. Thanks.
Well first of all, I can suggest you reading about php and MySql. Second of all you have couple of issues here. The action post that performs on submit, puts everything in a form with a name tag in a superglobal $_POST. So you can't use this:
$database = "my_database";
$username="user";
$password="password";
$tName="customers";
As you don't have anything there. You only have one field in your html in a form with a name tag, which is this:
<input type="text" name="Name">
As I understand that this is what you are trying to achieve, to put inputs from the html form to the database.
Now in you PHP file you can read from the superglobal $_POST, like this:
$username=$_POST['Name']; //Notice that the `name=` here, is the exact name in your `html` input field
You can actually see what's inside $_POST by var dumping it: var_dump($_POST);
This is a start. See that everything is working and you getting all the relevant information from the form and then you can move to work on sending it to database.
Now for the database. You should not use mysql command instead use PDO or Mysqli.
You can find more info here on how to connect to database using PDO:
http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
and of course you can read the PHP: manual:
http://www.php.net/manual/en/intro.mysql.php

Categories