2014-11-23 65 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中有错误,那么错误将被输出到浏览器,并且查询将不会执行。

希望这会有所帮助。