简体   繁体   中英

understanding php die with mysql_error

I have 4 queries that run on a post. I've noticed that not all the queries are working if one of the first queries have no work to do.

Here are my queries

mysql_query("UPDATE invoice SET company='$company' WHERE company='$oldcompanyname'") or die(mysql_error());

mysql_query("UPDATE bill SET customer='$company' WHERE customer='$oldcompanyname'") or die(mysql_error());

mysql_query("UPDATE project SET customer='$company' WHERE customer='$oldcompanyname'") or die(mysql_error());

mysql_query("INSERT INTO activity_log (item, date) VALUES ('Customer Editted', NOW()) ") or die(mysql_error());

To give you an example, the first one runs ok. But the second one has no work to do because the data in the field does not exist. The third and the fourth should run but they do not.

I have always been accustomed to appending my queries with "or die(mysql_error());" but I'm thinking now that is not the best choice. But shouldn't the remaining queries run even if the one in the middle has no work to do?

If there is work to be done in all 4, then it works fine.

@HamZa DzCyberDeV is right, if one of your first queries fails, the die() call will stop the rest of your script from executing just like exit() . You are much better off removing the die statement and using if/else in cases where you need to run a query only if another one completes.

$result = mysql_query("UPDATE invoice SET company='$company' WHERE company='$oldcompanyname'");
if ($result !== false) {
   // do something here or execute the next query
}

Also, don't use mysql_* functions in new code Why shouldn't I use mysql_* functions in PHP? . They are no longer maintained and are officially deprecated https://wiki.php.net/rfc/mysql_deprecation . Learn about Prepared statements https://en.wikipedia.org/wiki/Prepared_statement instead, and use PDO http://php.net/pdo or MySQLi http://php.net/mysqli .

This sounds like you should just normalize your data. If you had your customer table linked based off of an ID, you could just do:

UPDATE `company` SET name='$new_name' WHERE company_id=$id

And then in your invoice/bill/project tables you would have a foreign key for company_id, instead of basing it off of company_name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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