<html>
<!--
====================================================================================================
This PHP script takes data from a form, and writes it to MySQL database (table: cust_order)
====================================================================================================
-->
<head>
<title>Process an HTML form</title>
</head>
<body>
<?php include "../include.php"; ?>              <!-- hyperlink to see the code -->

<?php
    error_reporting(0);
        
    $firstname  = $_POST['firstname'];              #get HTML form entry fields 
    $lastname   = $_POST['lastname'];                
    $address    = $_POST['address'];
    $flavors    = $_POST['flavor'];                 #select list array
    $toppings   = $_POST['topping'];                #checkboxes array
    $creditCard = $_POST['creditCard'];

    if (is_array($flavors))                         #flavors is an array
        $flavor  = implode(',' , $flavors);         #turn it into a string          
    if (is_array($toppings))                        
        $topping = implode(',' , $toppings);         

    saveData();                                     #save data into the database

//----- Write data into Database ----------------------------------------------------
function saveData()
{
    global $firstname,$lastname,$address,$flavor,$topping,$creditCard;

        $host   = 'localhost';
        $DBname = 'demo2';
        $DBuser = 'demo2';
        $DBpswd = 'demo2';
 
        $connect = mysqli_connect($host,$DBuser,$DBpswd,$DBname);   #connect to db server
 
        if (! $connect) 
            die('Could not connect: ' . mysqli_connect_error());

        $firstname = htmlentities($firstname);    		#replace < > ' " & characters;
        $lastname  = htmlentities($lastname);     		#with their html entities;
        $address   = htmlentities($address );     		# < > ' "e; &

        $firstname = mysqli_real_escape_string($connect,$firstname);  #escape all ' " \ newline 
        $lastname  = mysqli_real_escape_string($connect,$lastname);   #with another \, making them
        $address   = mysqli_real_escape_string($connect,$address);    # \' \" \\ \newline

        $insert = "INSERT INTO cust_order
                   (order_id,firstname,lastname,address,flavor,topping,creditCard,cust_id) 
                   VALUES(0,'$firstname','$lastname','$address',
                            '$flavor',   '$topping', '$creditCard', 1)";
        
        $result = mysqli_query($connect, $insert);                        #issue the query                        

        if (! $result) 
            die('Could not execute insert: ' . mysqli_error($connect));
       
        mysqli_close($connect);                                  #close connection

        print "<b>Order Processed Successfully!!!</b>";
}
//=============================================================================
?>

<br><br>
<hr/>
Click <a href=getFromDB.php>here</a> to see all orders
</body>
</html>