MySQL(PDO)中的基本选择和删除

时间:2013-10-11 19:13:34

标签: php mysql sql pdo

我有以下基本查询从表中选择PIN,将其绑定到变量,然后从表中删除它。

$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语句来捕获错误?

2 个答案:

答案 0 :(得分:1)

您的DELETE语法中存在语法错误。 LIMIT没有DELETE的偏移量参数。

答案 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 )