Перейти к содержимому

Как сделать форму put php mysql

  • автор:

Запись в базу данных mysql на php через форму

Запись в базу данных mysql на php через форму

Рассмотрим на примере, как создать форму, с помощью которой мы будем делать запросы в базу данных mysql на языке php, используя PDO.

1. Создадим разметку html-формы

  Запись в БД через форму на php   

Форма отправляется методом POST и обрабатывается на текущей странице.

2. Создадим таблицу, в которую будем записывать данные

Можно выполнить через SQL в PhpMyAdmin или ручками.

CREATE TABLE `mytable` ( `id` int(20) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(255) CHARACTER SET utf32 NOT NULL, `text` text NOT NULL ) 

3. Подключимся к базе данных и напишем запрос для записи.

Подключимся к базе данных.

// Переменные с формы $name = $_POST['name']; $text = $_POST['text']; // Параметры для подключения $db_host = "localhost"; $db_user = "user"; // Логин БД $db_password = "123"; // Пароль БД $db_base = 'mybase'; // Имя БД $db_table = "mytable"; // Имя Таблицы БД try < // Подключение к базе данных $db = new PDO("mysql:host=$db_host;dbname=$db_base", $db_user, $db_password); // Устанавливаем корректную кодировку $db->exec("set names utf8"); > catch (PDOException $e) < // Если есть ошибка соединения, выводим её print "Ошибка!: " . $e->getMessage() . "
"; >

Кодировку установили, чтобы избежать лишних проблем (не обязательно).

Не забудьте заранее создать таблицу в базе данных с трёмя значениями (id, name, text), подробнее об этом читать здесь.

Далее напишем наш запрос для записи в базу данных и запишем его в переменную.

// Собираем данные для запроса $data = array( 'name' => $name, 'text' => $text ); // Подготавливаем SQL-запрос $query = $db->prepare("INSERT INTO $db_table (name, text) values (:name, :text)"); // Выполняем запрос с данными $query->execute($data); 

Здесь мы сначала все наши данные для записи записываем в переменную $data, затем подготавливаем запрос с плейсохледарами (переменные) и выполняем запрос передавая ему данные для заполнения из $data

Создадим небольшую проверку, чтобы знать, выполнился ли наш запрос или нет.

if ($result)

4. Подключение формы к запросу

Форму создали, к базе подключились и написали запрос, теперь нужно связать всё это.

Форма отправляется методом POST, поэтому мы можем сделать проверку на него, а именно на любое поле формы.

У нас передаются поля с именами «name» и «text», на них мы и сделаем проверку.

Вставим весь наш скрипт в эту проверку:

if (isset($_POST['name']) && isset($_POST['text']))< // Переменные с формы $name = $_POST['name']; $text = $_POST['text']; // Параметры для подключения $db_host = "localhost"; $db_user = "user"; // Логин БД $db_password = "123"; // Пароль БД $db_base = 'mybase'; // Имя БД $db_table = "mytable"; // Имя Таблицы БД try < // Подключение к базе данных $db = new PDO("mysql:host=$db_host;dbname=$db_base", $db_user, $db_password); // Устанавливаем корректную кодировку $db->exec("set names utf8"); // Собираем данные для запроса $data = array( 'name' => $name, 'text' => $text ); // Подготавливаем SQL-запрос $query = $db->prepare("INSERT INTO $db_table (name, text) values (:name, :text)"); // Выполняем запрос с данными $query->execute($data); // Запишим в переменую, что запрос отрабтал $result = true; > catch (PDOException $e) < // Если есть ошибка соединения или выполнения запроса, выводим её print "Ошибка!: " . $e->getMessage() . "
"; > if ($result) < echo "Успех. Информация занесена в базу данных"; >>

То есть, если существует значения «name» и «text» переданные методом POST, то выполняется подключение к БД и запись в таблицу.

How to Create a PHP Contact Form With MySQL & HTML5 Validation

php contact form

