2012-10-11 71 views
0

我是pdo的新手,並且有點爭鬥。php pdo使用變量顯示mysql查詢的輸出

我想使用mysql查詢的結果填充表。該查詢將返回基於所述可變

具有以下功能的單個結果:

function get_editusers($db){  
    try { 
     $result = $db->query("SELECT firstname, middlename,surname,fullname,gender, birthdate,homelanguage,department,employeetype,employeestatus,idnumber FROM Persons where employeeid= :empid"); 
     return $result; 
    } catch(PDOException $ex) { 
     return $ex; 
    } 
} 

$useredit= get_editusers($db); 

我然後使用以下方法來輸出的值:

while($row = $useredit->fetch(PDO::FETCH_ASSOC)) 
{ 
echo $row['firstname']; 
echo $row['middelname']; 
echo $row['surname']; 
} 

然而這產生一個空白結果沒有錯誤。

我該如何糾正這個sytnax?此外,我需要更改語法以將變量綁定到可信的$ employeeid。

這是獲取和輸出mysql查詢結果的正確和最好的方法,輸出單個記錄?如果不是,請你可以提供一個可行的例子。

由於提前,

+0

道歉,更正的問題。 – Smudger

回答

1

您使用的參數:empid在你的查詢,你必須通過該參數的值。沒有值意味着一個空的結果集。

使用綁定參數時,必須準備查詢,綁定參數,然後執行查詢。

function get_editusers($db, $id){  
    try { 
    $result = $db->prepare(" 
    SELECT firstname, middlename,surname,fullname,gender, 
    birthdate,homelanguage,department,employeetype,employeestatus,idnumber 
    FROM Persons where employeeid= :empid"); 

    $result->bindParam(':empid', $id, PDO::PARAM_INT); 
    $result->execute();   
    return $result; 
} 
    catch(PDOException $ex) { 
    return $ex; 
    } 
} 
+0

謝謝JvdBerg,你能幫我一個代碼片段,需要一些指導嗎?謝謝, – Smudger

+0

謝謝JvdBerg,我更新了代碼,除了將變量$ id更改爲$ employeeid以適合我的代碼。我現在得到錯誤:'缺少get_editusers()的參數2 ...'任何建議。謝謝 – Smudger

+1

你還必須改變這個調用:'$ useredit = get_editusers($ db,$ id);' – JvdBerg

1

您必須在執行查詢之前綁定參數:empid。

$sth = $dbh->prepare("SELECT firstname, middlename FROM Persons where employeeid= :empid"); 
$sth->bindParam(':empid', $emp_id, PDO::PARAM_INT); 
$sth->execute(); 
$row = $sth->fetch(); 
echo $row['firstname']; 
+0

謝謝surffan,這種方法比JvdBerg在下面建議的更好嗎? – Smudger

+1

正如JvdBerg所說,它與PHP文檔中顯示的方法相同http://www.php.net/manual/de/pdostatement.bindparam.php – surffan