2012-11-11 32 views
0

我想寫使用PDO選擇使用使用PHP MySQL的其中PDO

function getRec($id=0) 
{ 
    ($id==0?$addQuery="":$addQuery=" where id =".$id); 
    $statement = $dbh->prepare("select * from TCMS :name order by id"); 
    $statement->execute(array(':name' => $addQuery)); 
    $row = $statement->fetchAll(); 
    return $row ; 
} 

在PHP和MySQL的函數來選擇PHP和MySQL的價值觀,我得到錯誤

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' where id =2' order by id' at line 1' in /Applications/XAMPP/xamppfiles/htdoc

實際上什麼我試圖

如果值(2)ID傳遞則說明會

select * from TCMS where id=2 order by id 

如果ID = 0,則select語句將

select * from TCMS order by id 

我是新來的PDO和不知道確切的語法。

該怎麼辦?

+3

你不能那樣做。佔位符不是任意插入SQL的字符串,它們只能用於像'WHERE something =:placeholder'這樣的參數 –

+0

親愛的@Michael Berkowski感謝您的回覆,那麼如何解決這個問題?我需要此 – air

+0

的幫助,請參閱下面的答案。 –

回答

3

而是執行此操作:

function getRec($id=0) 
{ 
    //($id==0?$addQuery="":$addQuery=" where id =".$id); 
    if ($id == 0) 
    { 
     $statement = $dbh->prepare("select * from TCMS order by id"); 
     $statement->execute(); 
    } 
    else 
    { 
     // Notice the SQL string has changed. Placeholder :name now properly takes the place of a SQL value. 
     $statement = $dbh->prepare("select * from TCMS where id = :name order by id"); 
     $statement->execute(array(':name' => $id)); 
    } 

    $row = $statement->fetchAll(); 
    return $row ; 
} 

你在做什麼錯的是你試圖結合並與佔位符任意字符串值,這是不是佔位符是什麼執行的SQL。

佔位符將被設置在值的位置(不是表名或其他),以便在執行過程中傳入的值可以由PDO在內部正確處理以進行正確的轉義。

我寫的函數應該有助於創建有效的SQL。

2

如果您需要動態添加WHERE子句,請首先構造SQL字符串,然後prepare()它。如果符合條件添加參數,則必須有條件地將相應的佔位符/值對添加到傳遞到​​的數組中。

無法將佔位符綁定爲任意的SQL字符串。

// Array to pass into execute() 
$values = array(); 

// Start your SQL... 
$sql = "SELECT * FROM TCMS"; 
// Add the WHERE clause if $id is not zero 
if ($id !== 0) { 
    $sql .= " WHERE id=:name "; 
    // And add the placeholder into the array 
    $values[':name'] = $id); 
} 
// add the ORDER BY clause 
$sql .= " ORDER BY id"; 

// Prepare the statement 
$statement = $dbh->prepare($sql); 

$statement->execute($values); 
// fetch, etc...