简体   繁体   English

如何在运行SQL查询之前检查受影响的行?

[英]How to check affected rows before an sql query running?

Consider a table with some rows. 考虑一个带有一些行的表。 by php, I make a SQL query such as "DELETE * From my_table". 通过php,我进行了SQL查询,例如“ DELETE * From my_table”。 How can I recognize affected rows before running the sql query. 如何在运行sql查询之前识别受影响的行。 On the other words, I want to have the list of affected rows after an sql query and before of its running. 换句话说,我想在sql查询之后和运行之前获得受影响的行的列表。

All in all, I want to check somethings before running SQL irreversible queries. 总而言之,我想在运行SQL不可逆查询之前先进行检查。

best respects. 最好的尊重。

You can perform a SELECT query with the same JOIN and WHERE criteria as the DELETE would use. 您可以使用与DELETE相同的JOINWHERE条件执行SELECT查询。 This will return the rows that would have been deleted. 这将返回本应删除的行。

If you want perfect safety, you need to use transactions in all the applications that access the tables. 如果想要完美的安全性,则需要在访问表的所有应用程序中使用事务。 The process that's doing the DELETE should perform the SELECT in the same transaction. 正在执行DELETE的进程应在同一事务中执行SELECT Otherwise, another process could add rows to the table between the SELECT and DELETE , and they might be deleted if they meet the criteria. 否则,另一个过程可能会在SELECTDELETE之间向表中添加行,如果满足条件,则可能会删除它们。

If you're just trying to verify the logic of your DELETE query with an eyeball examination of the results, this may be overkill. 如果您只是通过仔细检查结果来验证DELETE查询的逻辑,那么这可能是过大了。

Suppose you have a DELETE query like: 假设您有一个DELETE查询,例如:

DELETE FROM my_table WHERE foo='bar'

To see how many records will be deleted you could first run: 要查看将删除多少条记录,可以先运行:

SELECT count(*) from my_table where foo='bar'

The result of that query will be the count of records that meet the same condition. 该查询的结果将是满足相同条件的记录数。

You can use SELECT and then mysqli_affected_rows to get the number of rows about to get deleted. 您可以使用SELECT,然后使用mysqli_affected_rows来获取要删除的行数。 If you want data from the rows as well then you fetch it with SELECT. 如果您还希望从行中获取数据,则可以使用SELECT获取数据。

在您的发言之前添加解释

1) Create a function that analyzes the rows: 1)创建一个分析行的函数:

function checkRows($table){
    $query = 'SELECT * FROM ' . $table;

    // execute SELECT query
    // get the result
    // using for loop, set $delete boolean based on whether to delete or not

    return $delete;
}

2) Create a function that deletes the stuff: 2)创建一个删除内容的函数:

function deleteFromTable($table){
    $query = 'DELETE FROM ' . $table;

    // execute DELETE query
}

3) Create conditional calls: 3)创建条件调用:

$table = 'SomeTable';
$validDelete = checkRows($table);

if($validDelete){
    deleteFromTable($table);
}

This will allow you to perform validation of records prior to deletion. 这将允许您在删除之前执行记录验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM