Home Backend Development PHP Tutorial Detailed explanation of the interactive use of PHP and MySQL_PHP tutorial

Detailed explanation of the interactive use of PHP and MySQL_PHP tutorial

Jul 21, 2016 pm 04:06 PM
mysql php and interaction generation use create database of automatic Detailed explanation connect

Detailed explanation of the interaction between PHP and MySQL
1. Create the code to automatically connect to the database and generate some necessary codes. If we carefully study the connection function of the database, we will find this line of code.
$link_id=@mysql_connect($hostname,$username,$password);
So we just add the following code to the include file connect.inc. connect.inc$username='phpstar';$password='phpstar';$dbname='script';
$tablename='php_script';$link_id= mysql_connect($hostname,$username,$password);
if (! $link_id){ echo 'Error ';
echo 'Connection to PHP has failed.';echo '';exit(); }?>
Add this program to every PHP script , so that a database connection is established when the script is run. Because our program is interactive and we need to process the information entered by the user, the following code should also be added to the file.
if (count($HTTP_GET_VARS)) /*If the user information is input in GET mode, read the data*/
{ while ( list($key, $value) = each ($HTTP_GET_VARS)) /*Function list() and each() cooperate to process input data*/
{ $arr_request[strtolower($key)] = $value; } }
/*The function strtolower() converts the distinguishing key string to lowercase, which is beneficial to subsequent programming, and forms them into an array*/
if (count($HTTP_POST_VARS)) /*User Information is entered in POST mode*/
{ while (list($key, $value) = each ($HTTP_POST_VARS))
{ $arr_request[strtolower($key)] = $value; } } //We Also define the HTML output each time
function html_header($title){ echo '';echo "$title"; <br>echo ' '; }function html_footer()
{ global $link_id;@mysql_close($link_id);echo ' ';}//There is also an error message processing
function html_error_exit($msg){ $errno = mysql_errno(); /*Get the error message code*/
$error = mysql_error(); /*Get the error information, the two work together for troubleshooting*/
echo 'Error';echo $msg;
echo "
Error: ($errno) $error
";echo '';exit(); }?>
Okay! Let’s do it Some commonly used codes are placed here, which is convenient to use. 2. There are two methods for creating database tables: entering commands in a DOS environment, but it is easy to make mistakes.
Using programs, even if mistakes are made, it is easy to modify them. .We use a program to create a data table. Because our program needs to be universal, the fields in the table are not important. Here we just simply create one. The table has the following management fields:
key_script This is a An auto-increment field, which ensures that the records in the table are unique. date_created This is a date field, which stores the time when the record was created
data_updated This is also a date field, which stores the time when the record was last updated
flag_deleted stores whether the record has been deleted, "Y": the record has been deleted, "N": the record has not been deleted, you can use the following fields to store information. script_name program name
script_size program bytes script_describe program Brief description author_name program author name author_email program author's email
author_homepage Create the program under the program author's homepage: createTable.php$str_sql="create table php_script(
key_script int(10) unsigned DEFAULT '0' NOT NULL auto_increment,
date_created datetime DEFAULT '0000-00-00 00:00:00',
date_updated datetime DEFAULT '0000-00-00 00:00 :00',
flag_deleted enum('Y','N') DEFAULT 'N' NOT NULL,
script_name VARCHAR(20) NOT NULL,script_size VARCHAR(10) NOT NULL,
script_describe VARCHAR( 200) NOT NULL,author_name VARCHAR(20) NOT NULL,
author_email VARCHAR(20) NOT NULL,author_homepage VARCHAR(30) NOT NULL,
primary key (key_script))";$result=mysql_db_query($dbname ,$str_sql,$link_id);
if ($result){echo "ok! Table $tablename has been created!";}else{echo "Failed!";}
?>OK! Our The table is built! 3. Generate the insert record code program. It seems that we should display the record first and then insert the record, but since we don't have a record yet, we put this step first.
First, create an HTML form to allow users to enter relevant information. Second, create the MySQL code that can insert the form information.good! Let's start. The form style is as follows: Program name: File size: Program description: Author name:
Author email address: Author's homepage: The MySQL code that can insert form information is as follows: script_insert_action.phprequire( 'connect.inc');if($arr_request['action']=='insert'){
$current_date=date('Y-m-d H:i:s');/*Press the current time to YYYY-MM -DD ​​HH:MM:SS arrangement*/
/*The SQL code will be dynamically generated below, in which the auto-increment fields we define are generated by MySQL itself*/
/*In addition, the default value of the flag_deleted field It's "N", so we don't need to mention these two items here*/
/*Everyone knows: PHP strictly distinguishes the functions of single quotes (') and double quotes ("). And our author The name is in the array*/
/*We need to reference the array like this: $arr_request['author_name'], note that there are single quotes (')*/
/*When we enter the value of the insert statement It should be like this: VALUES('$current_date') */
/*If we don't deal with these semicolons, this will happen: VALUES('$arr_request['author_name']') */
/*Can PHP handle this situation? Of course not, so we think of ways to deal with it*//*Here, we use the following technique to avoid this problem; of course, there are other methods you can think of first. Think about it! */
$script_name=$arr_request['script_name'];
$script_size=$arr_request['script_size'];
$script_describe=$arr_request['script_describe'];
$author_name=$arr_request['author_name'];
$author_email=$arr_request['author_email'];
$author_homepage=$arr_request['author_homepage'];/*With this replacement, the processing will be much better */
$str_sql="insert into $tablename(date_created,date_updated,script_name,
script_size,script_describe,author_name,author_email,author_homepage)VALUES(
'$current_date','$current_date','$ script_name','$script_size',
'$script_describe','$author_name','$author_email','$author_homepage')";
$result=mysql_db_query($dbname,$str_sql,$link_id) ;/* Here is a simple feedback to the user*/
if (!$result){html_error_exit('MySQL insertion command failed!');}else(html_header('Success');
echo"< center> ";echo('MySQL insertion command successful');echo"
";echo"html_footer();)?>
OK! The insert record function is completed!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/315361.htmlTechArticleDetailed explanation of the interaction between PHP and MySQL 1. Create the code to automatically connect to the database and generate some necessary code. We carefully If you study the connection function of the database, you will find that this is a line of code...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

