简体   繁体   English

如果其他表更新成功,则更新表

[英]Update table if other table update is successful

How can I update table2 in the below code only if the updation in table1 is success? 仅当成功更新table1时,才如何更新以下代码中的table2?

$sql="update table1 set col1='abc' where col2='1'";
$result=mysql_query($sql);
if(that is success)
{
    $sql="update table2 set col1='cde' where col2='1'";
    $result=mysql_query($sql);
}

See the mysql_affected_rows() function, which will return the number of rows just updated. 请参见mysql_affected_rows()函数,该函数将返回刚刚更新的行数。 Also, try to avoid using mysql_* functions in favor of mysqli_* or PDO, as they are now deprecated. 另外,请尝试避免使用支持mysqli_ *或PDO的mysql_ *函数,因为它们已被弃用。

First off, it is highly recommended to not use mysql_* functions as they are deprecated as of PHP v5.5.0 . 首先,强烈建议不要使用mysql_*函数,因为从PHP mysql_*开始推荐使用它们。

You can check directly with the $result variable 您可以直接使用$result变量进行检查

$result = mysql_query($sql);
if (!$result) {
    die('Update failed: ' . mysql_error());
} else {
    $sql="update table2 set col1='cde' where col2='1'";
    $result=mysql_query($sql);
}

if the above query is succeeded so the $result variable will have the number 1 as $result else it will have another value so simply you can test it like this 如果上面的查询成功完成,则$result变量的数字将为$result的数字为1,否则它将具有另一个值,因此您可以像这样简单地对其进行测试

if($result == 1)
 {
     //Your second update result
 }

Try this and tell me the result :) 试试这个,告诉我结果:)

手册指出,如果更新有效,则更新的返回值为true,否则为false,因此您可以继续检查$return的值以查看更新是否有效。

Do not use only $result as it will always be true as long as the query didnt cause an error. 不要只用$结果作为它永远是只要真正为查询didnt导致错误。 If the Where clause has no hits, nothing is updated and no error is caused. 如果Where子句没有命中,则不会更新任何内容,也不会引起错误。 So result would still be true. 因此结果仍然是正确的。

Use mysql_affected_rows as Alex suggested to know how many record have been updated. 根据Alex的建议使用mysql_affected_rows,以了解已更新了多少条记录。

So do if ($result && mysql_affected_rows() ) ... if ($result && mysql_affected_rows() ) ...

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

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