2013-10-11 21 views
0

我有以下基本查詢從表中選擇一個PIN,將它綁定到一個變量,然後從表中刪除它。MySQL中的基本選擇和刪除(PDO)

$sth = $this->db->query("SELECT available_pins FROM pin_list ORDER BY RAND() LIMIT 0,1 ;"); 
$pinarray = $sth->fetch(); 
$this->user_pin = $pinarray->available_pins; 

$sth = $this->db->prepare("DELETE FROM pin_list WHERE available_pins = ? LIMIT 0,1"); 
$sth->execute(array($this->user_pin)); 

我的問題:PIN被選中並且回聲良好,但它不會從表格中刪除。我究竟做錯了什麼?

此外,如何最好地添加一條if語句來在這兩種情況中的每一種情況下捕獲錯誤?

+0

除非你設置PDO到​​異常模式,它會返回布爾值false失敗的操作,所以,'$ result = $ sth-> execute(..)或die($ this-> db :: errorInfo)'應該有所幫助。 –

回答

1

您的DELETE語法中有語法錯誤。 LIMIT沒有DELETE的偏移參數。

+0

謝謝,什麼是正確的語法? – alias51

+0

@ alias51剛剛離開偏移量。 'LIMIT 1' –

0

選擇元組時,展開它以包含PK。將屬性綁定到變量後,可以通過使用PK限定where子句來刪除元組。

這裏是一個例子。唉,這個例子是用程序化的PHP編寫的,我現在還沒有編寫OO-php。對於那個很抱歉。儘管如此,我認爲主要想法是傳達出來的。請不要讓我知道。

鑑於該數據庫是這樣的:

CREATE TABLE `pin_list` (
`id` INT(11) NOT NULL AUTO_INCREMENT , 
`available_pins` CHAR(8) NOT NULL , 
`aux` VARCHAR(14) NOT NULL , 
PRIMARY KEY (`id`) 
) ENGINE = MYISAM ; 

mysql> select * from pin_list; 
+----+----------------+-----+ 
| id | available_pins | aux | 
+----+----------------+-----+ 
| 1 | 43236543  | f | 
| 2 | 43236523  | f | 
| 3 | 43266523  | f | 
| 4 | 48266523  | f | 
| 5 | 48264823  | f | 
+----+----------------+-----+ 
5 rows in set (0.00 sec) 

的PHP腳本可以這樣寫:

mysql_connect('mysql_server','user-id','pwd'); 
mysql_select_db('database-name'); 

//Select the available pin and its PK. 
$query = "SELECT id, available_pins FROM pin_list ORDER BY RAND() LIMIT 0,1"; 

$rs = mysql_query($query); 

//Select id and available_ping into an array 
$pinarray = mysql_fetch_array($rs); 

echo "The pin: " . $pinarray[1]; //Do something with it 

//Save the primary key (PK, here: the id-attribute) for use in delete statement 
$pk = $pinarray[0]; 

//Now: delete the pin that you have fetched from the database 
echo "DELETE FROM pin_list WHERE id = " . $pk; //echo to debug sql-statements in php. 
//Uncomment to delete 
//$del_qry = "DELETE FROM pin_list WHERE id = " . $pk; 
//mysql_query($del_qry) 
+0

請提供更多代碼 – Zim84