2017-01-03 3 views
0

Я пытался исправить проблему за последние 2 часа, но не повезло.Обновление запроса обновляется и вставляет

У меня есть страница, где я обновляю рейтинг. Но проблема в том, что когда я нажимаю кнопку «Отправить», она обновляет данные и вставляет новую строку одних и тех же данных. Я не делаю то, что я делаю неправильно. Пожалуйста помоги!

<?php 
require_once('connection.php'); 
if(!isset($_SESSION)) { 
    session_start(); 
} 

if(isset($_GET['company']) && isset($_GET['city']) && isset($_GET['state']) && isset($_GET['country'])) { 
    if(isset($_SESSION['email'])) { 
     $email = $_SESSION['email']; 
     $company = $_GET['company']; 
     $city = $_GET['city']; 
     $state = $_GET['state']; 
     $country = $_GET['country']; 

     $result = mysqli_query($conn, "SELECT * FROM companies_active_accounts WHERE Company_Name='$company' AND City='$city' AND `State/Province`='$state' AND Country='$country'"); 

     $result2 = mysqli_query($conn, "SELECT * FROM register WHERE email='$email'"); 
     while($row = $result2->fetch_assoc()) { 
      $username = $row["username"]; 
     } 

     $result1 = mysqli_query($conn, "SELECT * FROM review WHERE company_name='$company' AND city='$city' AND state='$state' AND country='$country' AND username='$username'"); 
     $rowcount = mysqli_num_rows($result1); 

     if(isset($_POST['rating'])) { 
      $input1 = $_POST['input-1']; 
      $input2 = $_POST['input-2']; 
      $input3 = $_POST['input-3']; 
      $input4 = $_POST['input-4']; 
      $input5 = $_POST['input-5']; 

      $sql1 = "UPDATE `review` SET `respectful` = '$input1', `assurance` = '$input2', `tangibles` = '$input3', `empathy` = '$input4', `responsiveness` = '$input5' WHERE company_name='$company' AND city='$city' AND `state`='$state' AND country='$country'";  
      if ($conn->query($sql1) === TRUE) { 
       header('Location:myrating.php'); 
       exit(); 
      } 
     } 
    } 
} else { 
    header('Location: '.'index.php'); 
    exit(); 
} 

