【问题标题】:Error in php code in this cart code此购物车代码中的 php 代码错误
【发布时间】:2015-10-08 01:38:34
【问题描述】:

错误出现在我的代码中:-

<?php
session_start();
$page = 'index.php';
$connection = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
    die("not connected to db ".mysqli_connect_error());
}
function product()
{
     $sql = "select id,name,description,price from products where quantity > 0 order by id DESC" ;
     $result = mysqli_query($connection,$sql);
     if(mysqli_num_rows($result))
     {
         echo 'no products to display';
     }
     else
     {
         while($row = mysqli_fetch_assoc($result))
         {
             echo '<div class="boxed">'.$row['name'].'<br>'.$row['price'].'<br>'.$row['description'].'<br>'.'</div>';
         }
     }
}
?>
<html>
<head>
<title>
</title>
<script>
.boxed {
  border: 1px solid green ;
}
</script>
</head>
<body>
<?php
product();
?>
</body>
</html>

错误是:

注意:未定义的变量:连接在 /Applications/XAMPP/xamppfiles/htdocs/cart.php 在第 11 行

警告:mysqli_query() 期望参数 1 为 mysqli,给定 null 在 /Applications/XAMPP/xamppfiles/htdocs/cart.php 第 11 行

警告:mysqli_num_rows() 期望参数 1 为 mysqli_result, 在线 /Applications/XAMPP/xamppfiles/htdocs/cart.php 中给出的 null 12

警告:mysqli_fetch_assoc() 期望参数 1 为 mysqli_result, 在线 /Applications/XAMPP/xamppfiles/htdocs/cart.php 中给出的 null 18

【问题讨论】:

  • 您能就我的回答给我反馈吗? :) 也真的考虑使用单例方法。
  • 如果您发现它有用,请您给一个答案投票,并用勾号将其标记为已接受。如果你不知道怎么看tour

标签: php mysqli global-variables


【解决方案1】:

嗯,错误是正确的,$connection 不能从函数中访问。要使其在函数中可访问,您必须使用 global 关键字,如下所示:

function product()
{
    global $connection;
    ...
}

由于第一个错误,其他错误正在出现。这也在this 问题中得到了回答。

但这不是最佳实践,因为您可以无缘无故地多次连接到数据库。我建议您使用单例类,以确保您只打开一个与数据库的连接。这在this 答案中有描述。

【讨论】:

    【解决方案2】:

    第一个答案是正确的,或者您可以像这样将 $connection 传递给您的函数:

    <?php
    session_start();
    $page = 'index.php';
    $connection = mysqli_connect("localhost","root","","cart");
    function product($connection){
        $sql = "select id,name,description,price from products where quantity > 0 order by id DESC" ;
        $result = mysqli_query($connection,$sql);
        if(mysqli_num_rows($result))
        {
            echo 'no products to display';
        }
        else
        {
            while($row = mysqli_fetch_assoc($result))
            {
             echo '<div class="boxed">'.$row['name'].'<br>'.$row['price'].'<br>'.$row['description'].'<br>'.'</div>';
            }
        }
    }
    
    ...
    
    product($connection);
    

    【讨论】:

      猜你喜欢
      • 2021-07-02
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      相关资源
      最近更新 更多