[英]How can I know if my mysql_query update didn't actually update anything?
I am doing an update to a table for a row that may not exist. 我正在对表中可能不存在的行进行更新。 If it doesn't exist, I need to do an insert.
如果不存在,则需要插入。 I was initially planning on knowing that I needed to do an insert based on a negative return value from the update statement, but it isn't returning anything negative.
我最初计划是要知道我需要根据update语句的负返回值进行插入,但是它没有返回负数。
How can I know that the update didn't do anything? 我怎么知道更新没有做任何事情? Do another query seeing if anything is there?
是否执行另一个查询以查看是否存在任何内容? Or maybe a query before?
还是以前的查询?
Thanks! 谢谢!
Use http://php.net/manual/en/function.mysql-affected-rows.php 使用http://php.net/manual/en/function.mysql-affected-rows.php
Get the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE query associated with link_identifier.
通过与link_identifier关联的最后一个INSERT,UPDATE,REPLACE或DELETE查询获取受影响的行数。
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* this should return the correct numbers of deleted records */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
/* with a where clause that is never true, it should return 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?>
If you're using mysqli
instead of mysql
( mysql
was deprecated a long time ago), it's mysqli_affected_rows
. 如果您使用的是
mysqli
而不是mysql
( 很久以前不建议使用mysql
), mysqli_affected_rows
。
Simply mysql_affected_rows
method is the way to find out the change in table in both case if table exist or not. 不论表是否存在,简单地使用
mysql_affected_rows
方法是找出表中更改的方法。 However, for optimized code better to check first for table existence like: 但是,对于优化的代码,最好先检查表是否存在,例如:
$status = mysql_query("select * from table_name");
if($status==false){
echo "table don't exists";
}
else{
//do your stuff here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.