2012-09-02 58 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 
} 
相關問題