【问题标题】:Argument 1 passed to must be an instance of int, integer given传递给的参数 1 必须是 int 的实例,给定整数
【发布时间】:2017-01-20 19:29:17
【问题描述】:

我刚刚开始学习php,并以http://www.mysqltutorial.org/php-calling-mysql-stored-procedures/为例。

但是当我尝试运行时出现错误“传递给的参数 1 必须是 int 的实例,给定整数...”:

   <?php

    require_once 'dbconfig.php';

    /**
     * Get customer level
     * @param int $customerNumber
     * @return string
     */
    function getCustomerLevel(int $customerNumber) {
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

            // calling stored procedure command
            $sql = 'CALL GetCustomerLevel(:id,@level)';

            // prepare for execution of the stored procedure
            $stmt = $pdo->prepare($sql);

            // pass value to the command
            $stmt->bindParam(':id', $customerNumber, PDO::PARAM_INT);

            // execute the stored procedure
            $stmt->execute();

            $stmt->closeCursor();

            // execute the second query to get customer's level
            $row = $pdo->query("SELECT @level AS level")->fetch(PDO::FETCH_ASSOC);
            if ($row) {
                return $row !== false ? $row['level'] : null;
            }
        } catch (PDOException $e) {
            die("Error occurred:" . $e->getMessage());
        }
        return null;
    }

    $customerNo = 103;
    echo sprintf('Customer #%d is %s', $customerNo, getCustomerLevel($customerNo));

在我看来 IN 参数的定义为 int 已经完成。你能给我一些提示吗?

【问题讨论】:

  • 听起来你正在运行一个
  • 所以只需在此处删除int 表单:getCustomerLevel(int $customerNumber)
  • 如果可以的话,升级到 PHP 7。如果您只是学习,不妨学习最新版本。
  • 我会争辩说,除非您在示例代码中定义它(不太可能)或类型转换它,否则无论如何传递时它将是一个字符串(来自$_POST,DB 等,所以为什么要强制int 在这里?

标签: php mysql


【解决方案1】:

仅 PHP 7.0.0 支持标量类型(bool、int、float、string)的类型提示/声明。

参见PHP manual / Function argumentsthis answer to similar question

【讨论】:

    【解决方案2】:

    无需在 PHP 中输​​入提示参数。不过,您可以在某些情况下使用类型提示(它对类非常有用)。 在您的情况下,PHP 需要一个未定义的 int 类的实例。可以使用is_int函数来检查传入的参数是否为整数

    【讨论】:

    • 只需从函数调用中删除 int,并在函数的开头使用 if 语句来确定传递的参数是否为整数。如果不是,您可以返回错误(或 null,因为这是您在函数中进一步返回的内容)
    • 我以为您可能是这个意思,所以我这样做了,但现在看起来所有带有连接字符串的变量都无法识别:主机、数据库名、用户名和密码。而且连接没问题。
    • 在代码 sn-p 中提供这些变量未定义。起初您没有收到此错误,因为由于参数错误导致函数无法初始化,这意味着函数中的代码没有运行。现在参数错误消失了,函数内部的错误确实出现了。
    • 我不认为这种情况,在同一个网页中还有另一个调用存储过程示例(虽然没有输入我们的输出参数),并且连接的变量设置完全一样,我跑了那个.php没有任何问题。
    • 好的,明白了。dbconfig.php 不知何故不适用于此脚本。所以我尝试设置$dsn、$username 和$password,并再次定义$pdo,现在它可以正常工作了。但是,是的,我删除了 typehint。非常感谢您的帮助
    【解决方案3】:

    你可以用这个替换参数绑定:

      $stmt->bindParam(':id', $customerNumber);
    

    在这种情况下不需要第三个参数。

    【讨论】:

    • 这可能是真的,但问题与此无关。
    猜你喜欢
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2016-08-10
    • 2013-11-23
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多