PHP: MySQL 함수 - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<msqlmysql_affected_rows>
view the version of this page
Last updated: Wed, 29 Jan 2003

LXIII. MySQL 함수

아래 함수들은 MySQL 데이터베이스 서버에 접근할 수 있게 해준다. 이들 함수를 사용하려면 PHP를 --with-mysql 인자를 사용하여 컴파일해야 한다. 만일 위의 인자를 설치된 MySQL의 경로 없이 사용한다면, PHP는 내장된 클라이언트 라이브러리를 대신 사용할 것이다. 서로 다른 어플리케이션을 이용하는 사용자들이 MySQL을 사용하려 할 때(예를들어, PHP3와 PHP4가 동시에 apache 모듈로써 돌아가거나, auth-mysql일 경우) MySQL 경로를 반드시 다음과 같이 설정해야 한다: --with-mysql=/path/to/mysql. 위 옵션은 php가 MySQL에 의해 설치된 클라이언트 라이브러리를 사용하도록 하며, 어떠한 충돌도 피할 수 있게 해준다.

MySQL에 대한 더 상세한 정보는 에서 얻을 수 있다.

MySQL 문서는 에 있다.

차례
mysql_affected_rows -- 최근 MySQL 작업으로 처리된 행(row) 개수를 얻음
mysql_change_user --  현 접속에서 로그인된 사용자를 변경
mysql_client_encoding -- Returns the name of the character set
mysql_close -- MySQL 접속을 닫음
mysql_connect -- MySQL 서버에 접속
mysql_create_db -- MySQL 데이터베이스를 생성
mysql_data_seek -- 내부적인 결과 포인터를 이동
mysql_db_name -- 데이터 결과를 얻음
mysql_db_query -- MySQL 질의문을 전송
mysql_drop_db -- MySQL 데이터베이스를 삭제
mysql_errno -- 최근 MySQL 작업으로 발생한 에러 번호를 반환
mysql_error -- 최근 실행된 MySQL 작업으로 발생한 에러 메시지를 반환
mysql_escape_string --  Escapes a string for use in a mysql_query.
mysql_fetch_array --  결과를 필드이름 색인 또는 숫자 색인으로 된 배열로 반환
mysql_fetch_assoc --  결과를 필드이름 색인으로 된 배열로 반환
mysql_fetch_field --  결과로부터 열 정보를 얻어서 객체로 반환
mysql_fetch_lengths --  결과로부터 각 출력의 길이를 반환
mysql_fetch_object -- 행(row)의 결과를 객체로 얻음
mysql_fetch_row -- 결과를 숫자색인으로 된 배열로 반환
mysql_field_flags --  결과로부터 특정 필드(field)의 상태정보(flag)를 반환
mysql_field_len --  특정 필드의 길이를 반환
mysql_field_name --  결과로부터 특정 필드 이름을 반환
mysql_field_seek --  특정 필드의 오프셋(offset)으로 위치(pointer)를 이동
mysql_field_table --  특정 필드가 속한 테이블 이름을 얻음
mysql_field_type --  결과로부터 특정 필드의 데이터 형(type) 정보를 반환
mysql_free_result -- Free result memory
mysql_get_client_info -- Get MySQL client info
mysql_get_host_info -- Get MySQL host info
mysql_get_proto_info -- Get MySQL protocol info
mysql_get_server_info -- Get MySQL server info
mysql_info --  Get information about the most recent query
mysql_insert_id --  최근 INSERT 작업으로부터 생성된 identifier 값을 반환
mysql_list_dbs --  MySQL 서버에 있는 데이터베이스 이름을 반환
mysql_list_fields -- MySQL 결과의 필드 리스트로 반환
mysql_list_processes -- List MySQL processes
mysql_list_tables -- MySQL 데이터베이스에 있는 테이블 목록을 반환
mysql_num_fields -- 결과로부터 필드 개수를 반환
mysql_num_rows -- 결과로부터 열 개수를 반환
mysql_pconnect --  MySQL 서버와 영구적인 데이터베이스 접속
mysql_ping -- Ping a server connection or reconnect if there is no connection
mysql_query -- Send a MySQL query
mysql_real_escape_string --  Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection.
mysql_result -- 결과 데이터를 반환
mysql_select_db -- MySQL 데이터베이스를 선택
mysql_stat -- Get current system status
mysql_tablename -- 필드의 테이블이름을 얻음
mysql_thread_id -- Return the current thread ID
mysql_unbuffered_query --  Send an SQL query to MySQL, without fetching and buffering the result rows


