Make a SQL Form Post Data Correctly - php

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

Related

How to access php from html?

I am sorry if this is a repeating question, but I can't find anyone who might have the same question as me yet. I am new in html and php, and I am trying to learn more by practising, basically creating a registration form and keep all the data in the MySQL database, by using xampp. I have created a registration form and saved it as a .html file format, but how can I use php to send the user input from html to the MySQL database? I have seen a lot of examples on Google, but most of them are using php file format, for example instead of registration.html, they use registration.php. I really do appreciate your help. Thank you very much StackOverflow community members.
P/S: I use Visual Studio Code to do this
Step 1: write this code in your html file
in form action redirect it to the php file
<!DOCTYPE html>
<html>
<head>
<title>form</title>
</head>
<body>
<form method="post" action="st.php">
<input type="text" name="text">
<input type="submit" name="submit_btn">
</form>
</body>
</html>
Step 2 create st.php file and call the action
<?php
if(isset($_POST['submit_btn'])){
//your code
header('Location:yourHTMLFile.html?status=success');//redirect to your html with status
}
?>
An example to insert some data in to the MySQL database using PHP
1. Create a Index.php page in a new folder(“764”) created under public_html folder present in your home directory
To use a PHP script on your web page, you just need to end the file name with .php and make sure the permissions on the file are set correctly. Any files to be accessed by the web server must be publically readable, but none of your PHP files (nor the directory containing them) may be group or publically writable. Following are the commands you can use for setting the permissions in linux:
chmod 755 public_html
chmod 644 public_html/764/index.php
The PHP page will have two simple text boxes for the user to enter some data in to it. Label them to be Firstname and Lastname.
INDEX.PHP
<html>
<body>
<h1>A small example page to insert some data in to the MySQL database using PHP</h1>
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
<input type="submit" />
</form>
</body>
</html>
We also need to make sure that the form method attribute is “post” so as to access the data being entered in a reliable way in the next page being directed “insert.php” so that the data being entered in the textboxes can then be saved to the database in the “insert.php” page.
To connect to MySQL :-
Before you can access your MySQL database, you must contact the system administrators to request an account.
Once the administrators have notified you that your account has been created, you may connect using the following instructions.
Go to http://localhost/phpmyadmin and type your MySQL ID and password being given.
Now enter the new table name “nametable” , number of fields in that table as “2” and hit GO button.
Enter the field names to be “firstname” and “lastname” and keep the length attributes to be “20” for both the fields. The default type of VARCHAR is kept as it is.
After the table fields are being created, the following screen will be shown to you.
Now we need to make a connection to the MySQL database and then send this entered data from our textboxes. For that we create a new PHP page “insert.php” and use the following connection strings to the connection variable $con
After making a connection, a SQL query is being written to enter this data in to the MySQL database being created (“nametable”)
To tell the user that the data is being entered we set the echo to "1 record added"
INSERT.PHP
<html>
<body>
<?php
$con = mysql_connect("localhost","cis_id","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cis_id", $con);
$sql="INSERT INTO nametable (fname, lname)
VALUES
('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
Now type the index page URL in your browser and enter some data in to the textboxes. Submit the Query.
For browsing the data, you need to click on Database: cis_id on top of the page (http://localhost/phpmyadmin) to get to the database tables page. Then click on the browse button as shown below, beside the “nametable” which you have already created to browse through the entered data.
the data being entered in to the MySQL database table being created.
Here is the reference.
http://people.cs.ksu.edu/~hankley/d764/tut06/GopisettyPHP.html
Note: Please write questions in proper way and internet is everything to get whatever you want. Hope you will search first and when you are helpless, post question with piece of code. Then only we can help in this forum.

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?

Inserting data into database using html forms

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'];
}

Using field data stored in constants, in multiple PHP scripts

I'm building a database modifying gui that executes basic queries. The user have to input the name of existing database and table name at the start. I'm using fields to take user input and then parsing them to a php script. I was using session variables to use the database name and table name in different php files. Is there a way to do this using include or include_once? or any other method that serves better than session variables in this situation? Keeping in mind that the script will be using GET to grab the input in the fields.
Yes you can. You can have your php code create a php file (with the information about the database and table) which you can then include into whichever file you wish to use those variables in. First create the form that will be used for the input, something similar to the following:
index.php:
<form method="POST" action="phpscript.php">
<input type="text" name="databaseName">
<input type="text" name="tableName">
<input type="submit" name="Submit" value="Submit">
</form>
then create the php code in the page that the form takes you to that will create the new php file:
phpscript.php:
<?php
$myFile = fopen("info.php", "w");
$myStrig = "<?php $tableName = ".$_POST['tableName']."; $databaseName = ".$_POST['databaseName']."; ?>";
fwrite($myFile, $myString);
fclose($myFile);
?>
Now whichever file that you would like to have access to variables $tableName and $databaseName would just need the following line of code:
include('info.php');
Also keep in mind that I am assuming that all the files are in the same directory. If you have them in different directories, you'll have to change the paths to those files.
Let me know if that helps you!

Inserting data from form into table using php

I just finished installing Xampp and trying it out.
I wrote a php script to connect to my database like this :
$mysqli = new mysqli("localhost","root","","triology");
$mysqli->select_db("triology");
$table ="users";
Now I want to insert data into my database table from a form I have created using php but I am getting an error message from mysql:
Table triology.users' doesn't exist.
Even though I have created the table in phpmyadmin.
The code to insert into my table is :
$mysql = "INSERT INTO $table VALUES('$_POST[firstname]','$_POST[lastname]')";
and my form code is:
<form action="index.php" method="post"/>
FirstName<input type="text" size="25">
LastName<input type="text" size="25"/>
<input type="submit" value="Submit" />
Please don't worry about sql injection as I am just trying it out.
The error message you get is pretty clear about your problem. When you see this message, you either misspelled table name when creating or your table is not there or the table is in a different database.
Also another thing after you initiate the connection with mysqli, you do not need the select database again with $mysqli->select_db("triology"); because you are already selecting your database when you create the connection with new mysqli("localhost","root","","triology");
i am not sure but i might cause duplication in your path and cause the problem.

Categories