|
|
mysql_query() function in PHP
|
Tutorials » Php »
|
Topic |
What is mysql_query() function in PHP?
How does mysql_query() works?
|
|
Explanation | |
|
This mysql_query()function in php is used to pass a sql query to mysql database.
Syntax
resource mysql_query ( string query [, resource link_identifier])
Returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.
mysql_query() sends a query to the currently active database on the server that is
associated with the specified link identifier. If link_identifier is not specified,
the last opened link is assumed. If no link is open, the function tries to establish a link as if
mysql_connect() was called with no arguments, and use it. The result of the query is buffered.
For Sql query's such as SELECT,SHOW,EXPLAIN or DESCRIBE statements, mysql_query function returns a resource identifier
or FALSE if the query was not executed correctly. For other type of SQL statements, mysql_query() returns
TRUE on success and FALSE on error.
Example
<?php
//Attempt to connect to the default database server
$conn = mysql_connect("mysql_host", "mysql_user", "mysql_password")
or die ("Could not connect");
//select database
$db = mysql_select_db('my_database');
//simple query
$sql="select * from my_table";
// execute the query
$result = mysql_query($sql,$conn);
if (!$result)
die('Invalid query: ' . mysql_error());
mysql_free_result($result);
?>
|
In the above example query is successfully executed and the result of the query is stored in $result.
<?php
//Attempt to connect to the default database server
$conn = mysql_connect("mysql_host", "mysql_user", "mysql_password")
or die ("Could not connect");
//select database
$db = mysql_select_db('my_database');
//simple query
$sql="select name from my_table where";
// execute the query
$result = mysql_query($sql,$conn);
if (!$result)
die('Invalid query: ' . mysql_error());
mysql_free_result($result);
?>
|
In the above code query passed to mysql_query is invalid query,
so the query is not executed and error message is displayed by mysql_error() function.
See also: |
|
|
|