User Contributed Notes
MySQL 함수
add a note add a note
steer at projex dot hu
07-Mar-2000 06:53

A quick way to extract a mysql query result into variables, without using an array:

$result = mysql_query("select model,color,price from cars where id=$id");

extract(mysql_fetch_assoc($result));

Now you have the variables $model, $color, $price. You can ask extract() to prefix it for you, with like extract(stuff,EXTR_PREFIX_ALL,"r"), and right there you have $r_model, $r_color...

If you have to pull multiple rows from the query, e.g. using "while", you have to pull 'em to an array, but still can use extract() to extract them :)

while ($r = mysql_fetch_array($result)) {
  extract($r);
  ...
}

laura at freschinfo dot com
22-Mar-2000 09:38

The easy way to surpress MySQL error messages is to put an "@" in front of the mysql command.  For example, @mysql_db_query(whatever).


This also works for any other PHP functions. (ed.)

craig at chiid dot ie
21-Dec-2000 05:17

Something to Note:

MySQL uses Unix time functions and has no problems with dates until 2069; all 2-digit years are regarded to be in the range 1970 to 2069, which means that if you store 01 in a year column, MySQL treats it as 2001.

15-Feb-2001 07:51
A good place to get beginner's info and some good pointers on using MySQL is:
mwalkup at morningstarstudios dot net
04-Apr-2001 09:04

Just a note, when using MySQL to output files (ie: a database backup script) if the directory permissions are not set right, it will not create the files AND WILL NOT return an error code.  You must have the permissions set right.
jcn at iki dot fi dot no_spam
01-May-2001 01:37

For one solution to problems with MySQL and special Nordic characters, please see

mw-php at ender dot com
22-Jun-2001 04:11

The mysql_fetch_[row|object|array] functions return data as type string. Owing to the very flexible nature of php variables, this is normally not relevent, but if you happen to retrieve two integers from a database, then try to compare with bitwise operators, you'll run into trouble, because (19 & 2) == 2, but ("19" & "2") == 0. To remedy this, if you use variables from a database with bitwise operators, use the settype() function to explicitly cast your variables as integers before comparing.
davey at shakedownwizards dot com
30-Jun-2001 06:24

The mysql_fetch_row function returns an array with numeric indices.

For example, a row from the query:

SELECT bookid,title,author FROM books

would look like:

$record[0]=3
$record[1]="A Farewell To Arms"
$record[2]="Ernest Hemingway"

The mysql_fetch_assoc function returns an array with indices that are the field names, like such:

$record["bookid"]=3
$record["title"]="A Farewell To Arms"
$record["author"]="Ernest Hemingway"

The mysql_fetch_array function returns an array with both kinds of indices, so this array looks like:

$record[0]=3
$record["bookid"]=3
$record[1]="A Farewell To Arms"
$record["title"]="A Farewell To Arms"
$record[2]="Ernest Hemingway"
$record["author"]="Ernest Hemingway"

This is the reason for the "doubled" field output from the example.

Note that the mysql_fetch_array function has an optional parameter where you can specify the indices.

So replacing the call:

mysql_fetch_array($result)

with:

mysql_fetch_array($result,MYSQL_NUM)

would be an identical fix to:

mysql_fetch_row($result)

Hope this helps!

keith at keithtyler dot com
30-Jun-2001 06:41

It looks like the reason for the double vision is so that when you want to use the sql results, you can call the array elements via either indices (e.g. $line[0], $line[1], etc.) or by their database field names (e.g. $line["uid"], $line["pw"], $line["gid"], etc.).

You can see this by changing the example to print $col_name as well as $col_value. Each repeated val shows up with a different key (of course) each time.

rupert at ditzed dot org
13-Jul-2001 08:23

Hi,

