bind_result vs get_result를 사용하는 방법의 예
하다를 사용해서 요.bind_result
★★get_result
다른 것들보다 하나를 더 사용하는 목적이 무엇인지에 대한 질문입니다.
또한 각각의 사용에 대한 찬반 양론이 있습니다.
어느쪽인가를 사용하는 경우의 제한은 무엇이며, 그 차이는 있습니까.
방법 모두 " "와 함께 사용할 수 있습니다.*
「」의 경우, 「」의 경우bind_result()
사용하면 할 때 할 수 .bind_result()
변수 순서는 반환되는 행의 구조와 엄밀하게 일치해야 하기 때문입니다.
1 - 1 1$query1
를 사용합니다.bind_result()
$query1 = 'SELECT id, first_name, last_name, username FROM `table` WHERE id = ?';
$id = 5;
$stmt = $mysqli->prepare($query1);
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$stmt->bind_param('i',$id);
/* execute query */
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Get the number of rows */
$num_of_rows = $stmt->num_rows;
/* Bind the result to variables */
$stmt->bind_result($id, $first_name, $last_name, $username);
while ($stmt->fetch()) {
echo 'ID: '.$id.'<br>';
echo 'First Name: '.$first_name.'<br>';
echo 'Last Name: '.$last_name.'<br>';
echo 'Username: '.$username.'<br><br>';
}
§ 의 예 2:$query2
를 사용합니다.get_result()
$query2 = 'SELECT * FROM `table` WHERE id = ?';
$id = 5;
$stmt = $mysqli->prepare($query2);
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$stmt->bind_param('i',$id);
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
/* Get the number of rows */
$num_of_rows = $result->num_rows;
while ($row = $result->fetch_assoc()) {
echo 'ID: '.$row['id'].'<br>';
echo 'First Name: '.$row['first_name'].'<br>';
echo 'Last Name: '.$row['last_name'].'<br>';
echo 'Username: '.$row['username'].'<br><br>';
}
bind_result()
장점:
- 오래된 PHP 버전에서 작동합니다.
- 개별 변수를 반환합니다.
단점:
- 모든 변수를 수동으로 나열해야 합니다.
- 행을 배열로 반환하려면 더 많은 코드가 필요합니다.
- 테이블 구조가 변경될 때마다 코드를 업데이트해야 합니다.
get_result()
장점:
- 관련/번호가 지정된 어레이 또는 개체를 반환하고 반환된 행의 데이터로 자동으로 채워집니다.
fetch_all()
return at all one 반 method at 。
단점:
- MySQL 네이티브 드라이버(mysqlnd) 필요
예시는 각 매뉴얼페이지 및 에서 확인할 수 있습니다.
장단점은 간단하지만,
get_result()
를 이다.- 그러나 일부 오래된 PHP 버전에서는 항상 사용할 수 있는 것은 아닙니다.
최신 웹 응용 프로그램에서는 데이터가 쿼리에 바로 표시되지 않습니다.데이터를 먼저 수집한 다음 출력을 시작해야 합니다.또, 베스트 프랙티스를 따르지 않아도, 데이터를 곧바로 인쇄하지 않고 반환할 필요가 있는 경우가 있습니다.
이 점에 유의하여 두 가지 방법을 모두 사용하여 선택한 데이터를 연관 배열의 중첩된 배열로 반환하는 코드를 작성하는 방법을 살펴보겠습니다.
bind_result()
$query1 = 'SELECT id, first_name, last_name, username FROM `table` WHERE id = ?';
$stmt = $mysqli->prepare($query1);
$stmt->bind_param('s',$id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $first_name, $last_name, $username);
$rows = [];
while ($stmt->fetch()) {
$rows[] = [
'id' => $id,
'first_name' => $first_name,
'last_name' => $last_name,
'username' => $username,
];
}
테이블에서 열이 추가 또는 삭제될 때마다 이 코드를 편집해야 합니다.
get_result()
$query2 = 'SELECT * FROM `table` WHERE id = ?';
$stmt = $mysqli->prepare($query2);
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
테이블 구조가 변경되어도 이 코드는 그대로 유지됩니다.
그리고 더 있습니다.
을 다음과 하는 경우
$query = 'SELECT * FROM `table` WHERE id = ?';
$rows = prepared_select($query, [$id])->fetch_all(MYSQLI_ASSOC);
get_result()
몇 줄이면 꽤 그럴듯한 일이 될 거야단,bind_param()
지루한 탐색이 될 것이다.
그래서 내가 전화한 거야bind_result()
method "displicate" 입니다.
get_result()
는 MySQL 네이티브 드라이버(mysqlnd)를 설치하는 경우에만 PHP에서 사용할 수 있습니다.환경에 따라서는 mysqlnd 설치가 불가능하거나 바람직하지 않을 수 있습니다.
그래도 mysqli를 사용하여SELECT *
필드 이름을 사용하여 결과를 얻을 수 있습니다.단, 사용하는 것보다 조금 복잡합니다.get_result()
, 및 PHP의 사용도 포함됩니다.call_user_func_array()
기능.간단한 작업을 수행하는 php의 get_result() 대신 bind_result()를 사용하는 방법의 예를 참조하십시오.SELECT *
쿼리하여 결과를 (열 이름을 사용하여) HTML 테이블로 출력합니다.
내가 알아차린 가장 큰 차이점은bind_result()
에러가 발생하다2014
다른 $stmt 내에 중첩된 $stmt를 코드화하려고 하면 해당 $stmt가 가져오기됩니다(없음).mysqli::store_result()
):
준비 실패: (2014) 명령이 동기화되지 않았습니다. 지금 이 명령을 실행할 수 없습니다.
예:
기본 코드에서 사용되는 함수입니다.
function GetUserName($id) { global $conn; $sql = "SELECT name FROM users WHERE id = ?"; if ($stmt = $conn->prepare($sql)) { $stmt->bind_param('i', $id); $stmt->execute(); $stmt->bind_result($name); while ($stmt->fetch()) { return $name; } $stmt->close(); } else { echo "Prepare failed: (" . $conn->errno . ") " . $conn->error; } }
메인 코드
$sql = "SELECT from_id, to_id, content FROM `direct_message` WHERE `to_id` = ?"; if ($stmt = $conn->prepare($sql)) { $stmt->bind_param('i', $myID); /* execute statement */ $stmt->execute(); /* bind result variables */ $stmt->bind_result($from, $to, $text); /* fetch values */ while ($stmt->fetch()) { echo "<li>"; echo "<p>Message from: ".GetUserName($from)."</p>"; echo "<p>Message content: ".$text."</p>"; echo "</li>"; } /* close statement */ $stmt->close(); } else { echo "Prepare failed: (" . $conn->errno . ") " . $conn->error; }
언급URL : https://stackoverflow.com/questions/18753262/example-of-how-to-use-bind-result-vs-get-result
'it-source' 카테고리의 다른 글
개체 목록 섞기 (0) | 2022.11.20 |
---|---|
MySql 최대 메모리 용량이 위험할 정도로 높아도 증대가 필요함 (0) | 2022.11.19 |
regex의 "\d"는 숫자를 의미합니까? (0) | 2022.11.19 |
clone() 메서드가 java.lang으로 보호되는 이유는 무엇입니까?오브젝트? (0) | 2022.11.19 |
MySQL에 코멘트를 추가하려면 어떻게 해야 하나요? (0) | 2022.11.19 |