How to fill in mysql username and password How to fill in mysql username and password Apr 08, 2025 pm 07:09 PM

To fill in the MySQL username and password: 1. Determine the username and password; 2. Connect to the database; 3. Use the username and password to execute queries and commands.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

How to copy and paste mysql How to copy and paste mysql Apr 08, 2025 pm 07:18 PM

Copy and paste in MySQL includes the following steps: select the data, copy with Ctrl C (Windows) or Cmd C (Mac); right-click at the target location, select Paste or use Ctrl V (Windows) or Cmd V (Mac); the copied data is inserted into the target location, or replace existing data (depending on whether the data already exists at the target location).

Understand ACID properties: The pillars of a reliable database Understand ACID properties: The pillars of a reliable database Apr 08, 2025 pm 06:33 PM

Detailed explanation of database ACID attributes ACID attributes are a set of rules to ensure the reliability and consistency of database transactions. They define how database systems handle transactions, and ensure data integrity and accuracy even in case of system crashes, power interruptions, or multiple users concurrent access. ACID Attribute Overview Atomicity: A transaction is regarded as an indivisible unit. Any part fails, the entire transaction is rolled back, and the database does not retain any changes. For example, if a bank transfer is deducted from one account but not increased to another, the entire operation is revoked. begintransaction; updateaccountssetbalance=balance-100wh

How to view mysql How to view mysql Apr 08, 2025 pm 07:21 PM

View the MySQL database with the following command: Connect to the server: mysql -u Username -p Password Run SHOW DATABASES; Command to get all existing databases Select database: USE database name; View table: SHOW TABLES; View table structure: DESCRIBE table name; View data: SELECT * FROM table name;

See all articles