The problem with
extract(mysql_fetch_array($result));
is that it actually fetches two arrays, a number index array ($arr[0], $arr[1], $arr[2], ...) and an associative (hash) array, ($arr["field1"], $arr["field2"], $arr["field3"], ...), thus $arr actually contains two sets of data (as you have observed).

If you then try to push out all the data from $arr without explicitly naming those field ids, then you WILL get your data appearing twice.

The full definition for mysql_fetch_array is as follows:
mysql_fetch_array ($result_id, [MYSQL_NUM|MYSQL_ASSOC])
Since MYSQL_NUM is equivalent to mysql_fetch_row, you have found that switching to mysql_fetch_row works fine.
In fact, the only real reason you may want to use mysql_fetch_array is with the MYSQL_ASSOC option, as this allows you to reference the fields in the associative array returned.

philip at cornado dot com
23-Jul-2001 07:24

If you're new to this, you really should learn basic SQL before moving on. PHP != SQL. Here's are a few good basic SQL tutorials:

 *
 *
*

mbabcock-php at fibrespeed dot net
29-Jul-2001 02:41

Since there aren't functions to start and end/rollback transactions, you'll have to use mysql_query("BEGIN"), mysql_query("COMMIT") and mysql_query("ROLLBACK"). These will only work properly on tables that support transactions.  You may also wish to roll your own mysql_begin (etc) functions that run the above queries for you.
skelley at diff dot nl
25-Sep-2001 09:11

Hi, here's a nice little trick to select records in random order from a table in a MySQL database prior to version 3.23

SELECT *, (ItemID/ItemID)*RAND() AS MyRandom FROM Items ORDER BY MyRandom

[[[Editors note:
And just SELECT * FROM foo WHERE bar = RAND() after 3.23
]]]

nospam at nospam dot nos
19-Nov-2001 04:17

ever wanted to know the date a table was last updated? use this:

$info = mysql_fetch_array(mysql_query("show table status from databasename like 'tablename'"));
echo $info["Update_time"];

kekoa13 at yahoo dot com
18-Feb-2002 11:44

I find it the least problematic to simply use the list() construct to assign variables from an array returned from the mysql_fetch_row() & others.

$data = mysql_query("SELECT name, data FROM table");
while(list($t_name, $t_data) = mysql_fetch_row($data)) {
  echo "Name: $t_name    Data: $t_data\n";
}

It's not too difficult to maintain something like this, since the list() variables mirror the fields being queried.  It gets messy when you have more than 10 fields you are working with.

jeyoung at priscimon dot com
25-Apr-2002 04:23

MySQL transactions

MySQL supports transactions on tables that are of type InnoDB. I have noticed a behaviour which is puzzling me when using transactions.

If I establish two connections within the same PHP page, start a transaction in the first connection and execute an INSERT query in the second one, and rollback the transaction in the first connection, the INSERT query in the second connection is also rolled-back.

I am assuming that a MySQL transaction is not bound by the connection within which it is set up, but rather by the PHP process that sets it up.

This is a very useful "mis-feature" (bug?) because it allows you to create something like this:

class Transaction {
 var $dbh;

 function Transaction($host, $username, $password) {
   $this->dbh = mysql_connect($host, $username, $password);
 }

 function _Transaction() {
    mysql_disconnect($this->dbh);
 }

 function begin() {
  mysql_query("BEGIN", $this->dbh);
 }

 function rollback() {
    mysql_query("ROLLBACK", $this->dbh);
}

 function commit() {
   mysql_query("COMMIT", $this->dbh);
 }
}

which you could use to wrap around transactional statements like this:

$tx =& new Transaction("localhost", "username", "password");
$tx->begin();
$dbh = mysql_connect("localhost", "username", "password");
$result = mysql_query("INSERT ...");
if (!$result) {
 $tx->rollback();
} else {
$tx->commit();
}
mysql_disconnect($dbh);
unset($tx);

The benefit of such a Transaction class is that it is generic and can wrap around any of your MySQL statements.

pvenable at cs dot cmu dot edu
31-May-2002 12:43

