0

Hi so I can't seem to find any help on this topic because there is no error being thrown. I am trying to insert records to a database via php using mysqli_query but after the re-direct no changes are made. I have three files I am working with, index.php, conn.php and new.php. index.php and new.php are located in the same folder but conn.php is one directory below. index.php:

    <!DOCTYPE html>
<html>
    <head>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <link rel="stylesheet" href="style.css" type="text/css" >
        <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Khula" rel="stylesheet">

    </head>
    <script>
        $(function()
        {
            $('.error').fadeOut(10000);
        });
    </script>

    <body>

        <header>
           <img src="images/logo.png"> 
            <p>The reliable bus company</p>
        </header>

        <div class="wrapper">
            <div class="container">
                <div class="titletxt">
                    <h4>Drivers</h4>

                </div>
                <?php
        include '../conn.php';
        mysqli_query($conn, "SET NAMES utf8");
        $result = mysqli_query($conn, "SELECT * FROM tbl_employee");

        echo "
        <div class='table_content'>
        <table align='center'>
        <tr>
        <th>Employee ID</th>
        <th>Title</th>
        <th>Name</th>
        <th>Address</th>
        <th>Contact Number</th>
        <th>Job Position</th>
        <th>Gender</th>
        <th>DOB</th>
        </tr>
        ";

        while($row = mysqli_fetch_array($result))
        {
            echo "<tr>";
            echo "<td>" . $row['employeeID'] . "</td>";
            echo "<td>" . $row['title'] . "</td>";
            echo "<td>" . $row['name'] . "</td>";
            echo "<td>" . $row['address'] . "</td>";
            echo "<td>" . $row['contactNum'] . "</td>";
            echo "<td>" . $row['position'] . "</td>";
            echo "<td>" . $row['gender'] . "</td>";
            echo "<td>" . $row['DOB'] . "</td>";
            echo "</tr>";
        }
        echo "</table></div>";


        ?>


                <!-- Record Insert -->
                <br>
                <div class="titletxt">
                    <h4>Insert a Record</h4>
                </div>
                <h3 style="font-weight: 400; margin-left: 5px;">New Employee</h3>
                <form class="insert_form" action="new.php" method="post" name="insert_form">
                    <label>Title: </label>
                    <input type="text" name="title" required><br>
                    <span class="error"><?php echo $titleErr ?></span>
                    <br>
                    <label>Name: </label>
                    <input type="text" name="name" required> <br>
                    <span class="error"><?php echo $nameErr ?></span>
                    <br>
                    <label>Address:</label>
                    <input type="text" name="address" required><br>
                    <span class="error"><?php echo $addressErr ?></span>
                    <br>
                    <label>Contact Number</label>
                    <input type="text" name="contactNum" required><br>
                    <span class="error"><?php echo $contactErr ?></span>
                    <br>
                    <label>Job Position</label>
                    <input type="text" name="position" required><br>
                    <span class="error"><?php echo $positionErr ?></span>
                    <br>
                    <label>Gender: </label>
                    <input type="radio" name="gender" value="male" required> Male
                    <input type="radio" name="gender" value="female" required> Female<br>
                    <span class="error"><?php echo $genderErr ?></span>
                    <br>
                    <label>DOB: </label>
                    <input style="width: 60px;" type="text" name="DOB_year" required>YYYY
                    <input style="width: 30px;" type="text" name="DOB_months" required>MM
                    <input type="text" name="DOB_day" style="width: 30px" required>DD<br>
                    <span class="error"><?php echo $DOBErr ?></span>
                    <br>
                    <input type="submit" Value="Insert Entry">

                </form>


            </div>
        </div>
    </body>
</html>

conn.php:

    <?php 
   $server = "localhost";
    $user = "root";
    $password = "";
    $db = "bus_db";
    global $conn;
    $conn = mysqli_connect($server, $user, $password, $db);
    if(mysqli_connect_errno())
    {
        echo "Mysql Error has occured" . mysqli_connect_error;
    }

    else if(!mysqli_connect_errno())
    {
        echo "<connection>Connection Established</connection>";
    }


function close_connection()
{
    global $conn;
    mysqli_close($conn);
}

