Forum und email

mysql_query

(PHP 4, PHP 5, PECL mysql:1.0)

mysql_query — MySQL 질의를 전송

설명

resource mysql_query ( string $query [, resource $link_identifier ] )

mysql_query()는 (link_identifier 와 연관된 데이터베이스 서버로) 질의를 전송한다. mysql_query() sends a query (to the currently active database on the server that's associated with the specified link_identifier ).

매개변수

query

SQL 질의.

세미콜론으로 끝나지 않는 질의 문자열.

link_identifier

MySQL 연결. 지정하지 않으면 mysql_connect()로 연 마지막 연결을 사용합니다. 연결이 없으면, 매개변수 없이 mysql_connect()를 호출하여 연결을 만듭니다. 연결이 성립되지 않으면 E_WARNING 경고를 생성합니다.

반환값

SELECT, SHOW, DESCRIBE, EXPLAIN 구문으로 mysql_query()를 호출하면 성공할 경우 resource를, 실패하면 FALSE를 반환한다.

UPDATE, DELETE, DROP 등을 실행할 경우 성공하면 TRUE를 실패하면 FALSE를 반환한다.

반환되는 결과 리소스(resource)는 mysql_fetch_array()와 같은 결과 테이블을 다루는 함수들에 전달하여 데이터에 접근할 수 있다.

SELECT 구문으로 부터 얼마나 많은 행이 있는지 알기 위해서는 mysql_num_rows()를, DELETE, INSERT, REPLACE, UPDATE 구문으로 변경된 행의 개수를 알기 위해서는 mysql_affected_rows()를 사용한다.

질의에 의해 참조되는 테이블에 접근을 허용되지 않은 사용자에 의해 mysql_query()가 실패하면 FALSE를 반환한다.

예제

Example#1 잘못된 질의

다음 질의는 문법적으로 오류가 있어서 mysql_query()는 실패하고, FALSE를 반환한다.

<?php
$result 
mysql_query('SELECT * WHERE 1=1');
if (!
$result) {
    die(
'Invalid query: ' mysql_error());
}

?>

Example#2 유효한 질의

다음 질의는 유효한 질의로서 mysql_query()resource를 반환한다.

<?php
// This could be supplied by a user, for example
$firstname 'fred';
$lastname  'fox';

// Formulate Query
// This is the best way to perform a SQL query
// For more examples, see mysql_real_escape_string()
$query sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
    
mysql_real_escape_string($firstname),
    
mysql_real_escape_string($lastname));

// Perform Query
$result mysql_query($query);

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    
$message  'Invalid query: ' mysql_error() . "\n";
    
$message .= 'Whole query: ' $query;
    die(
$message);
}

// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row mysql_fetch_assoc($result)) {
    echo 
$row['firstname'];
    echo 
$row['lastname'];
    echo 
$row['address'];
    echo 
$row['age'];
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>