php - 试图获取非对象的属性 - PHP

标签 php mysql sql

所以我试图获取与用户输入的教师名字和姓氏相对应的teacher_id,但是当我尝试获取teacher_id它输出 Trying to get property of non-object。有人有什么想法吗?

PHP

<?php

// PROCESSES STUDENT INFO

// get connect page
require '../../connect.php';

// get input info
$student_id = $_POST['student_id'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$teacher_first_name = $_POST['teacher_first_name'];
$teacher_last_name = $_POST['teacher_last_name'];

// check if input is not empy
if(!empty($student_id) && !empty($first_name) && !empty($last_name) && !empty($teacher_first_name) && !empty($teacher_last_name)) {

    // check if numeric inputs have a number
    if(is_numeric($student_id)) {
        $teacher_check = mysqli_query($link, "SELECT teacher_id FROM teachers WHERE first_name='$teacher_first_name' AND last_name='$teacher_last_name'");

        // check if teacher exists
        if($teacher_check) {
            $row = $teacher_check->fetch_object();

            $result = mysqli_query($link, "INSERT INTO students (student_id, first_name, last_name, teacher_id) VALUES ($student_id, '$first_name','$last_name', $row->teacher_id)");

            if($result) {
                header("Location: ../../../admin.php?message=Success!");
            } else {
                echo mysqli_error($link);
                // header("Location: ../../../admin.php?message=Sorry we ran into an error");
            }
        } else {
            header("Location: ../../../admin.php?message=Teacher Does Not Exist");
        }
    } else {
        header("Location: ../../../admin.php?message=Please add a number for Student ID");
    }

} else if (empty($student_id) || empty($first_name) || empty($last_name)) {
    header("Location: ../../../admin.php?message=Please add you're input values");
}

?>

最佳答案

改变这一行,你正在检查查询是否正常,但你还没有检查它是否有任何结果。

if($teacher_check) {
        $row = $teacher_check->fetch_object();

到(这一行检查你是否有任何结果数据,如果你有结果数据,你有它 $row 否则为空)

if($row = $teacher_check->fetch_object()){

关于php - 试图获取非对象的属性 - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43024551/

相关文章:

MySQL 计算当前连胜的连续日期

php - 根据 mysql 数据库项目的选择禁用输入字段

php ssh 回显 $!不显示真实的 pid

php - Laravel phpunit 测试获取带参数

mysql - 为什么内部 ORDER BY 不起作用?

sql - 如何在 SQL CREATE TABLE 中使用常量?

php - 当 session ID 已知但无法启动 session 时删除 session 变量

php - 在数据库 PHP/MySQL 中查找类似的描述

MySql 插入、删除、更新的持续时间

具有不同记录的 SQL 增量计算