【问题标题】:Shopping cart in php (mysql_num_rows)php 中的购物车 (mysql_num_rows)
【发布时间】:2015-06-03 10:03:00
【问题描述】:

我正在尝试用 php 做一个购物车。

我收到以下错误

“警告:mysql_num_rows() 期望参数 1 是资源,第 19 行 C:\wamp\www\shoppingCart\cart.php 中给出的字符串”并且返回没有产品。

代码中的错误在第19行:

if(mysql_num_rows($get)==0)[
<?php
  session_start();
  $page='index.php';
  $server="localhost";
  $username="root";
  $password="";
  $database="jennifer_db";
  $conn = new mysqli($server, $username, $password, $database);

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

  function products(){
    $get='mysql_query("select Product_ID, Product_name, Product_desc,
        Product_price from products where quantity>0 order by id desc")';

    if(mysql_num_rows($get)== 0){
      echo "There ae no products to display!";
    }
    else{
    echo "Success!";
    }
  }
?>

【问题讨论】:

  • 您正在使用mysqli,但您想使用mysql_num_rows
  • if(mysql_num_rows($get)==0)[ 你有“[”而不是“{”作为第一个错误
  • 奇怪的是,您正在运行此代码并且它不应该返回任何产品错误。尝试发布您的完整代码。

标签: php cart shopping


【解决方案1】:

您正在混合使用 mysqlimysql 函数。请使用mysqliPDO

【讨论】:

    【解决方案2】:

    我对你的代码做了一些修改(我使用了 mysqli),我认为它应该可以工作,查看 cmets:

    session_start();
    
    $page = 'index.php';
    $server = 'localhost';
    $username = 'root';
    $password = '';
    $database = 'jennifer_db';
    
    // this is the connection object
    $mysqli = new mysqli($server, $username, $password, $database);
    
    // if we have an error we abort
    if ($mysqli->connect_errno)
      die('Connection failed: ' . $mysqli->connect_error);
    
    
    function products(&$conn)
    {
        // we pass $conn to this function and make the query
        // note that only the SQL query string should be in ""
        $result = $conn->query("select Product_ID, Product_name, Product_desc, Product_price from products where quantity > 0 order by id desc");
    
        if ($result)
        {
            // checking row count
            echo (!$result->num_rows ? 'There are no products to display!' : 'Success');
    
            // we close the result set
            $result->close();
        }
        else 
            echo "Error: {$conn->error}";
    }
    
    // call products() here
    products($mysqli);
    
    // we close the connection
    $conn->close();
    

    有关 mysqli 的更多信息,请查看http://php.net/manual/en/book.mysqli.php

    还可以查看 PDO 并决定要使用哪一个(mysqli 或 PDO) http://php.net/manual/en/book.pdo.php

    我认为您也可以从中学习: http://davidwalsh.name/php-shorthand-if-else-ternary-operators

    希望我能帮上忙。 :)

    【讨论】:

    • 注意:试图在第 25 行获取 C:\wamp\www\shoppingCart\cart.php 中非对象的属性
    • 致命错误:在第 28 行调用 C:\wamp\www\shoppingCart\cart.php 中非对象的成员函数 close()
    • 我更新了我的答案并添加了“错误处理”。请立即检查。 :)
    猜你喜欢
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 2012-04-10
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    相关资源
    最近更新 更多