Home > Back-end >  Data inserted into the database but has empty values
Data inserted into the database but has empty values

Time:03-08

I have a form that upon successful completion, it should get inserted into the data base, however, this is not what happens, what happens is that i see in the table of the database that the "id" is incremented by 1, but the other columns in the table are empty, so the connection to the data base is not the issue, could use some help, thank you everyone. below is the php code for my form, as well the the inserting code.

<?php


// define variables and set to empty values
$staffErr = $emailErr = $subjectErr = $problemErr = $descriptionErr= "";
$staffname = $email = $subject = $problem_type = $description = "";


// staff name validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["staff_name"])) {
    $staffErr = "Staff Name is required";
} else {
    $staffname = test_input($_POST["staff_name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z-' ]*$/",$staffname)) {
    $staffErr = "Only letters and white space allowed";
    }    
}


if (empty($_POST["email"])) {
    $emailErr = "Email is required";
} else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailErr = "Please enter a valid email.";
    }
}


// subject validation:

    if (empty($_POST["subject"])) {
        $subjectErr = "Subject is required";
    } else {
        $subject = test_input($_POST["subject"]);
        // check if subject only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' ]*$/",$subject)) {
        $subjectErr = "Only letters and white space allowed";
        }
    }
    



// problem type validation:

if (empty($_POST["problem_type"])) {
    $problemErr = "Problem type is required";
} else {
    $problem_type = test_input($_POST["problem_type"]);
}

// description validation:

if (empty($_POST["description"])) {
    $descriptionErr = "A Description is required";
} else {
    $description = test_input($_POST["description"]);
}


}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}


if(isset($_POST['submit'])) {
    if ($staffErr == "" && $emailErr == "" &&$subjectErr == "" &&$problemErr == "" &&$descriptionErr == "") {
    header("Location:insert_logs.php");
            exit(); 
            
             } 
     else {
                header("Location:log-it-reports.php");
            exit(); 
}
     }
?>



    <div class= "content">
       
       <div >
        <form  method="POST" onsubmit=" return formSubmit() " >
          <div  id= "errorMsg">* Required Fields</div>
          <div  id= "errorMsg1">*<?php echo $staffErr; ?></div>
          <div>
          <label for="staff_name"><b>Staff Name:</b></label> 
          <input   id="staff_name" name="staff_name" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name"  > 
          </div><br>

          <div  id= "errorMsg2">*<?php echo $emailErr;?></div>
          <div>
          <label for="email"><b>Email:</b></label> 
          <input  id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="[email protected]">  
          </div><br>
          <div  id= "errorMsg3">*<?php echo $subjectErr;?></div>
          <div>
          <label for="subject"><b>Subject:</b></label> 
          <input   name="subject" id="subject1" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title"  > 
          </div><br>

          <div  id= "errorMsg4">*<?php echo $problemErr;?></div>
          <div>
            <select onclick=" return problemValidation()" onchange=" return problemValidation()"  name="problem_type" id="problemtypes">
                <option value="">Problem Type</option>
                <option value="Hardware">Hardware</option>
                <option value="Software">Software</option>
                <option value="Software&Hardware">Software & Hardware</option>
                <option value="Other">Other</option>
              </select>
          </div><br>
          <div  id= "errorMsg5">*<?php echo $descriptionErr;?></div>
          <div>
          <textarea  id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" name="descript" rows="15" cols="90"></textarea>
          </div>          
          
          <div>
            <button  name="submit" type="submit" >Submit</button>
            <input type="checkbox" id="notify" name="notify" value="">
            <label for="notify">Inform me by email when issue is resolved.</label> 
        </div>
        </form>
       
    </div>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inserting IT reports into the database</title>
    <link rel="stylesheet" href="update.css">
</head>
<body>
<?php
        //inserting inputs to the data base
        //database connection variables for the database on your web server
        $servername = "localhost"; 
        $username = "*******";
        $password = "*******";
        $database = "attack_titan"; 
        
        //saving all of the user's POST values from the the form submission to local variables
        $staffname = $_POST['staffname'];
        $email = $_POST['email'];
        $subject = $_POST['subjects'];
        $problem_type = $_POST['problem_type'];
        $description = $_POST['description'];
        


       
        //we start a try and catch block to attempt to connect to our database and run the query. If it fails, we see the error/exception generated by the catch
        try {
            $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); //building a new PDO connection object
           
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the PDO error mode to exception

             // prepare sql and bind parameters

            $stmt = $conn->prepare("INSERT INTO it_reports (staff_name, email, subjects, problem_type, descriptions)
            VALUES ('$staffname', '$email', '$subject', '$problem_type', '$description')");
            $stmt->bindParam(':staffname', $staffname);
            $stmt->bindParam(':email', $email);
            $stmt->bindParam(':subject', $subject);
            $stmt->bindParam(':problem_type', $problem_Type);
            $stmt->bindParam(':description', $description);

            
            // use execute() to run the query
            $stmt->execute();
            
            echo "<p class = 'inserted' >Your report has been submitted successfully</p><br>"  ,  '<a class = "button" href="log-it-reports.php">Click to go back to the previous page</a>';
            // If successful we will see this
            // you could then check PHPMyAdmin to see if the record was inserted
            }
        catch(PDOException $e)
            {
            echo "Error" . $e->getMessage(); //If we are not successful we will see an error
            }
        ?>
</body>
</html>

CodePudding user response:

You have an error in your insert statement.
Try to change:

$stmt = $conn->prepare("INSERT INTO it_reports (staff_name, email, subjects, problem_type, descriptions) VALUES ('$staffname', '$email', '$subject', '$problem_type', '$description')");

with

$stmt = $conn->prepare("INSERT INTO it_reports (staff_name, email, subjects, problem_type, descriptions) VALUES (:staffname, :email, :subject, :problem_type, :description)");

So, the bindValue statement can works

CodePudding user response:

I am not that familiar with MySQL, but i know there are different storage engines available. InnoDB supports transactions and MyISAM doesn't have such a feature. With InnoDB you might need to explicitly commit your changes, depending on the configuration.

More info on this topic: https://dev.mysql.com/doc/refman/8.0/en/innodb-autocommit-commit-rollback.html

  • Related