PHP 명령 동기화 안 됨 오류
저는 pHP/MySQLi에서 준비된 두 개의 문을 사용하여 mysql 데이터베이스에서 데이터를 검색하고 있습니다.하지만 문을 실행하면 "Commands out of synch, now 명령어를 실행할 수 없습니다"라는 오류가 나타납니다.
여기 내 코드가 있습니다.
$stmt = $mysqli->prepare("SELECT id, username, password, firstname, lastname, salt FROM members WHERE email = ? LIMIT 1";
$stmt->bind_param('s', $loweredEmail);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $firstname, $lastname, $salt);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
while($mysqli->more_results()){
$mysqli->next_result();
}
$stmt1 = $mysqli->prepare("SELECT privileges FROM delegations WHERE id = ? LIMIT 1");
//This is where the error is generated
$stmt1->bind_param('s', $user_id);
$stmt1->execute();
$stmt1->store_result();
$stmt1->bind_result($privileges);
$stmt1->fetch();
내가 시도한 것:
- 준비된 문을 두 개의 개별 개체로 이동합니다.
코드 사용:
while($mysqli->more_results()){ $mysqli->next_result(); } //To make sure that no stray result data is left in buffer between the first //and second statements
- free_result() 및 mysqli_stmt->close() 사용
PS: 두 번째 문의 '$stmt1->error'에서 'Out of Sync' 오류가 발생합니다.
mysqli::query MYSqli_USE_RESULT를 사용하는 경우 모든 후속 호출이 error를 반환합니다. mysqli_free_result()를 호출하지 않는 한 명령이 동기화되지 않습니다.
여러 개의 저장 프로시저를 호출할 때 "Commands out of sync(명령이 동기화되지 않음); 이 명령을 지금 실행할 수 없습니다"라는 오류가 발생할 수 있습니다.호출 사이에 결과 개체에서 close() 함수를 사용하는 경우에도 발생할 수 있습니다.문제를 해결하려면 저장된 프로시저 호출 후에 mysqli 개체의 next_result() 함수를 호출해야 합니다.아래의 예를 참조:
<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');
// Check for errors
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
// 1st Query
$result = $db->query("call getUsers()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$user_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
// 2nd Query
$result = $db->query("call getGroups()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$group_arr[] = $row;
}
// Free result set
$result->close();
$db->next_result();
}
else echo($db->error);
// Close connection
$db->close();
?>
이것이 도움이 되기를 바랍니다.
"명령이 동기화되지 않았습니다. 지금 이 명령을 실행할 수 없습니다."
이 오류에 대한 자세한 내용은 mysql 문서에서 확인할 수 있습니다.이러한 세부 정보를 읽어보면 동일한 연결에서 다른 준비된 문장을 실행하기 전에 준비된 문장 실행의 결과 집합을 완전히 가져올 필요가 있음을 알 수 있습니다.
매장 결과콜을 이용하면 문제를 해결할 수 있습니다.처음에 제가 하려고 했던 것의 예를 보여드리겠습니다.
<?php
$db_connection = new mysqli('127.0.0.1', 'user', '', 'test');
$post_stmt = $db_connection->prepare("select id, title from post where id = 1000");
$comment_stmt = $db_connection->prepare("select user_id from comment where post_id = ?");
if ($post_stmt->execute())
{
$post_stmt->bind_result($post_id, $post_title);
if ($post_stmt->fetch())
{
$comments = array();
$comment_stmt->bind_param('i', $post_id);
if ($comment_stmt->execute())
{
$comment_stmt->bind_result($user_id);
while ($comment_stmt->fetch())
{
array_push($comments, array('user_id' => $user_id));
}
}
else
{
printf("Comment statement error: %s\n", $comment_stmt->error);
}
}
}
else
{
printf("Post statement error: %s\n", $post_stmt->error);
}
$post_stmt->close();
$comment_stmt->close();
$db_connection->close();
printf("ID: %d -> %s\n", $post_id, $post_title);
print_r($comments);
?>
이 경우 다음과 같은 오류가 발생합니다.
Comment 문 오류: 명령이 동기화되지 않았습니다. 지금 이 명령을 실행할 수 없습니다.
PHP 공지사항:정의되지 않은 변수: post_title in error.php on 41 ID : 9033 -> 배열 ( )
다음은 올바르게 작동하기 위해 수행해야 하는 작업입니다.
<?php
$db_connection = new mysqli('127.0.0.1', 'user', '', 'test');
$post_stmt = $db_connection->prepare("select id, title from post where id = 1000");
$comment_stmt = $db_connection->prepare("select user_id from comment where post_id = ?");
if ($post_stmt->execute())
{
$post_stmt->store_result();
$post_stmt->bind_result($post_id, $post_title);
if ($post_stmt->fetch())
{
$comments = array();
$comment_stmt->bind_param('i', $post_id);
if ($comment_stmt->execute())
{
$comment_stmt->bind_result($user_id);
while ($comment_stmt->fetch())
{
array_push($comments, array('user_id' => $user_id));
}
}
else
{
printf("Comment statement error: %s\n", $comment_stmt->error);
}
}
$post_stmt->free_result();
}
else
{
printf("Post statement error: %s\n", $post_stmt->error);
}
$post_stmt->close();
$comment_stmt->close();
$db_connection->close();
printf("ID: %d -> %s\n", $post_id, $post_title);
print_r($comments);
?>
위의 예에 대해 몇 가지 주의할 사항은 다음과 같습니다.
The bind and fetch on the statement still works correctly.
Make sure the results are freed when the processing is done.
올바른 작업을 수행하고 준비된 진술과 함께 저장된 절차를 사용하는 사람들을 위한 것입니다.
어떤 이유로 mysqli는 저장 프로시저에서 출력 변수를 매개 변수로 사용할 때 리소스를 확보할 수 없습니다.이 문제를 해결하려면 출력 변수/파라미터에 값을 저장하는 대신 절차 본문 내의 레코드 집합을 반환하기만 하면 됩니다.
예를 들어 SET outputVar = LAST_INSERT_ID() 대신 SELECT LAST_INSERT_ID()를 가질 수 있습니다. 그러면 PHP에서는 다음과 같이 반환 값을 받습니다.
$query= "CALL mysp_Insert_SomeData(?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("is", $input_param_1, $input_param_2);
$stmt->execute() or trigger_error($mysqli->error); // trigger_error here is just for troubleshooting, remove when productionizing the code
$stmt->store_result();
$stmt->bind_result($output_value);
$stmt->fetch();
$stmt->free_result();
$stmt->close();
$mysqli->next_result();
echo $output_value;
이제 "Commands out of synch(명령이 동기화되지 않아 명령을 실행할 수 없습니다)" 오류 없이 두 번째 저장 프로시저를 실행할 준비가 되었습니다.레코드 집합에서 두 개 이상의 값을 반환하는 경우 다음과 같이 루프를 거쳐 모든 값을 가져올 수 있습니다.
while ($stmt->fetch()) {
echo $output_value;
}
저장 프로시저에서 두 개 이상의 레코드 세트를 반환하는 경우(여러 개의 선택 항목이 있음), $stmt->next_result()를 사용하여 해당 레코드 세트를 모두 검토해야 합니다.
언급URL : https://stackoverflow.com/questions/14554517/php-commands-out-of-sync-error
'programing' 카테고리의 다른 글
C11 유형 계층 구조 이해 (0) | 2023.09.25 |
---|---|
Oracle Partition - Error ORA14400 - 삽입된 Partition Key가 어떤 Partition에도 매핑되지 않음 (0) | 2023.09.25 |
mysql 타임스탬프를 실제 날짜와 시간으로 변환하시겠습니까? (0) | 2023.09.20 |
내 sqli가 죽거나, 죽거나, 죽어야 합니까? (0) | 2023.09.20 |
자바스크립트 ES6 export const vs exportlet (0) | 2023.09.20 |