删除查询失败后,变量将不会显示

时间:2019-03-24 10:29:09

标签: php mysqli

我正在处理删除品牌查询。如果品牌中有任何产品,它将不会删除,否则品牌将被删除。当使用没有产品的品牌时,它将被删除,但是当使用带有产品的品牌时,它会显示错误消息,指出无法删除,但是单击删除按钮后,删除页面上与该品牌相关的数据未显示。所有变量都不会被打印或回显任何东西,只是带有“删除”按钮和其他HTML代码的错误消息在那里。

<?php 
require_once('../auth.php');
require_once('../constants.php'); 
$errors = array();
$id = $_GET['id'];
$select = mysqli_query($conn,"SELECT * FROM brands Where `id` = '".$id."'");
$row = mysqli_fetch_array($select);
$brandname = $row['brand_name'];
if(!isset($_GET['id']))
{
    header("Location: http://localhost/php/brands/index.php");
}
if(isset($_POST['submit'])){
    $selectProducts = mysqli_query($conn,"SELECT * FROM `products` Where `brand_id` = '".$id."'");
    $select = mysqli_query($conn,"SELECT * FROM brands Where `id` = '".$id."'");
    $selectrow = mysqli_fetch_array($select);
    $brandName = $selectrow['brand_name'];
    if($row = mysqli_num_rows($selectProducts) > 0)
    {
        $errors[] = "Cannot Delete this brand, it has products in it.";     
    }
    else{
    $id = $_GET['id'];
    $sql ="DELETE FROM `brands` WHERE `brands`.`id` = '".$id."'";
    $result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
    if($result){
        echo $msg = $id." is deleted.";
        header("Location: http://localhost/wsp/php/brands/index.php");
        }
        else{
            $msg = $id." cannot be deleted.";
        }
    }
}
?>

表格是

<form method="post" action="delete.php?id=<?php echo $id; ?>">
    <h2 class="panel-title">Delete <?php echo $brandname; ?>?</h2>

    <div class="messages">
        <?php if($errors){
            foreach ($errors as $key => $value) {
                echo '<div class="alert alert-warning" role="alert">
                <i class="glyphicon glyphicon-exclamation-sign"></i>
                '.$value.'</div>';
            }
        }?>

    </div>
    <img src="<?php echo ASSETS;?><?php echo $row['brand_logo']; ?>" style="max-width:195px"/>
    <h2><?php echo strtoupper($row['brand_name']); ?></h2>
    <br><?php echo $row['brand_type']; ?><br><?php echo $row['status']; ?>
    <button type="submit" id="submit" name="submit"  class="btn btn-danger">Delete</button>
    <button name="reset" type="reset" class="btn btn-default">Cancel</button>
</form>

我想知道为什么查询说不能删除品牌后$ row ['']中的所有变量都显示为空?为什么不显示变量?

1 个答案:

答案 0 :(得分:1)

您的代码中发生了很多(坏)事情,但是我认为您的问题归结为:

true

在那里,您将false$row分配给if (mysqli_num_rows($selectProducts) > 0) { } else { $row = mysqli_fetch_array($selectProducts); } ,而不是行数据。您应该将其更改为

.

关于坏东西:

  1. 使用准备好的语句,而不要使用bindService() 运算符来构建查询。
  2. 使用正确的缩进,因此代码更具可读性。 (代码比书面更容易阅读。)
  3. 尝试结构好一点。一次只做一件事,而不是四件事交织在一起。