I had some difficulties installing PHP with MySQL support on RedHat-7.1, but it works at last. :)  Here are a few of the unexpected things I had to do to get it working:
After installing apache, mysql, and php4, I found a php-mysql rpm, since the php4 rpm lacks MySQL support.  (I also had to find a few more rpms before this one would install.) Then, I had to make sure and export the path of the library libgcc_s.so (export LD_LIBRARY_PATH=/usr/local/lib) before running the Apache httpd. Otherwise PHP fails to load the MySQL library, which apparently depends on libgcc_s.so, but doesn't give much useful feedback except that the MySQL-specific commands you're using are unrecognized.  I hope this saves someone else from going through the hours of hassle it took me to figure it out!

ajenks at discoverymining dot com
05-Jun-2002 04:04

just a little FYI, when installing PHP from an RPM.  In order to get MySql support you need to download the php-mysql*.rpm.  If you don't install the php-mysql*.rpm you'll just get the common error: Call to undefined function: mysql_connect().
vinod at jobsure dot com
09-Jun-2002 09:22

To protect your mysql server from long running query which hangs the database

This PHP code basically kills the long running sql process .

I kept this PHP file in cron to run every 15 minues and believe me
it had dramatic performance on my website and my mysql database NEVER HANGED

//################ //

kill_long_query.php
//################ //

set_time_limit(30000);

$result=mysql_query("show processlist");

while ($row=mysql_fetch_array($result))
{
$process_id=$row["Id"];
if (($row["Time"] > 100 ) || ($row["Command"]=="Sleep") )
{
print $row["Id"];
$sql="kill $process_id";
mysql_query($sql);
}

}
//###################//

//###################//

16-Jun-2002 07:38
Regarding transactions, you must use a recent MySQL version which supports InnoDB tables. you should read the mysql manual (the part about Innodb tables, section 7.5) and configure your server to use them.
Some reading about how it works:

