Обновить страницу после принятия ошибки

0

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

    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, которая фактически введет неправильные данные. Приведенное выше приводит к бесконечному циклу после обновления, и предупреждение продолжает всплывать. Как я могу получить предупреждение один раз, обновить страницу и продолжить?

РЕДАКТИРОВАТЬ

Полный код:

<!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
    Вы должны вернуться на страницу, где у пользователя есть возможность выбрать или изменить значение цвета.
  • 0
    Можете ли вы показать больше кода на этой странице? Это поможет увидеть, как исправление лучше всего подходит к тому, что у вас уже есть.
Показать ещё 2 комментария
Теги:

2 ответа

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 после ошибки. И в то же время перезагрузите после успешной вставки.
  • 0
    @MyCodeSucks использует это вместо location.reload()
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']);
}

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню