PHP

PHP함수 - mysqli_connect() / mysqli_query() / mysqli_num_rows() / mysqli_fetch_assoc();

이유림 2021. 2. 2. 18:38

이번에는 mysql함수에 대해서 알아보도록 한다

관련 함수들은 php5 이전에는 mysql이라는 키워드와 함께 쓰였지만 PHP5 이후로는 mysqli로 지원하고있다

 

mysqli_connect(); 함수 [W3C]

:mysqli_connect() function opens a new connection to the MySQL server. (mysqli_connect()는 오픈한다  MySQL서버와의 새로운 커넥션을)

 

:이 함수는 데이터베이스에 접속하는 함수이다. 사용하는 방법은

 

mysqli_connect(서버의 호스트명,계정,비번,DB이름);

 

순으로 각자 알맞은 값을 넣어주면 된다.

 

 

mysqli_query();함수 [W3C]

:mysqli_query() function performs a query against a database. (mysqli_query()는 수행한다 데이터베이스에 맞는쿼리를

 

:이 함수는 mysqli_connect를 통해 연결된 객체를 이용하여 MySQL쿼리를 실행하는 함수이다. (쿼리란? 데이터베이스에 정보를 요청하는것이다.)

mysqli_query(연결객체,쿼리);

연결 객체와 쿼리를 미리 변수로 지정해 놓은 후 위와 같은 문법으로 사용 할 수 있다.

 

 

 

mysqli_num_rows(); 함수 [W3C]

 :The mysqli_num_rows() function returns the number of rows in a result set. (The mysqli_num_rows()는 반환한다 result set의 행 수를)

 

아 함수는 말 그대로 DB내부에 있는 결과 행의 수를 확인하는 것이다

 

mysqli_num_rows(resuet set);

위와 같은 문법으로 사용 할 수 있으며 resuet set 자리에는 보통 mysqli_query를 통해 지정한 변수를 넣으면 된다.

 

이 함수는 if절과 함께 결과값에 데이터가 있는지를 체크할 수 있다

 

 

 

mysqli_fetch_assoc(); 함수 [W3C]

:mysqli_fetch_assoc() function fetches a result row as an associative array. (mysqli_fetch_assoc()는결과행을 연관배열로써 가져온다.)

mysqli_fetch_assoc(resuet set);

위와 같은 문법으로 사용 할 수 있다.

 

 

위의 함수들을 이용해 예제문을 만들어보도록 하자

 

아래 보이는 표는 guest라는 데이터베이스의 테이블이다

number name age gender
1 이유림 23
2 남주혁 28

 

아래 코드는 데이터의 number,name,gender를 조회해서 표 내부에 출력해보는 코드이다

 

$connect = mysqli_connect(서버이름, 유저아이디, 패스워드, db의 이름)
$sql = "select * from guest" //데이터베이스를 조회할 쿼리를 만든다
$result = mysqli_query($connect, $sql)

if(mysql_num_rows($result) > 0){
  while($row = mysql_fetch_assoc($result)){
    echo "	
      <tr>
        <td> $row[number] </td>
        <td> $row[name] </td>
        <td> $row[gender] </td>
      </tr>
     "
    }
}