php 함수관련 질문 드립니다.
본문
<?php
//DB연결
$mysqli = new mysqli("localhost", "root", "!Qazxsw123@","myDB");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);}
//테이블 선택
$sql= "SELECT * FROM Member";
//테이블 안쪽 데이터 접근하고 데이터의 수를 파악
$res = mysqli_query($mysqli,$sql);
$rows= mysqli_num_rows($res);
//echo $rows; <---이부분까지 문제 없어서 주석처리
//이 아래부분 테이블작성 테스트후 문제없고 데이터 조회 하려는 코드 작성후 페이지가 작동하지 않는다고 표시
echo("<table border='1'>");
while($i=0;<$rows;$i++)
{
$userid=mysqli_result($res,'id',$i);
$userage=mysqli_result($res,'age',$i);
$useremail=mysqli_result($res,'email',$i);
$userreg_date=mysqli_result($res,'reg_date',$i);
echo("<tr>
<td$userid</td>
<td>$userid</td>
<td>$userage</td>
<td>$userreg_date</td>
</tr>");
}
echo("</table>");
//아무래도 mysqli_result 함수가 잘못된듯함
//DB종료
$mysqli->close();
?>
뭐가 잘못 된걸까요? 답변 부탁 드리겠습니다. 대단히 감사합니다.
답변 2
while($i=0;<$rows;$i++) <- 이게 잘 작동하나요?
for 하고 while 이랑 혼돈 하신 듯 합니다.
- 비밀번호 노출. 가짜 데이터라면 상관이 없으나 주의가 필요합니다.
- while문 오류, for문으로 변경해도 오류. 문법 주의!
- 기존 MySQL에서 MySQLi로 이름 등 일부만 변경한 것 같군요.
* 아래 페이지에 여러 fetch 방법이 있습니다.
- https://www.php.net/manual/en/class.mysqli-result.php
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
$mysqli->set_charset('utf8mb4'); // utf8 등 환경에 맞게….
$sql = "SELECT * FROM Member";
$res = $mysqli->query($sql);
$rows = $res->num_rows;
echo '<table border="1">';
while ( $row=$res->fetch_assoc() ) {
?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['age']?></td>
<td><?=$row['email']?></td>
<td><?=$row['reg_date']?></td>
</tr>
<?php
}
echo '</table>';
$mysqli->close();