mysql_query() function
In the PHP MySQL function library, the mysql_query() function is used to send and execute SQL statements to MySQL.
For SQL that does not return a result set with data, such as UPDATE, DELETE, etc., TRUE is returned when the execution is successful, and FALSE is returned when an error occurs; for SELECT, SHOW, EXPLAIN or DESCRIBE statements, a resource is returned Identifier, returns FALSE if the query was executed incorrectly.
mysql_query() syntax:
resource mysql_query( string query [, resource connection] )
mysql_query() parameter description:
Parameter | Description |
---|---|
query | SQL statement to send query |
connection | Optional, Connect to the databaseIdentifies the resource, if not specified, the previous connection will be used |
Prompt
If there is no open connection, this function will try to call the mysql_connect() function without parameters to establish a connection
For queries that return dataset, even if The return result is 0 (that is, there are no records that meet the query conditions), and the resource identifier is still returned instead of FALSE
Example 1:
<php $conn = @mysql_connect("localhost","root","root123"); if (!$conn){ die("连接数据库失败:" . mysql_error()); } mysql_select_db("test", $conn); $result = mysql_query("SELECT * WHERE 1=1") or die("无效查询: " . mysql_error()); ?>
The query statement in this example has an error in SQL syntax , so mysql_query() fails and returns FALSE.
Example 2:
<php $conn = @mysql_connect("localhost","root","root123"); if (!$conn){ die("连接数据库失败:" . mysql_error()); } mysql_select_db("test", $conn); mysql_query("set names 'gbk'");//为避免中文乱码做入库编码转换 $password = md5("123456");//原始密码 12345 经过加密后得到加密后密码 $regdate = time();//得到时间戳 $sql = "INSERT INTO user(username, password, email, regdate)VALUES('小王', '$password', '12345@163.com', $regdate)"; if(!mysql_query($sql,$conn)){ echo "添加数据失败:".mysql_error(); } else { echo "添加数据成功!"; } ?>
This example writes data to the user table and returns TRUE successfully, otherwise it returns FALSE (use the ! symbol to judge).
The above is the detailed content of Use the mysql_query() function to execute SQL statements. For more information, please follow other related articles on the PHP Chinese website!