I’m a begginner learning to make "contact us" page (in a bit of an improvised way, as you’ll see hehe). I defined some variables using global variables. But when write the query to save them to the database, MySQL understands them as strings, not variables (i.e., instead a name, it saves ${name}), which I understand is because the variables are not defined in MySQL. How can I solve the problem?
Here are the relevant parts of my code. In the first one contato.php, the main file. The second one mens_env.php is the action of the form, where I set the variables related to the database.
contato.php
<form method="POST" action="mens_env.php">
<div class="h"><h2>Fale Conosco</h2></div>
<div class="line1">
<p>Nome</p>
<input type="text" name="nome" class="name">
<p>Email</p>
<input type="text" name="email" class="email">
</div>
<div class="line2">
<p>Celular</p>
<input type="text" name="cel" class="tel">
<p>Assunto</p>
<input type="text" name="assunto" class="assunto">
</div>
<p>Mensagem</p>
<input type="text" name="mensagem" id="mensagem">
<div class="line3">
<input type="submit" value="Enviar" id="submit">
</div>
</form>
mens_env.php
<?php
$hostname="localhost";
$dbname="myDB";
$username="root";
$password="passw";
$dsn="mysql:host=$hostname;dbname=$dbname";
$db= new PDO($dsn, $username ,$password);
$nome = $_POST["nome"];
$email = $_POST["email"];
$tel = $_POST["cel"];
$assunto = $_POST["assunto"];
$mensagem = $_POST["mensagem"];
$userQuery= $db->query('INSERT INTO contato VALUES("${nome}", "${email}", "${assunto}", "${mensagem}", "${tel}")');
$db = null;
?>
2
Answers
Using global variables directly is a bad way. It is better to use filter_input to receive data, and bind it with bindParam before the request. A simple example with email:
The code captures user input from a form and uses a prepared statement to securely insert this data into a database table called contato. By using placeholders and binding parameters, it prevents SQL injection attacks. The execute() method then safely inserts the data into the database.