2012-09-02 59 views
0

我正在做一个可能不存在的行的表的更新。如果它不存在,我需要做一个插入。我最初计划知道我需要根据update语句中的负面返回值执行插入操作,但它不会返回任何负面消息。如何知道我的mysql_query更新是否实际上没有更新?

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

谢谢!

+3

正如[简介](http://www.php.net/manual/en/intro.mysql.php)中所述有关'mysql_ *'函数的PHP手册章节:*不推荐使用此扩展名编写新代码。相反,无论是[mysqli](http://www.php.net/manual/en/book.mysqli.php)还是[PDO_MySQL](http://www.php.net/manual/en/ref.pdo应该使用-mysql.php)扩展名。另请参阅[MySQL API概述](http://www.php.net/manual/en/mysqlinfo.api.choosing.php),以便在选择MySQL API时获得进一步的帮助。 – eggyal

回答

5

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

上一条INSERT,UPDATE获取受影响的行数,替换或删除与link_identifier关联的查询。

<?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

0

只需mysql_affected_rows方法是在表中存在或不存在的情况下找出表中变化的方法。但是,对于优化代码更好地检查第一个表是否存在,如:

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