PHP mysql_query() Function
Definition and Usage
The mysql_query() function executes a MySQL query.
Syntax
mysql_query(query,connection)
Parameter | Description |
---|---|
query | Required. Specifies the SQL query to be sent. Note: The query string should not end with a semicolon. |
connection | Optional. Specifies the SQL connection identifier. If not specified, it uses the last opened connection. |
Description
If no connection is open, this function will attempt to call the mysql_connect() function without parameters to establish a connection and use it.
Return value
The mysql_query() function returns a resource identifier for SELECT, SHOW, EXPLAIN, or DESCRIBE statements, and returns FALSE if the query execution is incorrect.
For other types of SQL statements, mysql_query() returns TRUE on success and FALSE on error.
A non FALSE return value means that the query is valid and can be executed by the server. This does not indicate 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().
Instance
Example 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); ?>
Example 2
Create a new database 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(); } ?>