$title = $name = $address = $contact = $position = $gender = $DOB = "";
                      $titleErr = $nameErr = $addressErr = $contactErr = $positionErr = $genderErr = $DOBErr = ""; 
                mysqli_query($conn, "SET NAMES utf8");
                    if ($_SERVER["REQUEST_METHOD"] == "POST")
                      {
                          if (empty($_POST["title"]))
                          {
                              $titleErr = "Title is Required";
                          }else{
                              $title = input($_POST["title"]);
                          }

                          if (empty($_POST["name"]))
                          {
                              $nameErr = "Name is Required";
                          }else
                          {
                              $name = input($_POST["name"]);
                              if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                                    $nameErr = "Invalid Name"; 
                            }
                          }

                          if (empty($_POST["address"]))
                          {
                              $addressErr = "Address is Required";
                          }else{
                              $address = input($_POST["address"]);
                          }

                            if (empty($_POST["contactNum"]))
                            {
                                $contactErr = "Contact Number is required ";
                            }else{
                                $contact = input($_POST["contactNum"]);
                                $regex = "^([0-9]{10,11})$^";
                                if (!preg_match($regex, $contact)) {
                                    $contactErr = "Invalid Phone Number";
                                }
                            }

                            if(empty($_POST["position"]))
                            {
                                $positionErr = "Position is required";
                            }else{
                                $position = input($_POST["position"]);
                            }

                            if (empty($_POST["gender"]))
                            {
                                $genderErr = "Gender is Required";
                            }else{
                                $gender = input($_POST["gender"]);
                            }

                            if (empty($_POST["DOB_year"]) || empty($_POST["DOB_months"]) || empty($_POST["DOB_day"]))
                            {
                                $DOBErr = "Invalid entry for date of birth";
                            }else
                            {
                                $DOB = input($_POST["DOB_year"] + "/" + $_POST["DOB_months"] + "/" + $_POST["DOB_day"]);
                            }
                      }
                      function input($data) {
                          $data = trim($data);
                          $data = stripslashes($data);
                          $data = htmlspecialchars($data);
                          return $data;
                      }

function insert_records($p_title, $p_name, $p_address, $p_contact, $p_position, $p_gender, $p_DOB)
{
    global $conn;
    mysqli_query($conn, "INSERT INTO tbl_employee VALUES(null, '" .$p_title."', '".$p_name."', '".$p_address."', '".$p_contact."', '".$p_position."', '".$p_gender."', '".$p_DOB."')");
}
?>

new.php:

<?php 
include '../conn.php';
insert_records($title, $name, $address, $contact, $position, $gender, $DOB);
header( 'Location:index.php');
close_connection();
?>

I would appreciate any, thanks

3
  • 1
    "No error thrown" - I didn't see mysqli_error($conn) or any error reporting done. Commented May 21, 2017 at 19:57
  • 1
    $DOB = input($_POST["DOB_year"] + "/" + $_POST["DOB_months"] + "/" + $_POST["DOB_day"]); are you doing math? I doubt it. Commented May 21, 2017 at 19:57
  • 1
    Your code is vulnerable to SQL injections. Please learn to use prepared statements. Commented May 21, 2017 at 20:00

1 Answer 1

2

You should edit your insert_records() to give you feedback if mysqli_query fails.

function insert_records($p_title, $p_name, $p_address, $p_contact, $p_position, $p_gender, $p_DOB)
{
    global $conn;
    $result = mysqli_query($conn, 'some query') or die('Query failed: ' . mysqli_error($conn));
    return $result;
}

and read about how you can prevent MySQL injection here: How can I prevent SQL injection in PHP?


edit:

$DOB = input($_POST["DOB_year"] + "/" + $_POST["DOB_months"] + "/" + $_POST["DOB_day"]);

in php '+' is used to do calculations. if you want to concatenate strings use '.'

$DOB = input($_POST["DOB_year"] . "/" . $_POST["DOB_months"] . "/" . $_POST["DOB_day"]);
Sign up to request clarification or add additional context in comments.

2 Comments

Hiya, thanks for your to help. The page now shows me the error: Incorrect date value: ' ' for column 'DOB' at row 1. Any idea what data format needs to be entered into the form for it to be accepted by the database
After a bit more research I found a post saying that php inserts for sql should be written like this: , CAST('". $date ."' AS DATE))"). So i changed my code to , CAST('". $p_DOB ."' AS DATE))") or die('Query failed: ' . mysqli_error($conn)); and the error I get now is Query failed: Incorrect datetime value: '' Any suggestions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.