Mysql connection and basic operation code in php

Source: Internet
Author: User
Tags php mysql

Occasionally, you need to use php to perform some mysql Database Operation tests. It is too troublesome to write by yourself. The search results generally contain a lot of useless code. Here we will summarize the operations of php mysql, I hope you don't have to worry about it in the future.

 

The Code is as follows:

<? Php

$ Dbhost = 'localhost'; // database server name

$ Dbuser = 'root'; // user name used to connect to the database

$ Dbpass = '000000'; // password used to connect to the database

$ Dbname = 'products'; // Database Name

 

// Connect to the database

$ Connect = mysql_connect ($ dbhost, $ dbuser, $ dbpass );

If (! $ Connect) exit ('database connection failed! ');

Mysql_select_db ($ dbname, $ connect );

Mysql_query ('set names utf8'); // sets the Encoding

 

// Query operation

$ SQL = "SELECT * FROM 'category '";

$ Result = mysql_query ($ SQL );

While ($ row = mysql_fetch_array ($ result )){

Echo $ row ['id'];

}

// Insert operation

$ SQL = "INSERT INTO 'category '('id', 'name') VALUES (NULL,'". $ name ."')";

$ Result = mysql_query ($ SQL );

If (mysql_affected_rows ()){

Echo 'insert successful, insert ID: ', mysql_insert_id ();

} Else {

Echo 'insertion failed: ', mysql_error ();

}

// Modify the operation

$ SQL = "UPDATE 'category' SET 'name' = '". $ name. "'where' id' ='". $ id ."'";

$ Result = mysql_query ($ SQL );

If (mysql_affected_rows ()){

Echo 'modification successful! ';

}

// Delete operation

$ SQL = "DELETE FROM 'category' WHERE 'id' = '". $ id ."'";

$ Result = mysql_query ($ SQL );

If (mysql_affected_rows ()){

Echo 'deleted! ';

}

// Close the connection

Mysql_close ($ connect );

?>

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.