我怎么知道我的mysql_query更新是否实际上没有更新任何内容?

时间:2012-09-02 18:19:42

标签: php mysql insert sql-update

我正在对可能不存在的行的表进行更新。如果它不存在,我需要插入。我最初计划知道我需要根据update语句中的负返回值进行插入,但它不会返回任何负数。

我怎么知道更新没有做任何事情?做另一个查询,看看有什么吗?或者可能是之前的查询?

谢谢!

2 个答案:

答案 0 :(得分:5)

使用http://php.net/manual/en/function.mysql-affected-rows.php

  

通过与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());
?>

如果您使用的是mysqli而不是mysqlmysql已被弃用时间之前),则为mysqli_affected_rows

答案 1 :(得分:0)

如果表存在与否,只需mysql_affected_rows方法即可找出表中的更改。但是,对于优化代码,最好首先检查表存在,如:

$status = mysql_query("select * from table_name");
if($status==false){
   echo "table don't exists";
}
else{
  //do your stuff here
}