A PHP contact form allows users to communicate with website administrators. It allows them to send queries to the site owners about relevant services or features. Using the contact form, web administrators are able to manage their business emails. Once there is an active contact form available, it can generate queries. It easily gets connected with the database, thus providing complete record and details about the users who are willing to contact and send their queries to website administrators.

  1. Prerequisites
  2. Create the Contact Form HTML
  3. Configure the MySQL Database
  4. Create the PHP Contact Form Script
  5. Mail Method
  6. Form Captcha
  7. PHP Contact Form with Captcha
    1. Contact Form Captcha Validation
    2. Captcha Refresh

    Prerequisites

    To create a simple PHP contact form with MySQL, I assume that you have a PHP application installed on a web server. My setup is :

    To make sure that that I don’t get side-tracked by server level issues, I decided to host PHP application on Cloudways managed servers because the platform offers a powerful PHP optimized environment. In addition, I don’t have to deal with server management hassles and thus focus on the core idea of this tutorial.

    Host PHP Websites with Ease [Starts at $10 Credit]

    • Free Staging
    • Free backup
    • PHP 8.0
    • Unlimited Websites

    You can also try out Cloudways for free by signing up an account on the platform following this GIF:

    Create the Contact Form HTML

    Create the contact form HTML as shown below with validation and save it with .php extension. Value which will be written between the double quotes in attribute Name like name=”u_name” in input tags work as a variable name. These attributes will contain the data from the form that we will use to save in our database . There are two methods to send your form data to your PHP page: GET and POST. I will be using POST as it hides the user data and there is no limit to send data. If you don’t have the time to dive deep in technicalities, you can use online forms that are pre-designed according to professional form design standards.

    Note: For styling you can use your own CSS and also use Bootstrap Classes for better styling.

    !DOCTYPE html>     #loading-img < display:none; >.response_msg  

    Easy Contact Form With Ajax MySQL

    Configure the MySQL Database

    The next step is to setup and configure the MySQL database. For this, fire up the Cloudways Database manager and create a table ‘contact_form_info’, with the fields id , name , email , phone,comments .

    Next, create config.php that will be used to set up the connection between the PHP app and the database. Once the file has been created, open it and paste the following code in it:

    connect_error) < die("Connection failed: " . $conn->connect_error); > ?>

    Create the PHP Contact Form Script

    Now let’s create a file get_response.php and paste the following code in it:

    $yourName = $conn->real_escape_string($_POST['your_name']); $yourEmail = $conn->real_escape_string($_POST['your_email']); $yourPhone = $conn->real_escape_string($_POST['your_phone']); $comments = $conn->real_escape_string($_POST['comments']); $sql="INSERT INTO contact_form_info (name, email, phone, comments) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."', '".$comments."')"; if(!$result = $conn->query($sql))< die('There was an error running the query [' . $conn->error . ']'); > else < echo "Thank you! We will contact you soon"; >> else < echo "Please fill Name and Email"; >?>

    In this PHP code, I have used the POST method for submitting the contact form data to the server. I will use two PHP global methods, $_REQUEST and $_POST to retrieve and save the contact form data in the server local variable.

    The difference between these two is that $_REQUEST can retrieve data from both methods i.e. GET and POST. However, $_POST can only receive data from the POST method.

    Here is what the PHP contact form script looks in action:

    Mail Method

    I also create a file contact_mail.php for mail in which send your contact form data on your mail easily.

    [email protected]"; $mailHeaders = "From: " . $_POST["your_name"] . "\r\n"; if(mail($toEmail, $_POST["comments"], $_POST["your_phone"], $mailHeaders)) < echo"

    Contact Mail Sent.

    "; > else < echo"

    Problem in Sending Mail.

    "; > ?>

    You might also like: How to Send Email in PHP

    Form Captcha

    You can use Captcha code in a form to ensure that the form is submitted with manual intervention without using any tools.

    PHP Contact Form with Captcha

    To develop contact form with captcha, let’s start with the following HTML code. In this code, I will put a PHP file link into the image tag with the name of captcha.php.

     

    Contact Form Captcha Validation

    For Captcha field validation, you can paste the following code in tag. Using this code, you can set jQuery validation for captcha form validation.

    if(!$(«#captcha»).val())

    Captcha Refresh

    This simple jQuery script will refresh PHP captcha code, and recreate the image with the new code. This new image will be set as captcha image source.

    function refreshCaptcha()

    PHP Captcha Image

    PHP uses a function called PHP rand() to generate a random number. Using md5(), you can encrypt the number and split it into 6-character captcha code. The code is not only added to the PHP session but also added as a source of captcha image using PHP GD function.

    session_start(); $random_alpha = md5(rand()); $captcha_code = substr($random_alpha, 0, 6); $_SESSION["captcha_code"] = $captcha_code; $target_layer = imagecreatetruecolor(70,30); $captcha_background = imagecolorallocate($target_layer, 255, 160, 119); imagefill($target_layer,0,0,$captcha_background); $captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0); imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color); header("Content-type: image/jpeg"); imagejpeg($target_layer);

    Form Handler Library

    You can also perform captcha and form validation by using Form Handler library. Check the following example:

    use FormGuide\Handlx\FormHandler; $demo = new FormHandler(); $validator = $demo->getValidator(); $validator->fields(['name','email'])->areRequired()->maxLength(50); $validator->field('email')->isEmail(); $validator->field('message')->maxLength(6000) $demo->requireCaptcha();

    Final Words

    In this tutorial, I demonstrated creating a PHP contact form using HTML, AJAX, jQuery and MySQL. Here is a live demo of the PHP contact form code in action. I’ve also given a brief overview about captcha form, and why you must use it in contact form. The article not only demonstrates how to setup captcha in a contact form, but also defines how to setup its validation using the script tag. Furthermore, you can also use Form Handler library to integrate captcha validation within the form.

    Still, if you have some more questions regarding captcha integration in the contact form, or want to share some of your tips on the topic, feel free to write down your suggestions in the comments section below.

    Q. How do I code a contact form in PHP ?

    A: You’ll need to create an HTML form that POSTs your PHP script that will handle the form submission. Each of your form fields/inputs should have an appropriate name, such as email, as you will use these to reference PHP data.

    The PHP will need to capture the POST data (e.g., $_POST[‘email’]) and use the mail() function to send a message that includes the desired output in the message body.

    Q. Do you need PHP for the contact form ?

    A: Contact form in PHP is one piece of website that you will get to know as a web developer. This is commonplace for users of a website to start a conversation with a seller or author, company, and freelancer.

    Q. How do I create a contact us form in HTML and PHP ?

    A: You’ll need to create an HTML form that POSTs your PHP script that will handle the form submission. Each of your form fields/inputs should have an appropriate name, you can retrieve the value of a particular form field by passing its name to the $_POST superglobal array, and display each field value using echo() statement.

    Q. Are there any PHP frameworks or libraries that can simplify the process of building a custom contact form?

    A: Yes, there are many PHP frameworks and libraries to help you create custom contact forms. Popular options include Laravel, Symfony, Zend Framework (Laminas), Slim Framework, PHPMailer, and Swift Mailer.

    Q. What are some best practices for preventing spam submissions in the PHP and MySQL contact form?

    A: One of the best practices for preventing spam submissions in PHP and MySQL contact forms is to dynamically create random names for form fields. This approach makes it difficult for automated bots to target specific fields. Additionally, you can change the field names when the session expires to further enhance security.

    Share your opinion in the comment section. COMMENT NOW

    Share This Article

    Save EXTRA With the Hosting Pricing Calculator!

    Get a detailed cost comparison of the leading hosting providers for FREE. Find the optimum hosting solution that optimizes your savings.

    Ahmed Khan

    Ahmed was a PHP community expert at Cloudways — A Managed PHP Hosting Cloud Platform. He is a software engineer with extensive knowledge in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *