MySQLi가 준비한 문 오류 보고
MySQLI를 이해하려고 하는데 오류가 보고되어 혼란스럽습니다.SQL 실행 시 오류를 감지하기 위해 MySQLi 'prepare' 문의 반환 값을 사용합니다.
$stmt_test = $mysqliDatabaseConnection->stmt_init();
if($stmt_test->prepare("INSERT INTO testtable VALUES (23,44,56)"))
{
$stmt_test->execute();
$stmt_test->close();
}
else echo("Statement failed: ". $stmt_test->error . "<br>");
단, prepare 스테이트먼트의 반환값은 SQL 스테이트먼트의 준비에 오류가 있는지 여부만 검출하고 실행 에러는 검출하지 않는 것입니까?이 경우 실행 행을 다음과 같이 플래그 오류로 변경해야 합니다.
if($stmt_test->execute()) $errorflag=true;
그리고 만약을 위해 스테이트먼트가 실행된 후 다음 작업도 수행해야 합니다.
if($stmt_test->errno) {$errorflag=true;}
...아니면 처음부터 괜찮았습니까?MySQLi prepare' 문의 반환값은 정의된 쿼리의 완전한 실행과 관련된 모든 오류를 캡처합니다.
고마워 C
mysqli의 각 메서드는 실패할 수 있습니다.각 반환값을 테스트해야 합니다.실패했을 경우, 기대했던 상태가 아닌 오브젝트를 계속하는 것이 말이 되는지 생각해 보세요.(잠재적으로 '안전'한 상태는 아니지만, 여기서는 문제가 되지 않는다고 생각합니다.)
연결/문마다 마지막 작업에 대한 오류 메시지만 저장되므로 문제가 발생한 후에도 계속하면 오류의 원인에 대한 정보가 손실될 수 있습니다.이 정보를 사용하여 스크립트가 재시도할지(일시적인 문제만), 무언가를 변경할지 또는 완전히 구제할지(및 버그를 보고할지) 결정할 수 있습니다.디버깅이 훨씬 쉬워집니다.
$stmt = $mysqli->prepare("INSERT INTO testtable VALUES (?,?,?)");
// prepare() can fail because of syntax errors, missing privileges, ....
if ( false===$stmt ) {
// and since all the following operations need a valid/ready statement object
// it doesn't make sense to go on
// you might want to use a more sophisticated mechanism than die()
// but's it's only an example
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc = $stmt->bind_param('iii', $x, $y, $z);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if ( false===$rc ) {
// again execute() is useless if you can't bind the parameters. Bail out somehow.
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if ( false===$rc ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->close();
6년 후 몇 장의 메모만 남았는데...
mysqli 확장은 예외를 통해 0 이외의 (mysqli) 오류 코드를 생성하는 작업을 완벽하게 보고할 수 있습니다. mysqli_driver를 참조하십시오.:$report_mode.
die()는 정말 너무 조잡해서 더 이상 이런 예에도 사용하지 않을 것입니다.
따라서, 각 (mysql) 작업이 여러 가지 이유로 실패할 수 있다는 사실만 무시하십시오. 이전에도 똑같은 작업이 수천 번 제대로 수행되었더라도...
완전성
다 요.$mysqli
★★★★★★★★★★★★★★★★★」$statement
틀리면 $mysqli->error
★★★★★★★★★★★★★★★★★」$statement->error
각각 다음과 같다.
효율성.
종료할 가능성이 있는 간단한 스크립트의 경우 메시지와 함께 PHP 오류를 트리거하는 단순한 한 줄짜리 스크립트를 사용합니다.보다 복잡한 애플리케이션의 경우, 예를 들어 예외를 발생시키는 등 오류 경고 시스템을 활성화해야 합니다.
사용 예 1: 심플 스크립트
# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);
사용 예 2: 응용 프로그램
# This is part of an application
class FuzDatabaseException extends Exception {
}
class Foo {
public $mysqli;
public function __construct(mysqli $mysqli) {
$this->mysqli = $mysqli;
}
public function updateBar() {
$q = "UPDATE foo SET bar=1";
$statement = $this->mysqli->prepare($q);
if (!$statement) {
throw new FuzDatabaseException($mysqli->error);
}
if (!$statement->execute()) {
throw new FuzDatabaseException($statement->error);
}
}
}
$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
$foo->updateBar();
} catch (FuzDatabaseException $e)
$msg = $e->getMessage();
// Now send warning emails, write log
}
이것이 당신의 질문에 대한 답변인지 아닌지 확실하지 않습니다.아니라면 미안해
쿼리에 대한 오류를 mysql 데이터베이스에서 가져오려면 연결 개체를 포커스로 사용해야 합니다.
따라서:
echo $mysqliDatabaseConnection->error
mysql에서 보낸 쿼리에 대한 오류를 에코합니다.
도움이 되었으면 좋겠다
언급URL : https://stackoverflow.com/questions/2552545/mysqli-prepared-statements-error-reporting
'programing' 카테고리의 다른 글
Seaborn 플롯을 파일에 저장하는 방법 (0) | 2023.02.01 |
---|---|
프로그램 방식으로 SearchView를 열려면 어떻게 해야 합니까? (0) | 2023.02.01 |
JPA를 사용한 맵 저장 (0) | 2023.02.01 |
VueJs, ReferenceError: google이 정의되지 않았습니다. (0) | 2023.02.01 |
프록시를 통해 CURL을 사용하는 방법 (0) | 2023.02.01 |