Home > Back-end >  PHP contact form not sending data to mysql database
PHP contact form not sending data to mysql database

Time:05-31

I'm a brand new beginner in this... This is my PHP, I've got it working to send the email, however, I'm struggling to connect it to the database. I'd welcome any pointers at all! Thanks so much! :)

<?php
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'sendEmail')
{
    $to = '[email protected]';
    $subject = 'websitecontactform';
    $send_arr = array();    
    
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: <".$_REQUEST['con_email'].">" . "\r\n";
    $headers .= "Cc: ".$_REQUEST['con_email'] . "\r\n";
    
    $message = "First Name : ".$_REQUEST['fname']. "<br />";
    $message .= "Last Name : ".$_REQUEST['lname']. "<br />";
    $message .= "Email : ".$_REQUEST['con_email']. "<br />";
    $message .= "Phone : ".$_REQUEST['con_phone']. "<br />";
    $message .= "Country : ".$_REQUEST['con_country']. "<br />";
    $message .= "Message : ".$_REQUEST['con_message']. "<br />";
    
    if (mail($to,$subject,$message,$headers) ){
        
        $send_arr['response'] = 'success';
        $send_arr['message'] = 'Your message has been sent.';
        
        } else{
            
        $send_arr['response'] = 'error';
        $send_arr['message'] = "You message couldn't be sent. Please try later!";
            
            }
    echo json_encode($send_arr);
    exit;
    
}

?>

CodePudding user response:

Welcome Andy!

You want to create a database connection file first and link to it from your php file.

You could use something like this for your connection file, just change the user, password, host and database name:

    <?php
$servername = "localhost";
$username = "";
$password = "";

try {
  $db_con = new PDO("mysql:host=$servername;dbname=", $username, $password);
  // set the PDO error mode to exception
  $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>

Then, in your php file include something like this (your location may differ):

require_once 'config/config.php';

This will get you started on connecting to your database.

CodePudding user response:

you must be clear with your question, i cant see any database query.

  • First connect to a database
  • Then write insert query to insert data.
  • Related