简体   繁体   中英

PHP error: “Trying to get property of non-object”

I know this question has been asked alot of times earlier, but none of the other answers worked for me. I'm having trouble on this line:

$row = $conn->query("SELECT * FROM urls WHERE id = '$id'");

I followed a tutorial so I don't know if there is any other information that I should provide

EDIT:

heres the whole text document:

<?php  

    function idExists($id){
        include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
        $row = $conn->query("SELECT * FROM urls WHERE id = '.$id'");

        if($row -> num_rows > 0){
            return true;
        } else {
            return false;
        }
    }

    function urlHasBeenShortened($url){
        include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
        $row = $conn->query("SELECT * FROM urls WHERE link_to_page = '$url'");

        if($row->num_rows > 0){
            return true;
        } else {
            return false;
        }
    }

    function getURLID($url){
        include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
        $row = $conn->query("SELECT id FROM urls WHERE link_to_page = '$url'");

        return $row->fetch_assoc()['id'];
    }

    function insertID($id, $url){
        include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
        $conn->query("INSERT INTO urls (id, link_to_page) VALUES ('$id', '$url')");

        if(strlen($conn->error) == 0){
            return true;
        }
    }

    function getUrlLocation($id){
        include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
        $row = $conn->query("SELECT link_to_page FROM urls WHERE id = '$id'");

        return $row->fetch_assoc()['link_to_page'];
    }
?>

Init code

    <?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

errors on lines: 7, 18

you did forget the database name :

$conn = new mysqli($servername, $username, $password);

// Create connection like this :
$conn = new mysqli($servername, $username, $password, $dbname);

change

$row = $conn->query("SELECT * FROM urls WHERE id = '$id'");

to

$row = $conn->query("SELECT * FROM urls WHERE id = ".$id);

also change :

if($row -> num_rows > 0)

to

if($row->num_rows > 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM