PHP mysql_query() 函数

定义和用法

mysql_query() 函数执行一条 MySQL 查询。

语法

mysql_query(query,connection)
参数 描述
query 必需。规定要发送的 SQL 查询。注释:查询字符串不应以分号结束。
connection 可选。规定 SQL 连接标识符。如果未规定,则使用上一个打开的连接。

说明

如果没有打开的连接,本函数会尝试无参数调用 mysql_connect() 函数来建立一个连接并使用之。

返回值

mysql_query() 仅对 SELECT,SHOW,EXPLAIN 或 DESCRIBE 语句返回一个资源标识符,如果查询执行不正确则返回 FALSE。

For other types of SQL statements, mysql_query() returns TRUE when executed successfully and FALSE when an error occurs.

A non FALSE return value means that the query is valid and can be executed by the server. This does not mean anything about the number of rows affected or returned. It is very likely that a query was executed successfully but did not affect or return any rows.

Tips and comments

Note:This function automatically reads and caches the record set. To run a non-cached query, please use mysql_unbuffered_query()

একটি উদাহরণ

উদাহরণ 1

<?php
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$sql = "SELECT * FROM Person";
mysql_query($sql,$con);
// Some code
mysql_close($con);
?>

উদাহরণ 2

A new database is created using the mysql_query() function:

<?php
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$sql = "CREATE DATABASE my_db";
if (mysql_query($sql,$con))
  {
  echo "Database my_db created";
  }
else
  {
  echo "Error creating database: " . mysql_error();
  }
?>