?> 
<?php include('partials/header.php');?> 
<?php include('partials/navbar.php');?> 
<!-- Content --> 
<section id="review"> 
    <div class="container"> 
     <div class="row"> 
     <?php if(isset($_SESSION['email'])) { ?> 
      <div class="col-md-8 col-md-offset-2"> 
       <?php while ($row = mysqli_fetch_assoc($result)) { ?> 
        <h1 class="text-center heading" id="a"><?php echo $row['Company_Name'] ?></h1> 
        <p class="text-center"><span>City: <span id="b"><?php echo $row['City'] ?></span></span> | <span>State/Province: <span id="c"><?php echo $row['State/Province'] ?></span> | </span><span> Country: <span id="d"><?php echo $row['Country'] ?></span></span></p> 
       <?php } ?> 
       <?php if($rowcount > 0) { 
        while ($row = mysqli_fetch_assoc($result1)) { 
       ?> 
         <form method="post" action="edit_rating.php?company=<?php echo $company ?>&city=<?php echo $city ?>&state=<?php echo $state ?>&country=<?php echo $country ?>" id="rating1" > 
          <table> 
           <tr> 
            <td><h2 style="padding-right: 60px;"><span class="hint--top hint--medium" aria-label="A company’s ability to perform the promised service dependably and accurately.">Respectful/Integrity</span></h2></td>  
            <td>     
            <input id="input-1" name="input-1" value="<?php echo $row['respectful']; ?>" class="rating-loading" data-size="sm" productId=1> 
            <script> 
             $(document).on('ready', function(){ 
              $('#input-1').rating({ 
               step: 1, 
               starCaptions: {1: 'Very Poor', 2: 'Poor', 3: 'Ok', 4: 'Good', 5: 'Very Good'}, 
               starCaptionClasses: {1: 'text-danger', 2: 'text-warning', 3: 'text-info', 4: 'text-primary', 5: 'text-success'} 
              }); 
             }); 
            </script> 
           </td> 
          </tr> 
          <tr> 
           <td><h2><span class="hint--top hint--medium" aria-label="The knowledge, competence and courtesy of employees and their ability to convey trust and confidence."> Assurance </span> </h2></td> 
           <td> 
            <input id="input-2" name="input-2" value="<?php echo $row['assurance']; ?>" class="rating-loading" data-size="sm" productId=2> 
            <script> 
             $(document).on('ready', function(){ 
              $('#input-2').rating({ 
               step: 1, 
               starCaptions: {1: 'Very Poor', 2: 'Poor', 3: 'Ok', 4: 'Good', 5: 'Very Good'}, 
               starCaptionClasses: {1: 'text-danger', 2: 'text-warning', 3: 'text-info', 4: 'text-primary', 5: 'text-success'} 
              }); 
             }); 
            </script> 
           </td> 
          </tr> 
          <tr> 
           <td><h2><span class="hint--top hint--medium" aria-label="Physical facilities, equipment and appearances that impress the customer."> Tangibles </span></h2></td> 
           <td> 
            <input id="input-3" name="input-3" value="<?php echo $row['tangibles']; ?>" class="rating-loading" data-size="sm" productId=3> 
            <script> 
             $(document).on('ready', function(){ 
              $('#input-3').rating({ 
               step: 1, 
               starCaptions: {1: 'Very Poor', 2: 'Poor', 3: 'Ok', 4: 'Good', 5: 'Very Good'}, 
               starCaptionClasses: {1: 'text-danger', 2: 'text-warning', 3: 'text-info', 4: 'text-primary', 5: 'text-success'} 
               }); 
              }); 
             </script> 
            </td> 
           </tr> 
           <tr> 
            <td><h2><span class="hint--top hint--medium" aria-label="The level of caring, individualized attention, access, communication and understanding that the customer perceives."> Empathy </span></h2></td> 
            <td> 
            <input id="input-4" name="input-4" value="<?php echo $row['empathy']; ?>" class="rating-loading" data-size="sm" productId=4> 
             <script> 
              $(document).on('ready', function(){ 
               $('#input-4').rating({ 
                step: 1, 
                starCaptions: {1: 'Very Poor', 2: 'Poor', 3: 'Ok', 4: 'Good', 5: 'Very Good'}, 
                starCaptionClasses: {1: 'text-danger', 2: 'text-warning', 3: 'text-info', 4: 'text-primary', 5: 'text-success'} 
               }); 
              }); 
             </script> 
            </td> 
           </tr> 
           <tr> 
            <td><h2><span class="hint--top hint--medium" aria-label="The willingness displayed to help and provide prompt service."> Responsiveness </span></h2></td> 
             <td> 
              <input id="input-5" name="input-5" value="<?php echo $row['responsiveness']; ?>" class="rating-loading" data-size="sm" productId=5> 
              <script> 
               $(document).on('ready', function(){ 
                $('#input-5').rating({ 
                step: 1, 
                starCaptions: {1: 'Very Poor', 2: 'Poor', 3: 'Ok', 4: 'Good', 5: 'Very Good'}, 
                starCaptionClasses: {1: 'text-danger', 2: 'text-warning', 3: 'text-info', 4: 'text-primary', 5: 'text-success'} 
               }); 
              }); 
             </script> 
            </td> 
           </tr> 
          </table> 
          <br> 
         <?php } ?> 
         <button name="rating" id="rating" class="btn btn-success">Update Ratings</button> 
        </form> 
        <?php } else { ?> 
         <h2>Please Review First before editing.</h2> 
        <?php } 
       }?>    
      </div> 
     </div> 
    </div> 
</section> 

