duanju9104 2013-04-17 23:32
浏览 24
已采纳

将对象作为参数传递给函数不工作[关闭]

This seems extremely easy but for the life of me can't figure out why this is not working. I am trying to simply pass an object into a function but I get this error:

Catchable fatal error: Argument 3 passed to write_query() must be an instance of mysqli, null given, called in C:\xampp\htdocs\CSP\login\login.php on line 28 and defined in C:\xampp\htdocs\CSP\php_scripts\login_script.php on line 40

These are my functions definitions:

function conn_database()
    {
        if (!empty($_POST['userid']) && !empty($_POST['password']))
        {
            $conn = new mysqli('localhost', 'root', '', 'csp');

            if (mysqli_connect_errno()) 
            {
                echo 'Connection to database failed:'.mysqli_connect_error();
                exit();
            }
            return $conn;
        }

    }


function write_query($userid, $password, mysqli $conn)
    {
        $query = 'select * from authorized_users '
        ."where userid= '$userid'"
        ."and password_id='$password'";
        $result = $conn->query($query);
        return $result;
    }

I am calling them like this:

$conn = conn_database();
$result = write_query($userid, $password, $conn);

I'm type hinting in the definition of the write_query() but from what I understand from the error, my third argument is not considered an instance of mysqli. (I am aware I should be salting the password and all, I'm just trying to get this to work first). Any suggestions would be appreciated

  • 写回答

1条回答 默认 最新

  • duanjiong5023 2013-04-17 23:35
    关注

    Your third paramater is not an instance of mysqli. It is null. This is because your get_connection function is not returning anything.

    Why are you checking for this:

    if (!empty($_POST['userid']) && !empty($_POST['password']))
    

    This means you code will only try and connect to the SQL server if you provide it with post data for userid and password only. If this is the behaviour you want, you should put the if statement outside the function, something like this:

    if (!empty($_POST['userid']) && !empty($_POST['password']))
      $conn = conn_database();
      $result = write_query($userid, $password, $conn);
    }
    

    although it seems that userid and password aren't set, regardless. Make sure to check the name attribute on your inputs and do a var_dump($_POST) to see whats being posted to your script.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化