MySQL ROW_COUNT()不起作用

时间:2014-06-08 13:14:29

标签: mysql

我有这个问题:

DELETE FROM c_email WHERE code = '67890' AND user_id = '2';
SELECT ROW_COUNT() AS row_1;

我想获得一个名为row_1的字段,删除行数,但似乎无效......

3 个答案:

答案 0 :(得分:2)

您可以使用已删除的$mysqli->affected_rows;,如this document

所示
  

返回值:大于零的整数表示受影响或检索的行数。零表示没有为UPDATE语句更新记录,没有与查询中的WHERE子句匹配的行或者尚未执行任何查询。 -1表示查询返回错误。

来自同一website的一个小例子。

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);

$mysqli->query("ALTER TABLE Language ADD Status int default 0");

/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);

/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);

/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);

$result->close();

/* Delete table Language */
$mysqli->query("DROP TABLE Language");

/* close connection */
$mysqli->close();
?>

答案 1 :(得分:1)

这是使用PDO。

假设您可以进行一些研究,请设置PDO连接并确保指定此选项:

$db = new PDO ($dsn,$user,$pass,array (
  PDO::ATTR_EMULATE_PREPARES=>TRUE,
));

然后,准备并执行你的陈述。 我不知道任何实际选择已删除行的mysql命令。你必须去rowCount()

$stmt = $db->prepare("DELETE FROM c_email WHERE code = '67890' AND user_id = '2'");
$stmt->execute();
$count = $stmt->rowCount();

但你想在同一个电话中选择第二个查询,所以我们会通过正常选择现有行来做到这一点

$stmt = $db->prepare(
 'UPDATE c_email SET code=1376 WHERE user_id=3;
  SELECT user_id FROM c_email WHERE code=1376;'
);
$stmt->execute(); // this executes both statements, and sets some internal pointer towards the first.
$stmt->nextRowset(); // it's the next one that interests us
$row = $stmt->fetch(PDO::FETCH_ASSOC); // let's get the value
echo $row['user_id'];

答案 2 :(得分:1)

开始交易;
SELECT @before:=(SELECT count()FROM c_email);
从c_email删除WHERE代码=&#39; 67890&#39; AND user_id =&#39; 2&#39;;
SELECT @after:=(SELECT count(
)FROM c_email);
COMMIT;
在AS DELETED之后选择@ before- @;