<?php include('partials/footer.php');?> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#rating").click(function() { 
      var company = $('#a').text(); 
      var city = $('#b').text(); 
      var state = $('#c').text(); 
      var country = $('#d').text(); 
      var input1 = $('#input-1').val(); 
      var input2 = $('#input-2').val(); 
      var input3 = $('#input-3').val(); 
      var input4 = $('#input-4').val(); 
      var input5 = $('#input-5').val(); 
      if(input1 > 0 && input2 > 0 && input3 > 0 && input4 > 0 && input5 > 0) { 
       $.post('rating.php',{input1 : input1, input2 : input2, input3 : input3, input4 : input4, input5 : input5, company : company, city : city, state : state, country : country}); 
       $(this).attr("checked"); 
       window.location.reload(); 
      } else { 
       alert('Please Rate all fields'); 
       return false; 
      } 
     }); 
    }); 
</script> 

Thank you.

+0

Я не вижу никаких инструкций INSERT в введенном вами коде. Возможно ли, что 'myrating.php' делает INSERT? –

+0

№. Myrating.php только выбрал запрос – Phoenix

+0

Я скопировал вышеуказанный код из review.php и отредактировал его. review.php был вставлен, и обновленный код обновляется. но между двумя страницами нет связи. – Phoenix

ответ

0

Phoenix, я бы попробовал рефакторинг кода, чтобы сделать его намного легче проверить на наличие проблем. Прямо сейчас у вас так много перемешанных движущихся частей, что трудно выделить проблемы, которые у вас есть.

Во-первых, вытащить настройки для сеансов и связи в отдельный файл включают:

setup.php

<?php 
// display errors 
ini_set('display_errors', 1); 

require_once('connection.php'); 

if(!isset($_SESSION)) { 
    session_start(); 
} 

Тогда, я бы тянуть JavaScript в отдельный файл. Следует отметить, что если JavaScript загружен внизу, то после всех элементов HTML, которые вы будете ссылаться в коде, вам не нужно будет звонить ready().

main.js

// original 
$(document).ready(function() { 
    $("#rating").click(function() { 
     var company = $('#a').text(); 

// shorthand 
$(function() { 
    $("#rating").click(function() { 
     var company = $('#a').text(); 

// no need for ready() check at bottom of page as relevant DOM has loaded 
$("#rating").click(function() { 
    var company = $('#a').text(); 

Далее, вы можете реорганизовывать свои чеки. Например, Исеть() принимает несколько аргументов:

// original 
if(isset($_GET['company']) && isset($_GET['city']) && isset($_GET['state']) && isset($_GET['country'])) { 

// shortened 
if (isset($_GET['company'], $_GET['city'], $_GET['state'], $_GET['country'])) { 

Это говорит, на самом деле, я бы начал ломать этот код на более мелкие функции, которые могут быть проверены.

functions.php (или просто добавить к Setup.php

... 
function sessionHasEmail() { 
    return isset($_SESSION['email']); 
} 

function newPage($page) { 
    header('Location: ' . $page); 
    exit();   
} 

function getVarsSent() { 
    return isset($_GET['company'], $_GET['city'], $_GET['state'], $_GET['country']); 
} 

Теперь вы можете сократить большую часть кода на этой странице, чтобы:

<?php 
// include other files and functions and start session 
require_once('setup.php'); 
// check for get vars 
if (!getVarsSent()) newPage('index.php') 
// conditionally query if email session var set 
if (sessionHasEmail()) { 
    // these queries can be broken up into functions 
} 
// etc. 

Идея заключается в том, чтобы сломать код в управляемые разделы, которые намного легче понять, проверить и повторно использовать.

Также, с точки зрения БД, вы, вероятно, захотите нас e уникальный идентификатор для строк, а затем ссылаться на них при создании обновлений (это трудно понять с кодом, который вы опубликовали.)

Наконец, @ jory-geerts сделал два ценных комментария. POST может вызывать некоторые проблемы с точки зрения дубликатов (трудно узнать с кодом, который мы видим.) И теперь вы должны начать добавлять проверки безопасности (подготовленные SQL-запросы и проверка GET/POST var.) Безопасность не «болт- «хорошо, но он служит отличным фундаментом :)

Если вы реорганизуете код и имеете проблемы, связанные с конкретным разделом, опубликуйте обновление, и я постараюсь помочь.

Смежные вопросы