2017-08-06 71 views
0

我知道這個問題早已被問過很多次,但沒有其他答案爲我工作。我在這條線的麻煩:PHP錯誤:「試圖獲取非對象的屬性」

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

我跟着一個教程,所以我不知道是否有任何其他信息,我應該提供

編輯:

繼承人整個文本文檔:

<?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']; 
    } 
?> 

初始化代碼

<?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"; 
?> 

錯誤上線7條,18

+1

'ID = '$ id''應該是'ID =' $ id.'' –

+2

你忘記添加數據庫名稱:/你的連接 – yoeunes

+0

您應該檢查query()的返回值是否調用「=== FALSE」。如果是這樣的話,你的查詢中可能會出現語法錯誤(例如傳入的用戶數據)。您可以嘗試打印整個查詢,以便查看正在查詢的內容。 – PhilMasterG

回答

2

你忘掉了數據庫名稱:

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

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

變化

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

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

也隨之變化:

if($row -> num_rows > 0) 

if($row->num_rows > 0) 
相關問題