- How to connect an HTML form to a MySQL database in PHP
- Step 1: Set up XAMPP
- Step 2: Create an HTML form
- Step 3: Create a MySQL database
- Step 4: Create a PHP file
- Explanation
- Explanation
- Step 5: Create a connection
- Explanation
- HTML 5. Работа с Web SQL базой данных
- Соединение с базой данных.
- Выполнение запросов.
- Вставка данных.
- Работа с результатами запросов.
- Заключение.
- How to connect HTML Form to MySQL Database using PHP in 4 Minutes?
- Database
- HTML Form Code
- PHP Code (connect.php)
- Explaining connect.php
How to connect an HTML form to a MySQL database in PHP
Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.
This Answer outlines how to use PHP to connect an HTML form to a MySQL database. We’ll use XAMPP as the server software to create a database and run PHP.
We’ll use the below steps to create a connection:
- Set up XAMPP and configure a PHP development environment
- Create an HTML form
- Create a MySQL database
- Create a PHP file
- Create a connection
Step 1: Set up XAMPP
The method to configure a PHP development environment with XAMPP is shown here.
Step 2: Create an HTML form
This Answer explains what an HTML form is and how to create it.
Step 3: Create a MySQL database
In this step, we’ll create a simple MySQL database since our server is already running.
We’ll open the browser and type http://localhost/phpmyadmin/. This redirects us to the PHP admin page, where we can create and manage databases. Click on the New option in the menu panel on the left side. The image below demonstrates this:
On the next page, we’ll choose a name for our database and click on Create, as shown:
Next, we’ll create a table in the database. We’ll add a table name and choose the number of columns:
Once we click on Create, we’ll be redirected to the following page:
Here, we’ve to give details regarding the table. The columns correspond to our fields in the HTML form. We may also assign each column a data type, characters length, or special privileges such as the primary A unique identifier for each entry in a table. key. A sample table is as follows:
Once we’re done, we’ll click on Save. Our first table in the database is created.
Step 4: Create a PHP file
Now that we have our database and server ready, we’ll create the necessary files. We’ll begin by opening the folder directory containing XAMPP. We traditionally find this folder in Local Disk E or Local Disk C. For Linux users, this will be in the Computer/opt/lampp directory.
Within that folder, open another folder titled htdocs and create a folder in it. We can name it anything, but for this tutorial, we’ll name it educativeform . This new folder will contain our HTML and PHP files.
htdocs/educativeform|-> form.php|-> index.html
The following code snippet contains the HTML code for the form:
Note: If we click on the submit button, it will given an error since we haven’t yet connected it to the database.
Explanation
- Line 6: The method POST is the connection type to send the HTML form entries. The action attribute has the value form.php . This is the name of the PHP file in the working directory, and the form entries will be sent to this file upon submission.
- Lines 8–20: These are the form fields. The last input type is a button that submits the field values to the PHP file.
To confirm that our form is ready, we’ll type localhost/educativeform in the browser. This ensures that the server, MySQL, and Apache is running. Otherwise, we might get an error.
Next, we’ll create the PHP file. The sample code, along with the explanation, is given below:
if(isset($_POST['submit']))$fname = $_POST['fname'];$lname = $_POST['lname'];$email = $_POST['email'];>?>Explanation
- Line 2: We’ll use the $_POST as connection type to get HTML form entries.
- Lines 4–6: We define the fields here. The square brackets contain the values of the name attribute in the input labels of the HTML code.
Step 5: Create a connection
Finally, we’ll connect our HTML form to the database using PHP. The code below is an addition to the previous code snippet, as shown:
// getting all values from the HTML formif(isset($_POST['submit']))$fname = $_POST['fname'];$lname = $_POST['lname'];$email = $_POST['email'];>// database details$host = "localhost";$username = "root";$password = "";$dbname = "sampledb";// creating a connection$con = mysqli_connect($host, $username, $password, $dbname);// to ensure that the connection is madeif (!$con)die("Connection failed!" . mysqli_connect_error());>// using sql to create a data entry query$sql = "INSERT INTO contactform_entries (id, fname, lname, email) VALUES ('0', '$fname', '$lname', '$email')";// send query to the database to add values and confirm if successful$rs = mysqli_query($con, $sql);if($rs)echo "Entries added!";>// close connectionmysqli_close($con);?>Explanation
- Lines 10–14: We’ll specify the permissions of the database. This will allow us to add entries to the table.
- Line 17: We use mysqli_connect to create a connection.
- Lines 20–23: Here, we’ll confirm if the connection is made. If the connection has failed, we’ll get an error message.
- Line 26: We create an SQL query for insertion. Here we add the values that we received from the HTML form.
- Lines 29–33: We send the query to the database over the connection.
- Line 36: This line closes the connection once the entry is inserted.
If everything is running without errors, we should be able to add our HTML form details in the MySQL database.
Learn in-demand tech skills in half the time
HTML 5. Работа с Web SQL базой данных
В HTML 5 есть много новых возможностей, которые позволяют web разработчикам создавать более мощные и насыщенные приложения. К этим возможностям относятся и новые способы хранения данных на клиенте, такие как web storage(поддерживается в IE8) и web SQL database.
При этом если web storage ориентирован на хранение пар ключ-значение, то в случае с web SQL database у нас есть полноценный sqlite(во всех текущих реализациях применяется именно этот движок баз данных, что является проблемой при стандартизации).
Далее я расскажу, как работать с web SQL database. При этом примеры естественно будут на JavaScript. Кроме того, стоит отметить, что с поддержкой браузерами всего этого хозяйства дела обстоят, не очень хорошо, но всё постепенно меняется к лучшему и, скажем, в Opera 10.50 поддержка будет, а браузерах на движке WebKit она уже есть. Более подробно про то, какой браузер, что поддерживает можно узнать, пройдя по ссылке.
Соединение с базой данных.
Подсоединиться к базе данных очень просто:
db = openDatabase(«ToDo», «0.1», «A list of to do items.», 200000);
Данный код создаёт объект, представляющий БД, а если базы данных с таким именем не существует, то создаётся и она. При этом в аргументах указывается имя базы данных, версия, отображаемое имя и приблизительный размер. Кроме того важно отметить, что приблизительный размер не является ограничением. Реальный размер базы данных может изменяться.
Успешность подключения к БД можно оценить, проверив объект db на null:
Всегда предпринимайте данную проверку, даже если соединение с БД для данного пользователя уже производилось в прошлом, и было успешно. Могут измениться настройки безопасности, закончиться дисковое пространство (скажем, если пользователь использует смартфон) или фаза луны окажется неподходящей.
Выполнение запросов.
Для выполнения запросов к БД предварительно надо создать транзакцию, вызвав функцию database.transaction(). У неё один аргумент, а именно другая JavaScript функция, принимающая объект транзакции и предпринимающая запросы к базе данных.
- строка SQL запроса
- массив параметров запроса (параметры подставляются на место вопросительных знаков в SQL запросе)
- функция, вызываемая при успешном выполнении запроса
- функция, вызываемая в случае возникновения ошибки выполнения запроса
db.transaction(function(tx) tx.executeSql(«SELECT COUNT(*) FROM ToDo», [], function(result)<>, function(tx, error)<>);
>);Давайте теперь изменим код так, чтобы при невозможности выборки из таблицы «ToDo»(которой пока не существует), данная таблица создавалась.
db.transaction(function(tx) tx.executeSql(«SELECT COUNT(*) FROM ToDo», [], function (result) < alert('dsfsdf') >, function (tx, error) tx.executeSql(«CREATE TABLE ToDo (id REAL UNIQUE, label TEXT, timestamp REAL)», [], null, null);
>)>);Вставка данных.
Давайте вставим новую строку в таблицу «ToDo». Для знакомых с синтаксисом SQL пример, приведённый ниже, покажется очень знакомым:
db.transaction(function(tx) tx.executeSql(«INSERT INTO ToDo (label, timestamp) values(?, ?)», [«Купить iPad или HP Slate», new Date().getTime()], null, null);
>);Первый знак вопроса в SQL запросе заменяется на «Купить iPad или HP Slate», а второй на метку времени. В итоге выполнен будет примерно такой запрос:
INSERT INTO ToDo (label, timestamp) values («Купить iPad или HP Slate», 1265925077487)Работа с результатами запросов.
Результат выполнения запроса на выборку данных содержит набор строк, а каждая строка содержит значения столбцов таблицы для данной строки.
Вы можете получить доступ к какой-либо строке результата вызвав функцию result.rows.item(i), где i – индекс строки. Далее, для получения требуемого значения, нужно обратиться к конкретному столбцу по имени – result.rows.item(i)[ «label»].
Следующий пример выводит результат запроса к базе данных на страницу:
db.transaction(function(tx) tx.executeSql(«SELECT * FROM ToDo», [], function(tx, result) for(var i = 0; i < result.rows.length; i++) document.write('‘ + result.rows.item(i)[‘label’] + ‘
‘);
>>, null)>);Заключение.
Использование web SQL database предоставляет мощные возможности, но не стоит увлекаться. Если задачу можно решить с помощью web storage, лучше использовать его.
Вы можете найти дополнительную информацию по данной теме в соответствующем разделе сайта консорциуме w3c.
Также для web SQL database уже начали разрабатывать ORM библиотеки. Пример такой библиотеки тут.How to connect HTML Form to MySQL Database using PHP in 4 Minutes?
Want to know, How to connect HTML Form to MySQL Database with PHP. Here I have easy and Short steps to Insert Form data into a database.
Database
Now first, we need to create a MySQL database but if you don’t know how to create a database then check out How to create Database and Table in MySQL
Database Name = youtube
Table Name = account
Attribute = (id : int, username : varchar, password : varchar)HTML Form Code
Username :
Password :
In the above HTML code, we use action=»connect.php» that means we are sending data from our HTML form to connect.php.
PHP Code (connect.php)
else< $sql = "INSERT INTO account (username, password) values ('$username','$password')"; if ($conn->query($sql)) < echo "New record is inserted sucessfully"; >else< echo "Error: ". $sql ." ". $conn->error; > $conn->close(); > > else < echo "Password should not be empty"; die(); >> else < echo "Username should not be empty"; die(); >?>Explaining connect.php
Line 2, 3: Grab a Form data and store it in $username and $password .
4, 5: Check, whether this username and password are empty or not. If they are not empty then we can continue a process.
6-11: Making a database connection
13-15: Check, is their error while connecting the database. If yes then show that error message and exit. Otherwise, continue a process.
18, 19: SQL query, to insert data into a database table.
20, 21: If our insert query is executed, then give a message “New record is inserted successfully”
23-25: If the query fails to execute then show an error message.
At last, we close the database connection.
And this is how we connect HTML Form to MySQL Database using PHP.