2015-02-02 4 views
0

У меня есть страница PHP, которая генерирует предупреждение javascript при ошибке.Reload page after accepting error

if (strpos($this->color,':') !== false) { 
     echo '<script type="text/javascript">alert("Please use the RBG format of 255:255:255 for color.");</script>'; 
     echo '<script type="text/javascript">location.reload();</script>'; 
     die($conn); 
    } 

Как вы, возможно предположить, я хочу, чтобы перезагрузить страницу после того, как я получаю сообщение об ошибке, а не продолжать с остальной частью PHP, которая на самом деле вставить неправильные данные. Приведенное выше приводит к бесконечному циклу после обновления, и предупреждение продолжает всплывать. Как я могу получить предупреждение один раз, обновить страницу и продолжить?

EDIT

Полный код:

<!DOCspecies html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 
<meta content="text/html; charset=utf-8" http-equiv="Content-species" /> 
<title>Untitled 1</title> 
</head> 

<?php 

$servername = "localhost"; 
$username = "kevin"; 
$password = "ally"; 
$database = "test"; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $database); 

// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 

$getTableQuery = "SELECT tbf.Id, tbf.Name, tbf.Size, tbf.Color, tbs.Name as Species, tbs.Description 
FROM tbl_fish as tbf INNER JOIN 
    tbl_species as tbs ON tbf.Species = tbs.Id 
ORDER BY tbf.Id"; 

$table = $conn->query($getTableQuery); 

if ($table->num_rows > 0) { 
    echo "<table border='1'><tr><th>Name</th><th>Size</th><th>Color</th><th>Species</th></tr>"; 
    // output data of each row 
    while($row = $table->fetch_assoc()) { 
     echo "<tr><td>".$row["Name"]."</td><td>".$row["Size"]."</td><td>".$row["Color"]."</td><td>".$row["Species"]."</td></tr>"; 
    } 
    echo "</table>"; 
    echo "</br>"; 
} else { 
    echo "0 results"; 
} 

if(isset($_POST['btnInsert']) && ($_POST['btnInsert'] == "Insert")) 
{ 
    $Dog = new Dog($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txtSpecies'], $_POST['txtDescription']); 

    $Dog->InsertDog($conn); 
} 

class Dog 
{ 
    private $name = "Dog Name"; 
    private $size = 0; 
    private $color = "255:255:255"; 
    private $speciesName = "Species Name"; 
    private $speciesDescription = "Species Description"; 

    public function Dog($name, $size, $color, $species, $description){ 
     $this->name = $name; 
     $this->size = $size; 
     $this->color = $color; 
     $this->speciesName = $species; 
     $this->speciesDescription = $description; 
    } 

    private function ColorCheck($color){ 
     if($color > 256 || $color < 0) 
      return false; 
     else 
      return true; 
    } 

    public function InsertDog($conn){ 
     $this->speciesName = mysqli_real_escape_string($conn, $this->speciesName); 
     $this->speciesDescription = mysqli_real_escape_string($conn, $this->speciesName); 
     $this->name = mysqli_real_escape_string($conn, $this->name); 
     $this->size = mysqli_real_escape_string($conn, $this->size); 
     $this->color = mysqli_real_escape_string($conn, $this->color); 
     $_SESSION['reloaded'] = false; 
     $color = explode(':', $this->color); 

     if (strpos($this->color,':') !== false && !isset($_SESSION['reloaded'])) { 
      echo '<script type="text/javascript">alert("Please use the RBG format of 255:255:255 for color.");</script>'; 
      echo '<script type="text/javascript">location.reload();</script>'; 
      die($conn); 
     } 

     if(!$this->ColorCheck($color[0]) || !$this->ColorCheck($color[1]) ||!$this->ColorCheck($color[2]) && !isset($_SESSION['reloaded'])){ 
      echo '<script type="text/javascript">alert("Please use the RBG format of 255:255:255 for color.");</script>'; 
      echo '<script type="text/javascript">location.reload();</script>'; 
      die($conn); 
     } 

     $speciesId = "SELECT Id from tbl_species WHERE Name = '$this->speciesDescription'"; 
     $speciesInsert = "INSERT IGNORE INTO tbl_species (Name, Description) 
             VALUES ('$this->speciesName', '$this->speciesDescription')"; 

     $result = mysqli_query($conn, $speciesInsert) or die("Query fail: " . mysqli_error($conn)); 

     if($id = $conn->query($speciesId)){ 
      $row = $id->fetch_assoc(); 
      $intId = $row['Id']; 
     } 

     $DogInsert = "INSERT INTO tbl_fish (Name, Size, Color, Species) 
          VALUES ('$this->name', $this->size, '$this->color', $intId)"; 
     $result2 = mysqli_query($conn, $DogInsert) or die("Query fail: " . mysqli_error($conn)); 

     unset($this); 
    } 

    public function UpdateDog(){ 
    } 
} 
$conn->close(); 
?> 

<body> 

<form action="index.php" method="post"> 
    Dog Name:<br /> 
    <input name="txtName" type="text" /><br /> 
    <br /> 
    Size:<br /> 
    <input name="txtSize" type="text" /><br /> 
    <br /> 
    Color:<br /> 
    <input name="txtColor" type="text" /><br /> 
    <br /> 
    Species Name:<br /> 
    <input name="txtSpecies" type="text" /><br /> 
    <br /> 
    Species Description:<br /> 
    <input name="txtDescription" style="width: 419px; height: 125px" type="text" /><br /> 
    <br /> 
    <input name="btnInsert" type="submit" value="Insert" /> 
    <input name="btnUpdate" type="button" value="Update" /> 
</form> 

</body> 

</html> 
+1

Вы должны вернуться на страницу, где у пользователя есть возможность выбрать или изменить значение цвета. – hellcode

+0

Можете ли вы показать больше кода на этой странице? Это поможет понять, как исправление будет лучше всего соответствовать тому, что у вас уже есть. – mopo922

+0

@ mopo922: Я добавил весь свой код. – MyCodeSucks

ответ

1

location.reload так же, как нажатие на кнопку «Обновить» в вашем браузере, а это значит, что форма будет повторно пост и вы будете идти обратно в этот блок каждый раз:

if(isset($_POST['btnInsert']) && ($_POST['btnInsert'] == "Insert")) 
{ 
    $Dog = new Dog($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txtSpecies'], $_POST['txtDescription']); 

    $Dog->InsertDog($conn); 
} 

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

window.location = window.location.href; 
+0

Где я могу добавить это? Кроме того, я действительно не беспокоюсь о перезагрузке как таковой. Я просто хочу, чтобы это не продолжалось с PHP после ошибки. И в то же время перезагрузите успешную вставку. – MyCodeSucks

+0

@MyCodeSucks используют это вместо 'location.reload()' – mopo922

0

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

if (strpos($this->color,':') !== false && !isset($_SESSION['reloaded'])) { 
    echo '<script type="text/javascript">alert("Please use the RBG format of 255:255:255 for color.");</script>'; 
    echo '<script type="text/javascript">location.reload();</script>'; 

    //set session 
    $_SESSION['reloaded'] = true; 

    die($conn); 
} 
else 
{ 
    //unset session so you can validate again. could be placed somewhere else 
    unset($_SESSION['reloaded']); 
} 

То же самое можно сделать с помощью печенья.