This topic is locked

Insert data from a form

1/19/2021 4:21:54 PM
PHPRunner General questions
P
PaulM author

This is probably pretty straight forward but can anybody tell me how to add data from a form that I'll create in wordpress to the database?
I want people to be able to fill in a form online to register with their name and address and then for those details to be added to a table in the database.

S
salus1DevClub member 1/19/2021

Where does the form currently POST the name and address information to?

P
PaulM author 1/19/2021



Where does the form currently POST the name and address information to?


I haven't made the form yet but normally it would be to an email

S
salus1DevClub member 1/19/2021

Submitting to e-mail not ideal, can be done but involves adding e-mail parsing logic.
Might be better to use the approach outlined at...
https://www.codeandcourse.com/how-to-connect-html-form-to-mysql-database/

Admin 1/20/2021

Just use Wordpress template and create your own form in PHPRunner that would save the data in the database.
Otherwise I don't even see how it is related to PHPRunner.

S
salus1DevClub member 1/20/2021

Because there's a boatload of existing forms of all types out there that can POST to PHP scripts that sanitize and insert data into databases that PHPRunner can then work with.
Also, wanted to show a safer example for inserting user-supplied data in to the database. The example below uses HTMLPurifier (http://htmlpurifier.org) to sanitize input, PDO and Prepared Statements to protect against SQL injection. This example acquires user input from $_GET[''] Super Global Variables, switch to $_POST[''] if that works better in your situation.
<?php

header('Content-Type:text/html; charset=UTF-8');

require_once 'HTMLPurifier.standalone.php';

$servername = "localhost";

$username = "user5";

$password = "USER5password";

$dbname = "contacts";

$firstname = $_GET['firstname'] ?? 'first';

$lastname = $_GET['lastname'] ?? 'last';

$email = $_GET['email'] ?? 'email';

$purifier = new HTMLPurifier();

$firstname = $purifier->purify($firstname);

$lastname = $purifier->purify($lastname);

$email = $purifier->purify($email);

try {

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "INSERT INTO guests (firstname, lastname, email)

VALUES ('$firstname','$lastname','$email')";

$conn->exec($sql);

echo "New record created successfully";

} catch(PDOException $e) {

echo $sql . "
" . $e->getMessage();

}

$conn = null;

?>