w3resource logo


PHP mysql_query function

PHP : mysql_query() function

rating has average rating 9 out of 10. Total 8 users rated.

<<PreviousNext>>

Description

The mysql_query() is used to execute query on the default database.

Version

(PHP 4 and above)

Syntax

mysql_query(query, connection)

Parameters

Name Description Required/ Optional Type
query A SQL query. Required String
connection The MySQL connection. Before performing any operation on a MySQL database, it is required to set a connection to the mysql database you want to work with. And this is done by mysql_connect() function. This function takes three parameters, name of the host, username with which you want to perform tasks with the mysql database in question, and password of that user. As soon as a successful connection is established, you can perform the operations on that mysql database. In case, no such connection is found, it will try to create one without any arguments, i.e. mysql_connect() without any parameters. If it fails to connect to a mysql database, it will generate a warning (E_WARNING) but not an error. Optional Resource

Return value

Query handle for successful SELECT, SHOW, DESCRIBE, EXPLAIN and other statements or FALSE on error.

Value Type : Resource.

Example :

<?php
$con = mysql_connect("localhost", "root", "mypass") or
    die("Could not connect: " . mysql_error());
mysql_select_db("tutorials");
$result = mysql_query("select * from tutorials");
echo "<h2>Here is a list of the topics:</h2>";
while ($row = mysql_fetch_array($result)) {
    echo $row['name']."<br />";
}
mysql_close($con);
?>

Output :

Here is a list of the topics:

html
css
sql
mysql
javascript
php
quick reference

See also

PHP Function Reference

mysql_connect()

mysql_error()

mysql_real_escape_string()

mysql_result()

mysql_fetch_assoc()

<<PreviousNext>>