为什么在PHP中出现“尝试获取非对象的属性”错误?

时间:2020-03-04 19:13:21

标签: php

我正在处理一个表格,您可以在其中更新数据库中学生的信息。

我一直收到此错误:

注意:试图在第54行的[...] / EditPersonalInfo.php中获取非对象的属性。

我知道这是一个常见的错误,但到目前为止,我发现的所有解决方案都无法解决我的问题。

这是我的代码:

// At the top of the page I also made sure to require_once my server.php file, so the database does connect

<?php 
        if (isset($_POST['update_personal'])) {

            $phone = trim($_POST['phoneNumber']);       
            $address = trim($_POST['address']); 
            $id = $_SESSION['id'];

            // The three variables above work when echoed.

            $query = "UPDATE StudentInfo SET PhoneNumber = $phone , Address = '$address' WHERE Student_ID = $id";

            // The above looks fine when echoed

            // The problem starts here
            $result = $conn->query($query);

            // Line 54
            if($result->num_rows == 1) {        

               // This was an attempt to set session variables when things didn't work. Nothing
               // in the database has changed though.
               while ($row = $result->fetch_assoc()){
                    $_SESSION['address'] = $row['Address'];
                    $_SESSION['phone'] = $row['PhoneNumber'];
                    }
            }

        }
    ?>

当我设置会话变量时,同样的方法也可以工作:

// When user submits login info.
    if (isset($_POST['login_user']))
    {
        // Get info from forms and trim white space, then save as variables.
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);

        // If no errors.
        if (count($errors) == 0) {

            // Select user info from server. 
            $query = "SELECT * FROM StudentInfo WHERE Username='$username' AND Password='$password'";

            $result = $conn->query($query);

            if($result->num_rows == 1) 
            {
            // Load user from server, send to home page

                while ($row = $result->fetch_assoc()){
                    $_SESSION['id'] = $row['Student_ID'];
                    $_SESSION['fname'] = $row['FirstName'];
                    $_SESSION['lname'] = $row['LastName'];
                    $_SESSION['dob'] = $row['DateOfBirth'];
                    $_SESSION['address'] = $row['Address'];
                    $_SESSION['email'] = $row['EmailAddress'];
                    $_SESSION['due'] = $row['AmountDue'];
                    $_SESSION['phone'] = $row['PhoneNumber'];
                    $_SESSION['emergency'] = $row['EmergencyContact_ID'];
                    $_SESSION['coursesid'] = $row['CourseList_ID'];
                    $_SESSION['res'] = $row['Residency_ID'];
                    $_SESSION['user'] = $row['Username'];
                    $_SESSION['pass'] = $row['Password'];

                }

            header('location: home/home.php');
            }
        }
    }

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:-1)

问题在于$result->num_rows使用rowCount

因此正确的代码将是

    if($result->rowCount() == 1)