(Click where it says Part2, I can't put the direct URL here because it is too long)

Then in PHP you use commands like:

mysql_query("BEGIN");
mysql_query("COMMIT");
mysql_query("ROLLBACK");

You must make sure that you convert your existing tables to innodb or create new ones: CREATE TABLE (...) type=innodb;

opaf at yahoo dot com
13-Nov-2002 02:56

Two notes about PHP and MySQL:

1. Get used to the syntax

$myquery = "<your query here>";
$result = mysql_query($myquery);

instead of

$result = mysql_query("<your query here>");

Some of the benefits of the proposed syntax are:

- abilty to perform a global search to your scripts nice and easy
- ability to easily output/debug your queries

2. The second note has more to do with MySQL:

Timestamp fields update automaticaly everytime you issue an Update query. Read the documentation!!

I lost 3 days of my life because of this

mijnpc at xs4all dot nl
20-Nov-2002 09:33

If you have a Windows machine running a webserver with PHP you don't need to install MySQL server to locally test scripts, if you are granted to establish a Secure Telnet connection (port 22) to the remote webserver.

To do this you need a Secure Telnet client, which supports port-forwarding.
Before you establish a connection, define the port-forward.
Forward local port 3306 to [name or ip of remote server]:3306
Make sure that local ports accept connections from other hosts
Save this session

Connect to remote server with username and password
Minimize the shell and that's it...

You can use the same username (and password) as if you were working on the remote server !
E.g. : $link = mysql_connect("localhost", "root", "") or die("no way jose");

You may get a shell-timeout after xx minutes depending on your remote server, just reconnect or press enter in the shell once in a while...

An example of a superb freeware Secure Telnet client is Putty : Putty :

This 'discovery' really has saved me a lot of time because I don't have to upload the scripts to the remote server time and time again, pressing [save] is enough, heh (-:

past at sbox dot tugraz dot at
21-Feb-2003 09:17

As MySQL docs say, RAND() is not very usefull for generation of randomized result orders.

But this worked for me on Linux, however:
Somewhere before:
mt_srand((double)microtime()*1000000);

"SELECT *, " RAND(".mt_rand(0,86622340).")*10000%100 AS randomvalue ORDER BY randomvalue"

The upper value for mt_rand() has to be Quite Big to see any effect on MySQL's RAND(). The exact number shouldn't be significant. Note the multiplication and modulo; MySQL seems to count steadily upwards when generating random numbers, so we take some numbers from between.

soren at byu dot edu
14-Mar-2003 08:23

Let's say that you want to generate a MySQL password hash from a plain text password.  Normally, you would just submit the MySQL query "SELECT PASSWORD('password')", but if for some reason you can't access to MySQL database directly, then you can use the following function (translated right out of the MySQL source code):

function mysql_password($passStr) {
       $nr=0x50305735;
      $nr2=0x12345671;
       $add=7;
       $charArr = preg_split("//", $passStr);

       foreach ($charArr as $char) {
               if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
               $charVal = ord($char);
               $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
               $nr2 += ($nr2 << 8) ^ $nr;
               $add += $charVal;
       }

       return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
}

example:

<? print mysql_password("hello"); ?>

outputs:

70de51425df9d787

Which is the same result you get if you do "SELECT PASSWORD('hello')" directly in MySQL.  Hopefully you'll never be in a situation where you have to use this, but if you need it (like I did), it's here.

andre dot hoogeland at zonnet dot nl
01-May-2003 11:13

To find the holes in a table like this:
id| myField
3 | 6
4 | 0
5 | 1
6 | 5
7 | 4

I came up with this function:

function findhole( $table, $field ) {
 $retval = 0;
 $qrytxt = "SELECT $field FROM $table ORDER BY $field ASC";
 $query  = mysql_query( $qrytxt );
 $current = mysql_fetch_array( $query, MYSQL_ASSOC );
 if( $current[$field] != 0 || mysql_num_rows( $query ) < 1 ) {
   // no initial values: return 0
   return $retval;
 } else {
   do {
     $next = mysql_fetch_array( $query, MYSQL_ASSOC );
     // if successor doesn't appear in the table
     if( $next[$field] != $current[$field] + 1) {
       $retval = $current[$field] + 1;
       break;
     } else {
       $current = $next;
     }
   } while( true );
}
 return $retval;
}

And... to _fill_ the holes:

$fh = findhole( "myTable", "myField" ); // will return 2
mysql_query( "insert into myTable values( null, '$fh' )" );

I hope this is useful!
Regards, Andr� Hoogeland

Sparc at brturbo dot com
02-May-2003 10:35

At 25-Apr-2002 10:23 jeyoung at priscimon dot com said:
"If I establish two connections within the same PHP page, start a transaction in the first connection and execute an INSERT query in the second one, and rollback the transaction in the first connection, the INSERT query in the second connection is also rolled-back. "

As a matter of fact, you must call mysql_connect with the new_link parameter set to true to make a new connection, otherwise, you'll get the same resource id as returned by the first mysql_connect in the later connections.

Regards

leader at k2wrpg dot org
03-May-2003 11:27

While doing lots of mysql work remotely I got tired of having to upload my files over and over again to find problems in my sql queries. I was also having a hard time checking the data in the DB itself (especially when behind a firewall, ugh.) anyway I present to you a single file query analyzer. So I made an easier way. It�s not persistent so some complex statements using temp tables and such probably won't work, but for simple Selects, Updates, Inserts and Deletes, it works just fine. I would say it handles about 95% of the queries I want to run. Anyway I found it useful so I'll share. Just save the following code into a file named sqlquery.php, and put it on your server If you name it something else you'll have to change the target of the form. Also its totally insecure so if you�re worried about eavesdroppers don't use it.

Enjoy!

rather than post the code, here is a download:

Ronald
13-May-2003 09:45

Ask yourself why you want to use MySQL instead of other DB-engines. MySQL has some bugs and does not have all features which are standard in e.g. MSSQL or Oracle.
For more information about the bugs and missing features:



Ok, maybe this list is made by someone who is against MySQL, but I think it's worth reading for everyone.

santo at gimpyleg dot com
13-May-2003 09:49

Roland, maybe you should ask yourself the cost of SQL Server and Oracle versus the cost of MySQL.


add a note add a note

<msqlmysql_affected_rows>
 Last updated: Wed, 29 Jan 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Fri May 23 21:10:19 2003 CEST