Artorias2718
Artorias2718

Reputation: 633

Laravel SQL: Duplicate Insertion Into Table

I am working on a self-learning project to learn how to use Laravel 4. At this point, I have managed to get most of it to work, but the problem I run into is I get 2 entries in the database tables rather than 1.

I had an error before about a duplicate primary key value, and it still added two entries. I thought this error was the reason behind the duplicate values, but I have since fixed this error and this still happens.

I'm sorry if my code is really messy and unorganized. I will be reorganizing it at the end.

Here's my code (I can't submit images):

Thanks for the help!

File 1: views/customer/index.blade.php

@extends('layout')

<?php
    $total = "";
    $url = "";

    function line_totals()
    {
        $qty = "";
        $unit_price = "";

        global $total;

        $bool = isset($_GET['qty']) || isset($_GET['unit_price']);

        if($bool)
        {
            $qty            = $_GET['qty'];
            $unit_price     = $_GET['unit_price'];
        }

        $qty = str_replace("\n", '<br>', $qty);
        $qty = str_replace("\n", '<br>', $qty);

        $unit_price = str_replace("\n", '<br>', $unit_price);
        $unit_price = str_replace("\n", '<br>', $unit_price);

        $qtyArr = explode('<br>', $qty);
        $priceArr = explode('<br>', $unit_price);

        $total = array();

        for($i = 0; $i < count($qtyArr); $i++)
        {
            $total[$i] = $qtyArr[$i] * $priceArr[$i];
        }
        return $total;
    }

    $total = json_encode(line_totals());

function insert_customer()
    {
        $customerIsFilled = isset($_GET['date']) || isset($_GET['receipt']) || isset($_GET['name']) || isset($_GET['address']) || isset($_GET['city']) || isset($_GET['state']) || isset($_GET['zip']);

        if($customerIsFilled)
        {
            $id                 = "";
            $name               = $_GET['name'];
            $address            = $_GET['address'];
            $city               = $_GET['city'];
            $state              = $_GET['state'];
            $zip                = $_GET['zip'];
            $created_at         = date('Y-m-d H:i:s');
            $updated_at         = date('Y-m-d H:i:s');

            $insert_cust = array(
                                'id'                => $id,
                                'name'              => $name,
                                'address'           => $address,
                                'city'              => $city,
                                'state'             => $state,
                                'zip'               => $zip,
                                'created_at'        => $created_at,
                                'updated_at'        => $updated_at
                    );

            DB::table('customer')->insert($insert_cust);
        }
        else
            return;
    }

    function insert_work()
    {       
        $curId = 0;

        $select = DB::select('SELECT * FROM customer');

        $ids = array();

        for($i = 0; $i < count($select); $i++)
        {
            if(!empty($select))
            {
                $ids[$i] = DB::table('customer')->pluck('id');
                $curId = max($ids);
            }
        }

        $workIsFilled = isset($_GET['date']) || isset($_GET['receipt']) || isset($_GET['qty']) || isset($_GET['description']) || isset($_GET['unit_price']) || isset($_GET['line_total']) || isset($_GET['created_at']) || isset($_GET['updated_at']);

        $line_total     =   "";

        if($workIsFilled)
        {
            $cust_id        =   $curId;
            $qty            =   htmlspecialchars($_GET['qty']);
            $date           =   htmlspecialchars($_GET['date']);
            $receipt        =   htmlspecialchars($_GET['receipt']);
            $description    =   htmlspecialchars($_GET['description']);
            $unit_price     =   htmlspecialchars($_GET['unit_price']);
            $created_at     =   date('Y-m-d H:i:s');
            $updated_at     =   date('Y-m-d H:i:s');

            $tot = line_totals();

            for($i = 0; $i < count($tot); $i++)
            {
                $line_total .= $tot[$i]."\n";
            }

            $insert_work = array(
                                'cust_id'       => $cust_id,
                                'qty'           => $qty,
                                'date'          => $date,
                                'receipt'       => $receipt,
                                'description'   => $description,
                                'unit_price'    => $unit_price,
                                'line_total'    => $line_total,
                                'created_at'    => $created_at,
                                'updated_at'    => $updated_at
                        );
            DB::table('work')->insert($insert_work);
        }
        else
            return;
    }

    // Store HTTP GET request parameters into $url

    $get = action('CustomerController@getResults', $url);   
 ?>

@section('content')
    <form action="{{ $url }}" method="get">
        <table style="margin-left:250px;" cellspacing="5">
            <tr>
                <td> Name: </td> <td> <input name="name" id="name" type="text" value="John Doe"> </td>
                <td> Address: </td> <td> <input name="address" id="address" type="text" value="Street Address"> </td>
                <td> City: </td> <td> <input name="city" id="city" type="text" value="City"> </td>
                <td> ST: </td> <td> <input name="state" id="state" size="2" maxlength="2" type="text" value="ST"> </td>
                <td> Zip: </td> <td> <input name="zip" id="zip" type="text" value="12345"> </td>
            </tr>
        </table>

        <br><br>


        <h1 style="text-align:center;">Work Performed</h1>


    <table style="margin-left:350px;" cellspacing="5">
        <tr>
            <td> Date: </td> <td> <input id="date" name="date" type="text" value="14-01-01"></td>
            <td> Receipt#: </td> <td> <input name="receipt" value="9000"> </td>
        </tr>
    </table>
        <table style="margin-left:350px;" cellspacing="5">
        <tr>
            <td> <textarea rows="1" placeholder="Qty" id="qty" name="qty">5<?php echo "\n"; ?>5</textarea>                              </td>
            <td> <textarea rows="1" placeholder="Description" id="description" name="description">Job 1<?php echo "\n"; ?>Job 2</textarea>      </td>
            <td> <textarea rows="1" placeholder="Unit Price" id = "unit_price" name="unit_price">200<?php echo "\n"; ?>400</textarea>       </td>
            <td> <textarea rows="1" placeholder="Line Total" id="line_total" name="line_total" disabled></textarea> </td>
        </tr>
        </table>
        <br>
        <input style="margin-left:600px;" id="add" type="submit" value="Submit">
    </form>
