1

I'm New at PHP, I want to ask about my problem. I have a code for insert function and for check the duplicate data. But on my code can't show a message if there're a duplicate data. But the query for checking double data is work., and i want to show my message duplicate data on master_toko.php after section class content. Please Help me for this problem

crudAction.php

<?php
    
    function runQuery($db, $query, $queryType) {
    
        $result = mysqli_query($db, $query);
        if(!empty(mysqli_error($db))) {
            return [
                'error' => true,
                'message' => mysqli_error($db)
            ];
        }
            
            return [
                'error' => false,
                'message' => getMessage($queryType)
            ];
    }
    
    function buildInsertQuery($tableName, $data) {
    
        $tableColumns = [];
        $insertValues = [];
        foreach ($data as $key => $value) {
            array_push($tableColumns, $key);
            array_push($insertValues, $value);
        }
    
        $columns = "(`" . implode("`,`", $tableColumns) . "`)";
        $values = "('" . implode("','", $insertValues) . "')";
        $query = "INSERT INTO `$tableName` ". $columns . " VALUES " . $values ." ";
        
        return $query ?? false;
    }
    
    
    function getMessage($queryType) {
        $messages = [
            'insert' => 'Data has been succesfuly added',
            'delete' => 'Data has been succesfuly deleted',
            'dataDouble' => 'Data Ada yang Dobel'
        ];  
    
        return $messages[$queryType];
    }
    
    function getLastID() {
        return mysqli_insert_id();
    }
    ?>

formAction.php

<?php
    
    $actionObject = $_REQUEST['actionObject'] ?? '';
    $actionType = $_REQUEST['actionType'] ?? '';
    
    include $actionObject .'Crud.php';
    include 'config.php';
    
    function getTableName($actionObject) 
    {
      $tableMapping = [
        'toko' => 'master_toko'

      ];
        return $tableMapping[$actionObject];
    }
    
    $db = getDBConnection();
    $tableName = getTableName($actionObject);
    
    switch($actionType):
      case 'insert' : $result = insertData($db, $tableName);
        break;
      case 'delete' : $result = deleteData($db, $tableName);
        break;
      case 'update' : $result = updateData($db, $tableName);
        break;
    endswitch;
    
    if (!$result['error']) {
        header('location: ' . $_REQUEST['pageReferrer'] . '&error=false&message=' . $result['message']);
    } else {
        header('location: ' . $_REQUEST['pageReferrer'] . '&error=true&message=' . $result['message']);
    }
    
    
    
    
    ?>

tokoCrud.php

 ```
<?php
        include ('crudAction.php');
        
        function insertData($db, $tableName) {

            $redirect_url = 'http://localhost/city/?page=store&error=false&message=';
            $data = [
                'id_ot' => ' ',
                'nama_ot' => $_POST['namaToko'],
                'alamat_ot' => $_POST['alamatToko'],
                'status_ot' => '1'
            ];
    
            if(!isDataTokoExist($db, $namaToko)) {
                $query = buildInsertQuery($tableName, $data);
                
                return runQuery($db, $query, 'insert');
            }
            else {
                return runQuery($db, $query, 'dataDouble');
            }
            
        }

        function isDataTokoExist($db, $namaToko) {
            $namaToko = $_POST['namaToko'];
            $query = "SELECT * FROM master_toko WHERE nama_ot = '$namaToko'";
            $result = mysqli_query($db, $query);
            
        }

    ?>
```

messageBox.php

```
<?php

    if(isset($_GET['error']) && isset($_GET['message'])) {
        $error = $_GET['error'];
        $message = $_GET['message'];
        $messageClass = $error === 'false' ? 'error-message' : 'success-message';
    ?>

        <div class ="message <?php echo $messageClass; ?>">
            <?php echo $message; ?>
        </div>

    <?php
    }
    ?>
```

master_toko.php

```
<?php
  require "partial/header.php";
  require "partial/sidebar.php";
  // include 'messageBox.php';
 ?>
  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->

    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1>Master Toko</h1>
          </div>
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item active">Master Toko</li>
            </ol>
          </div>
        </div>
      </div><!-- /.container-fluid -->
    </section>

    <!-- Main content -->
    <section class="content">
    <?php include 'library/services/messageBox.php'; 
                ?>
      <div class="container-fluid">
        <div class="row">
          <div class="col-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">Data Toko</h3>
                <button type="button" class="btn btn-success float-right" data-toggle="modal" data-target=".modalBesar">Tambah Data</button>
              </div>
            <!-- Bagian Form Modal -->
              <div class="modal fade modalBesar" tabindex="-1" role="dialog" aria-hidden="true">
                <div class="modal-dialog">
                <div class="modal-content">
                <div class="modal-header">
                  <h4 class="modal-title" id="exampleModalLabel">Tambah Toko</h4>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
              <div class="modal-body">
                <form method = "post" action = "library/services/formAction.php">
                <input type="hidden" name="pageReferrer" value="http://localhost/city/?page=store" >
                <input type="hidden" name="actionObject" value="toko" >
                <input type="hidden" name="actionType" value="insert" >
                  <div class="form-group">
                    <label for="recipient-name" class="col-form-label">Nama Toko</label>
                    <input type="text" class="form-control" id="namaToko" placeholder="Masukkan Nama Toko" name="namaToko" required>
                  </div>
                  <div class="form-group">
                    <label for="recipient-name" class="col-form-label">Alamat Toko</label>
                    <input type="text" class="form-control" id="alamatToko" placeholder="Masukkan Nama Toko" name="alamatToko" required>
                  </div>
                  <div class="modal-footer">
                <button type="submit" class="btn btn-primary" name="submit">Submit</button>
              </div>
                </form>
              </div>
                  </div>
              </div>
            </div>
            <!-- Akhir Bagian Modal -->

            

              <!-- /.card-header -->
              <div class="card-body">
                <table id="example1" class="table table-bordered table-striped">
                  <thead>
                  <tr>
                    <th>No</th>
                    <th>Toko</th>
                    <th>Alamat</th>
                    <th>Status</th>
                    <th>Opsi</th>
                  </tr>
                  </thead>
                  <tbody>
                  
                  </tbody>
                </table>
              </div>
              <!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
          <!-- /.col -->
        </div>
        <!-- /.row -->
      </div>
      <!-- /.container-fluid -->
    </section>
    <!-- /.content -->
    
  </div>
  <!-- /.content-wrapper -->
  <!-- /.content-wrapper -->
  <?php require "partial/footer.php"; ?>




```
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Sep 28 '21 at 12:55

1 Answers1

2

Your isDataTokoExist() function doesn't return a value, so referencing it in a conditional will always yield NULL, regardless of whatever calculations it's doing. You want to return the result of your calculation:

function isDataTokoExist($db, $namaToko) {
    if (<some calculation to determine if the data exists>) {
        return true;
    } else {
        return false;
    }
}

Also note, you generally don't want to rely on the output of a SELECT query to avoid inserting duplicates. In a multi-user system, another process could insert into the database between the time when your SELECT runs and your subsequent INSERT runs, and then you'll get duplicates. Instead, create a UNIQUE constraint on the field in question and then verify that your INSERT succeeded.

And, your code is vulnerable to SQL injection attacks. Instead of building queries with string concatenation, always use prepared statements with bound parameters. See this page and this post for some good examples.

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98