PHP Try and Catch for SQL Insert
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1918624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Try and Catch for SQL Insert
提问by meme
I have a page on my website (high traffic) that does an insert on every page load.
我的网站上有一个页面(高流量),它在每个页面加载时插入。
I am curious of the fastest and safest way to (catch an error) and continue if the system is not able to do the insert into MySQL. Should I use try/catch or die or something else. I want to make sure the insert happens but if for some reason it can't I want the page to continue to load anyway.
我很好奇最快和最安全的方法(捕获错误)并在系统无法插入 MySQL 时继续。我应该使用 try/catch 还是 die 或其他什么。我想确保插入发生,但如果由于某种原因它不能,我希望页面仍然继续加载。
...
$db = mysql_select_db('mobile', $conn);
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'") or die('Error #10');
mysql_close($conn);
...
回答by Yacoby
Checking the documentationshows that its returns falseon an error. So use the return status rather than or die(). It will return false if it fails, which you can log (or whatever you want to do) and then continue.
检查文档显示其返回false错误。所以使用返回状态而不是or die(). 如果失败,它将返回 false,您可以记录(或任何您想做的事情)然后继续。
$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
//handle the error here
}
//page continues loading
回答by vkGunasekaran
This can do the trick,
这可以解决问题,
function createLog($data){
$file = "Your path/incompletejobs.txt";
$fh = fopen($file, 'a') or die("can't open file");
fwrite($fh,$data);
fclose($fh);
}
$qry="INSERT INTO redirects SET ua_string = '$ua_string'"
$result=mysql_query($qry);
if(!$result){
createLog(mysql_error());
}
回答by Nemoden
You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:
您可以自行实现对 mysql 查询失败的抛出异常。您需要为 mysql_query 函数编写一个包装器,例如:
// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;
// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}
function my_mysql_query($query, $conn=false) {
$res = mysql_query($query, $conn);
if (!$res) {
$errno = mysql_errno($conn);
$error = mysql_error($conn);
switch ($errno) {
case MYSQL_DUPLICATE_KEY_ENTRY:
throw new MySQLDuplicateKeyException($error, $errno);
break;
default:
throw MySQLException($error, $errno);
break;
}
}
// ...
// doing something
// ...
if ($something_is_wrong) {
throw new Exception("Logic exception while performing query result processing");
}
}
try {
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
// duplicate entry exception
$e->getMessage();
}
catch (MySQLException $e) {
// other mysql exception (not duplicate key entry)
$e->getMessage();
}
catch (Exception $e) {
// not a MySQL exception
$e->getMessage();
}
回答by engvrdr
if you want to log the error etc you should use try/catch, if you dont; just put @ before mysql_query
如果你想记录错误等,你应该使用 try/catch,如果你不这样做;只需将@ 放在mysql_query 之前
edit : you can use try catch like this; so you can log the error and let the page continue to load
编辑:您可以像这样使用 try catch;这样您就可以记录错误并让页面继续加载
function throw_ex($er){
throw new Exception($er);
}
try {
mysql_connect(localhost,'user','pass');
mysql_select_db('test');
$q = mysql_query('select * from asdasda') or throw_ex(mysql_error());
}
catch(exception $e) {
echo "ex: ".$e;
}
回答by Anonymous
Elaborating on yasaluyari's answer I would stick with something like this:
详细说明yasaluyari's answer 我会坚持这样的事情:
We can just modify our mysql_query as follows:
我们可以修改我们的 mysql_query 如下:
function mysql_catchquery($query,$emsg='Error submitting the query'){
if ($result=mysql_query($query)) return $result;
else throw new Exception($emsg);
}
Now we can simply use it like this, some good example:
现在我们可以像这样简单地使用它,一些很好的例子:
try {
mysql_catchquery('CREATE TEMPORARY TABLE a (ID int(6))');
mysql_catchquery('insert into a values(666),(418),(93)');
mysql_catchquery('insert into b(ID, name) select a.ID, c.name from a join c on a.ID=c.ID');
$result=mysql_catchquery('select * from d where ID=7777777');
while ($tmp=mysql_fetch_assoc($result)) { ... }
} catch (Exception $e) {
echo $e->getMessage();
}
Note how beautiful it is. Whenever any of the qq fails we gtfo with our errors. And you can also note that we don't need now to store the state of the writing queries into a $resultvariable for verification, because our function now handles it by itself. And the same way it handles the selects, it just assigns the result to a variable as does the normal function, yet handles the errors within itself.
注意它是多么美丽。每当 qq 中的任何一个失败时,我们都会因错误而 gtfo。而且您还可以注意到,我们现在不需要将写入查询的状态存储到$result变量中进行验证,因为我们的函数现在自己处理了。和它处理选择的方式相同,它只是像普通函数一样将结果分配给一个变量,但处理自身内部的错误。
Also note, we don't need to show the actual errors since they bear huge security risk, especially so with this outdated extension. That is why our default will be just fine most of the time. Yet, if we do want to notify the user for some particular query error, we can always pass the second parameter to display our custom error message.
另请注意,我们不需要显示实际错误,因为它们承担着巨大的安全风险,尤其是对于这个过时的扩展。这就是为什么我们的默认设置在大多数情况下会很好的原因。然而,如果我们确实想通知用户某些特定的查询错误,我们总是可以传递第二个参数来显示我们的自定义错误消息。
回答by starkm
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.
我不确定是否有 mysql 版本,但添加这行代码允许抛出 mysqli_sql_exception。
我知道,已经过了很多时间,问题已经得到了检查回答,但我得到了不同的答案,这可能会有所帮助。
回答by Bharat Chhabra
$new_user = new User($user);
$mapper = $this->spot->mapper("App\User");
try{
$id = $mapper->save($new_user);
}catch(Exception $exception){
$data["error"] = true;
$data["message"] = "Error while insertion. Erron in the query";
$data["data"] = $exception->getMessage();
return $response->withStatus(409)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
if error occurs, you will get something like this->
如果发生错误,你会得到这样的东西->
{
"error": true,
"message": "Error while insertion. Erron in the query",
"data": "An exception occurred while executing 'INSERT INTO \"user\" (...) VALUES (...)' with params [...]:\n\nSQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: \"default\"" }
with status code:409.
状态码:409。
回答by Vishal
$sql = "INSERT INTO customer(FIELDS)VALUES(VALUES)";
mysql_query($sql);
if (mysql_errno())
{
echo "<script>alert('License already registered');location.replace('customerform.html');</script>";
}
回答by TheHippo
Use any method described in the previous post to somehow catch the mysql error.
Most common is:
使用上一篇文章中描述的任何方法以某种方式捕获 mysql 错误。
最常见的是:
$res = mysql_query('bla');
if ($res===false) {
//error
die();
}
//normal page
This would also work:
这也可以:
function error() {
//error
die()
}
$res = mysql_query('bla') or error();
//normal page
try { ... } catch {Exception $e) { .... }will not work!
try { ... } catch {Exception $e) { .... }不管用!
Note:Not directly related to you question but I think it would much more better if you display something usefull to the user. I would never revisit a website that just displays a blank screen or any mysterious error message.
注意:与您的问题没有直接关系,但我认为如果您向用户展示一些有用的东西会更好。我永远不会重新访问只显示空白屏幕或任何神秘错误消息的网站。

