2013-06-20 2 views
0

나는 내 자신의 의견 시스템을 만들고있어 MySQLi로 이동할 때가되었다고 결정했습니다.MySQLi 준비된 명령문 형식

제가 궁금해하는 것은 - 정확하게하고 있습니까?

필요한 경우 결과를 해제하고 닫습니까? 내가 놓친 게 있니?

여기

$mysqli = new mysqli('localhost', 'username', 'password', 'comments'); 
if($stmt = $mysqli -> prepare("INSERT INTO comments (topid, body, user, active) VALUES (?, ?, ?, ?)")) 
{ 
    $stmt->bind_param('isii', $id, $comment, $userid, $mod); 
    $stmt->execute(); 
    $stmt->close(); 
} 
else 
{ 
    $mysqli->close(); 
    echo '{"status":0,"error":'.json_encode('Database Error - Please try again.').'}'; 
    return; 
} 
$mysqli->close(); 

및 (? 또한 어떤 구문이 사이트에서 강조 할 수 코드 샘플 버튼이 아무것도하지 않습니다는) 내 '동안'루프 뭐하는 거지입니다 :

$comments = array(); 

$mysqli = new mysqli('localhost', 'username', 'password', 'comments'); 
$mysqli->set_charset('utf8'); 
if($stmt = $mysqli -> prepare("SELECT user.id as userid, user.name, comments.id, comments.body, comments.dt FROM comments JOIN user ON comments.user = user.id where comments.postid = ? and comments.topid=0 and comments.active=1 ORDER BY comments.id DESC Limit ?, ?")) 
{ 
    $stmt->bind_param('iii', $postid, $offset, $limit); 
    $stmt->execute(); 
    $res = $stmt->get_result(); 
    $stmt->close(); 
} 

while($row = $res->fetch_assoc()) 
{ 
    $comments[] = new Comment($row); 
} 

$res->free(); 
$mysqli->close(); 

return $comments; 
+0

강조 표시된 부분이 깨졌습니다. –

+0

당신이 선택한 태깅은 당신의 질문에 극적으로 덜주의를 끌었습니다. 가장 많이 사용되는 태그 일수록 더 많은 의견을 얻을 수 있습니다. 그것은 비록 이익이되지 않을 수도 있습니다 ... –

답변

0

나는 이것을 제대로하고 있는가?

분명히 없습니다.

API PHP 사용자가 오해 한 점이 하나 있습니다. 응용 프로그램 코드에서 원시 형식으로 사용할 수 없습니다.
인터넷을 통해 찾을 수있는 모든 잘못된 예에도 불구하고 데이터베이스 추상화 라이브러리을 작성하거나 채택해야합니다. 그러면 뒤에서 더러운 일을 모두 처리 할 수 ​​있습니다. 그것을 가지고 무엇

같은 일하는 대신 코드의 의미 라인에 저장에 대한

include 'db.php'; 
// if you don't mind to scroll a couple screens to the right yourself, 
// please be polite to ones whom you ask to - split your code, make it readable 
$sql = "SELECT user.id as userid, user.name, comments.id, comments.body, comments.dt 
     FROM comments JOIN user ON comments.user = user.id 
     where comments.postid = ? and comments.topid=0 and comments.active=1 
     ORDER BY comments.id DESC Limit ?, ?" 
return $db->getAll($sql, $postid, $offset, $limit); 

, 쓸모없는 반복들에 저장합니다.

include 'db.php'; 
$sql = "INSERT INTO comments (topid, body, user, active) VALUES (?, ?, ?, ?)"; 
$res = $db->query($sql, $id, $comment, $userid, $mod); 
if (!$res) 
{ 
    echo json_encode(array("status" => 0, 
          "error" => 'Database Error - Please try again.'); 
} 

일부 사소한 노트는 삽입에 대한 문자 집합을 설정하지 않는 매우 이상한 이유로

. json을 잘못 사용하고 있습니다. 닫기 및 해제는 필요하지 않습니다.

관련 문제