@stop

File 2: views/layout.blade.php

<!doctype html>
<html>
@section('header')
<head>

    <title></title>

    <style type="text/css">

        #subHeading
        {
            display: block;
            position: absolute;
            font-style: italic;
            font-weight: bold;
            font-size: 25pt;
            margin-top:-10px;
            margin-left: 600px;
        }

        #qty, #description, #unit_price, #line_total
        {
            text-align: center;
        }

    </style>
<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui.min.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>

</head>
<body>

<span id="subHeading">Invoice</span>
<br>
<hr
<br>
<script type="text/javascript">
    $(function(){
        $("#date").datepicker({
            dateFormat:"y-mm-dd"
        });
    });

    $(document).ready(function(){
        if($("#name").val() != "" && $("#address").val() != "" && $("#city").val() != "" && $("#state").val() != "" && $("#zip").val() != "")
        {
            $("#add").on('click', function()
            {
                $.ajax({
                    url: 'customer/index.blade.php',
                    success: $(function(){
                        //alert("New Customer!");
                        <?php   insert_customer();?>
                    })
                });
            });
        }       
        else if($("#qty").val() != "" && $("#description").val() != "" && $("#unit_price").val() != "")
        {
            $("#add").on('click', function()
            {
                $.ajax({
                    url: 'customer/index.blade.php',
                    success: $(function(){
                        //alert("New Work Order Added!");
                        <?php insert_work(); ?>
                    })
                });
            });
        }

        $("#line_total").hide();
    });




/*  $.ajax({ 
      url: 'index.blade.php',
      success: $(function(data) {
       // <?php insert_customer(); ?>
        <?php insert_work(); ?>
    });*/

</script>

@stop

@yield('header')
@yield('content')

</body>
</html>

Upvotes: 0

Views: 1318

Answers (1)

Steve O
Steve O

Reputation: 5794

Ok so the reason you're getting a double insert is the commented out javascript contains php functions that aren't commented out:

/*  $.ajax({ 
    url: 'index.blade.php',
    success: $(function(data) {
    // <?php insert_customer(); ?>
    <?php insert_work(); ?>
});*/

While you've managed to comment out the javascript here, the php will still run. To successfully comment out the php you'd need to work within the php tags:

<?php // myFunction(); ?>
<?php /* myFunction(); */ ?>

From looking over your code it looks like you just need to work on your understanding of Javascript (a client side language) vs PHP (a server side language) which is no problem, that's what makes a learning project so valuable. Here's a bit of info you'll hopefully find useful:


1. PHP function calls in the page will be called on page load. Here's an example:

An example php file:

<?php
function myFunction(){
    echo 'Hello World';
}
?>

<html>
    <body>
        <?php myFunction(); ?>
    </body>
</html>

This will output the following html to the browser:

<html>
    <body>
        Hello World
    </body>
</html>

So when you call your <?php insert_work(); ?> function in the page, it will run straight away on the page load and because it's in there twice you're getting duplicate calls of your function.


2. You can't directly call PHP functions from Javascript

This unfortunately wont work how you might want it to:

<?php
    function myPhpFunction(){
        // Insert into database on click
    }
?>

<html>
    <head>
        <script>
            $('.button').click(function(){
                <?php myPhpFunction(); ?>
            });
        </script>
    </head>
...

What actually happens here is the myPhpFunction() get's called on the page load. What you need is an ajax call which I can see you already have attached to your #add submit button. Here's a quick example using your code:

A brief version of your layout.blade.php

<html>
    <head>
        <script>
            $("#add").on('click', function()
            {
                // Grab the form data
                var data = $("form").serialize();

                // Perform the ajax request
                $.ajax({
                    // Call the route here not the file
                    url: '/customer',
                    data: data,
                    success: $(function(data){
                        // Add the returned data to the p tag
                        $("p").html(data);
                    })
                });
            });
        </script>
    </head>
    <body>
        <form action="{{ $url }}" method="get">
            <input name="name" id="name" type="text" value="John Doe">
            <textarea rows="1" placeholder="Description" id="description" name="description">
            <input id="add" type="submit" value="Submit">
        </form>

        <p><!-- Your results will load here --></p>
    </body>
</html>

A brief version of your customer/index.blade.php

<?php
    function insert_customer(){
        // Perform DB insert

        echo 'Success! Customer added.';
    }

    // Call insert_customer()
    insert_customer();
?>

Here when your button is clicked we grab the form data and send a ajax GET request to the customer/index route which performs the function and send us the feedback that the function has been successful.

Sorry that's such a lengthy answer. Hopefully it's helpful!

Upvotes: 1

Related Questions