2014-11-23 46 views
0

我嘗試從合併表獲取存儲在由特定行SQL數據獲取數據的特定行由一個ID指定的合併表

這是我試過到目前爲止

<?php 
$id = $_GET['id']; 

$getdetails = mysql_query("SELECT 
scholarship.scholarshipid, 
scholarship.scholarshipname, 
scholarship.shortdescription, 
scholarship.scholarshippicture, 

scholarshipdetail.fulldescription, 
scholarshipdetail.degreetype, 
scholarshipdetail.location, 
scholarshipdetail.deadline 
FROM scholarship, scholarshipdetail 
WHERE scholarship.scholarshipid = scholarshipdetail.scholarshipid AND scholarship.scholarshipid = $id "); 

$retval = mysql_query($getdetails, $conn); 
if(! $retval) 
{ 
die('Could not get data: ' . mysql_error()); 
} 

?> 

該ID是從獲得theurl.php?id = IDNUMBER但事實證明,它無法獲取數據。如何從PHP中的ID號碼指定的行中獲取數據?

+2

當然你需要先取它。並停止使用mysql函數,並使用mysqli或PDO與準備語句來代替。 – Ghost 2014-11-23 07:01:33

+0

我刪除了'mysql_query',它可以工作。謝謝! – vinc 2014-11-23 07:38:30

回答

2

您試圖對其他mysql_query的結果執行mysql_query

我們假設您的SQL此刻是正確的,並且處理其餘的代碼。首先,您需要使用MySQLi或PDO,因爲不推薦使用mysql擴展名。所以在MySQLi中;

$mysqli = new mysqli('host', 'user', 'password', 'db'); // fill in your details 

$id = $_GET['id']; 
if($stmt = $mysqli->prepare("SELECT 
scholarship.scholarshipid, 
scholarship.scholarshipname, 
scholarship.shortdescription, 
scholarship.scholarshippicture, 
scholarshipdetail.fulldescription, 
scholarshipdetail.degreetype, 
scholarshipdetail.location, 
scholarshipdetail.deadline 
FROM scholarship, scholarshipdetail 
WHERE scholarship.scholarshipid = scholarshipdetail.scholarshipid 
AND scholarship.scholarshipid = ?")) { 

    $stmt->bind_param('i',$id); 
    $stmt->execute(); 
    $result = $stmt->get_result(); 
} 
else { 
    echo $mysqli->error; 
} 

while($row = $result->fetch_assoc()) { 
    // do stuff 
    // cols stored as $row['col_name']; 
} 

注意?在準備的SQL語句,其中$id了。這是變量的佔位符,然後與$stmt->bind_param('i',$id);i表示整數,s將用於字符串)綁定。然後,您必須執行結果並獲取結果集,然後才能對其執行任何操作。

如果您的SQL中有錯誤,那麼錯誤將被輸出到瀏覽器,並且查詢將不會執行。

希望這會有所幫助。

相關問題