Home  >  Article  >  php教程  >  php and mysql three-day pass

php and mysql three-day pass

高洛峰
高洛峰Original
2016-12-01 15:22:061033browse

1. Introduction to PHP/MySQL

You should have heard of Open Source Software (OSS), unless you have been living on Mars for the past six to eight months. This movement has huge impact and has attracted the attention of some major companies. Companies like Oralce, Informix, and many others have begun to port their main database products to one of the OSS products - the Linux operating system.

 If you have enough technical strength, having a complex and huge relational database system (RDBMS) will be even more powerful. But maybe you are just getting started with databases. You just read Jay's article and decided to build a data-driven website yourself. However, you may find that you lack the necessary resources to run an ASP server or an expensive database system (and you don't need these things). You need something free, Unix-ready.

  Then I recommend you to use PHP and MySQL. Together, these two things are the perfect combination for developing data-driven websites. In fact, I don’t need to waste any time explaining it. An unofficial survey organized by Netcraft showed that the number of hosts using PHP jumped from 7,500 in June 1998 to 410,000 in March 1999. Not bad right? The combination of these two software also won the Database Product of the Year Award at the Webcon98 conference and received a beautiful trophy.

 MySQL is a small and exquisite database server software, which is very ideal for small (of course not necessarily small) application systems. In addition to supporting standard ANSI SQL statements, it also supports multiple platforms. On Unix systems, the software supports multi-threaded operation, which can achieve very good performance. For users who do not use Unix, it can run as a system service on Windows NT systems, or as a normal process on Windows 95/98 systems.

 PHP is a server-side interpreted scripting language. If you have been exposed to ASP, then you should be familiar with embedding code in HTML pages. The PHP code is interpreted and converted into ordinary HTML page content on the server side and sent to the browser side. This mode allows us to use it to complete quite complex functions.

 In addition to being free (of course, MySQL also has some license restrictions), the PHP-MySQL combination can also run cross-platform, which means you can develop on Windows and then run on the Unix platform. In addition, PHP can also run as a standard CGI process, in which case it is an independent script interpreter or an embedded module of Apache.

 If you are interested in using other database servers, PHP also supports Informix, Oracle, Sybase, Solid and PostgreSQL, as well as common ODBC.

 PHP supports some cutting-edge technologies in Internet development. These technologies include authentication, XML, dynamic image generation, WDDX, shared memory, and dynamic PDF documents, to name a few. If you're still not satisfied, PHP is very easy to extend, so as long as you have programming skills, you can show off your skills yourself.
 The last thing to say is that both softwares are developed by a large number of programmers, so there are many support methods such as documentation and mailing lists. Bugs are fixed quickly, and if you ask for a new feature, someone will consider it and implement it if it's feasible.

 Enough said! Let’s take a look at what’s included in this tutorial.

The first lesson is about installing these two software in Unix and Windows environments. If you don't care much about this issue (maybe you are developing on the ISP's server), you can jump directly to the first sample program and start your wonderful journey from there.

In the second lesson, we will learn some more complex scripting functions, such as looping, processing user input, exchanging data with the database, etc.

The third lesson is about the confirmation function and how to make your script clear and concise.

 Let’s get started. >>
2. Install MySQL

Act quickly, get these software packages, and study them carefully. This is no easy task. You have many options in the process of obtaining the software package, compiling the software package, and installing the software package. Let's start with MySQL first, because it requires it to run PHP.

 MySQL central website is http://www.mysql.com/. In order to facilitate people to download and use it (this software is still relatively large), there are many mirror websites around the world. To use the Internet more effectively, please find a nearby website to download.

 You will also have a variety of choices at this time. If you are an enthusiast, you can download the source code; otherwise, there are pre-compiled binaries that run on various platforms and can be downloaded directly.

In addition, MySQL has also prepared a shareware version for Windows users, which has a slightly lower version number. If you want the latest version, you have to pay for a software license. MySQL also provides an ODBC driver to enable front-end applications to access the MySQL database. Some other details are available on its website, you can check it out.

 The pre-compiled Unix version and Windows version are very simple, just unpack and use it, no need to explain too much. Therefore, let's introduce the compilation of source code. Windows users, please remember that you need to run the mysqld program, which is located in the mysql/bin directory.

 Download the compressed software package file and place it in a directory. Use gzip and tar to decompress and unpack. A faster way is to use the following command:

gunzip < mysql-xxxx.tar.gz | tar xvf -

Where, xxxx is a version tag of your choice. The above command will create a directory named mysql-xxxx, and all source program files are in this directory. Enter the directory by executing the cd mysql-xxxx command, and carefully read the multiple README files and INSTALL files in it. These files may be of great help when encountering certain problems.

 MySQL comes with some convenient configuration scripts. You can let these programs do a lot of the work for you by simply typing ./configure. If you need to explicitly specify what to do, you can use the ./configure -help command, which will give you a list of options you can use. For example, if you are compiling on a machine with less memory, you can use the --with-low-memory option. I like to install MySQL in one total directory instead of multiple directories on the machine, so I will specify the installation directory and specify the -prefix option.

 You can also specify many other options, such as which parts to omit during compilation, which parts to keep, etc. We might as well assume that they are all installed in the server's /usr/local/mysql directory. This means we will type the ./configure -prefix=/usr/local/mysql command.

  When the configuration script runs, it will check your system and then generate some files to ensure smooth compilation. If the script fails, it will also display some helpful error messages telling you why it failed. We often encounter scripts that fail when looking for multi-threading library files. At this time, you should check whether MIT-pthreads has been installed in the system. If not, please install the software. Linux users must install LinuxThreads. These library files are very critical for MySQL's multi-threaded running mode (that is, running multiple versions of itself).

If everything goes smoothly, just type the make command and go make a cup of coffee. MySQL is a fairly complex program and takes a while to compile. If you find errors, check the documentation to see if you missed any preparations related to your operating system.

Next, type make. install command, all necessary files will be installed into the corresponding directories and you are almost ready to use it! If you are new to MySQL and have never installed MySQL before, you will have to create default permissions to install it, so type. ..scripts/mysql_install_db to make the corresponding settings.

 That’s it. All we need to do next is to automatically start the database when the machine starts and automatically close the database when it shuts down. There is also a dedicated script for this. The mysql.server start command can start the database, and mysql.server stop can shut down the database. If you want to start the database manually (so that you don't have to restart the machine), you can. Go to the top-level directory where MySQL is installed (/usr/local/mysql) and type the bin/safe_mysqld & command.

 We are halfway done. Next is the PHP part.
3. Install PHP

Well, by the time you get to this point, I hope you have MySQL installed and running. That's really fun! Here's PHP... The process is a little easier, but the sheer number of options is still overwhelming. You don't have to panic. You can always start over and recompile PHP to add or remove certain options as needed. The home of PHP is http://www.php.net/, which has a lot of information. From development project content to software bug reports. Like MySQL, you can choose a mirror website to download. Obviously, you have to download PHP in the Downloads section. There are not many choices here. There are some pre-compiled binaries, but they are experimental. If you are not on Windows platform, then download the source code and compile it yourself

.But let’s talk about Windows first. When using PHP, the general approach is to develop on a Windows system and then run it on a Unix server. You may end up choosing this method, which requires you to be familiar with installation on both platforms.

 After downloading the Windows binary file, you can use any ZIP decompression program you like to extract the files in the software package to the php3 directory on the C drive. The README file in the software package partially explains the details of the installation process, but here we will make a reader's digest of the key contents of this file: If you do not want to install PHP in the C:php3 directory, but elsewhere. directory, then you have to edit the .inf file in the extracted file.

 In the php3 directory, you will find a lot of .dll files. Move all .dll files whose file names do not start with php_ to the windowssystem directory. Then, rename the php.ini-dist file to php3.ini and move it to the windows directory. If you open this file, you'll see that there are a lot of interesting things you can change. Now, uncomment the line containing:

extension=php3_mysql.dll

 .

 If you are using an Apache server on a Win32 platform, please set up Apache so that it can recognize and interpret PHP files. You need to add the next line to the http.conf file or the srm.conf file (which one depends on the version of Apache software you are using):

 Action application/x-httpd-php3 "php3/php.exe "
  AddType application/x-httpd-php3 .php3

 Or, if you are using IIS, right-click the php_iis_reg.inf file and select "Install". You will need to restart your system for the changes you just made to take effect.

 OK, after talking about Windows, let’s talk about Unix. Of course, we have to start compiling from the source code. Similar to MySQL, download and unpack the source file. PHP also includes a configuration script, but you cannot completely use the default settings. Run the ./configure -help | more command to view new and interesting options page by page. You must choose whether to compile PHP into an external CGI program or an Apache embedded module. If you are using the Apache web server and you can recompile it, choose the inline module method, which runs faster and is easier to use. Otherwise, you can choose CGI method. In addition, you have to specify that the MySQL support part will be compiled into it.

  Now we assume that we want to compile it as an inline module with MySQL support part. If you later need to add other options or libraries, you can add them later. Type the following command:

./configure -with-apache=/path/to/apache/dir -with-mysql=/usr/local/mysql

If you plan to compile as an external CGI program, please remove it -with-apache option. After the configuration program is run, the corresponding system files will be created. Then simply execute the make command.

 It’s time to drink a cup of coffee again. If you feel restless at this point, don't worry. Everyone feels a little overwhelmed when they first install PHP. Just drink more coffee.

 If you choose the CGI program method to compile, you can use it now. Just copy the generated executable file to the CGI program directory. If you use the Apache embedded module method to compile, execute the make install command again and copy the relevant files to the Apache directory. In this directory, you can follow Apache's documentation to add the PHP module and recompile Apache.

Now you have to tell the web server how to process the page content through the PHP program. If you're not using Apache, you'll need to consult the documentation for your web server software to see how to get it to handle files with a .php3 suffix. Users of Apache 1.3.x version only need to add: AddType application/x-httpd-php3 .php3 to the httpd.conf or srm.conf file. If you are using a CGI program, you have to add the following content in front of AddType:

Action application/x-httpd-php3 "php3/php.exe

That's it. Your luck is not that bad, now MySQL is running, and PHP is working fine. Don't forget to check out the FAQ and software documentation when you encounter problems.

Since we've gone this far, Now we can practice it.

IV. The first script

If I tell you that the really sad part is over, you will be happy because the software installation process is always unpredictable. It can be said that there are huge differences between systems. But you are lucky, the database is running, PHP has been compiled and installed, and the web server can correctly handle files with the extension .php3. Let’s get started. Let’s write the first script. Create a text file and add the following content to it:





$myvar = "Hello World";
echo $myvar;
?>



 

Now, visit the corresponding URL, for example, http://myserver/test.php3. You should see the text containing "Hello World" on the page. If you see an error message, check the PHP documentation to see if the software is set up correctly.

That’s it! This is your first PHP program. If you look at the HTML source code of this page, you will find that there is only text like Hello World.

That’s because the PHP engine filters the file content, processes the code in it, and converts it into standard HTML.

 The first thing you may notice in the above program is the delimiter, which is the first few lines of ?lt;?php. This tag indicates that PHP code follows, and ?> indicates the end of the code. The power of PHP is that this code can be placed anywhere - and I mean anywhere - in many different ways. We'll see some interesting examples later, but for now let's start with the simplest one. If you prefer, you can set up PHP to use the short tags, , but this will conflict with XML, so use it with caution. If you're moving from ASP to PHP, you can even have PHP use <% and %> as delimiters.

  You will also notice the semicolon after each line. These semicolons are called delimiters and are used to separate different instructions. You can write all your PHP code on one line, using delimiters to separate commands. But that looks messy, so we put a new line after each semicolon. Remember, each line must end with a semicolon.

Finally, you will notice that the word myvar starts with a $ sign. This symbol tells PHP that this is a variable. We assign "Hello World" to the variable $myvar. A variable can be a number or an array. Regardless, all variables begin with the $ sign.

 The real power of PHP comes from its functions. Functions, basically process sequences of instructions. If you compiled all options into PHP, there would be over 700 functions in total. These functions let you do a lot of things.

Now let’s add some MySQL content. >>
5. Load the database

Now, we are going to add the MySQL content. An easy way to find out what options are included in PHP, or what's happening on the server side, is to use the function phpinfo(). Create a program like this:





phpinfo();
?>



 

Save this program and access this file in your browser. You'll see that the page contains some interesting and useful information, like this one. This information is about the server, web server internal environment variables, options included in PHP, etc. In the first section of Extensions, find the line starting with MySQL. If it is not found, it means that the MySQL support option is not compiled into PHP. You can double-check the installation steps and consult the PHP documentation to see if you missed anything.

 If you find the MySQL line, you can continue.

 Before reading data from the MySQL database, we must first put some data into the database. At this stage, there is no easy way to do this. Most PHP programs come with a data file that contains some data to create and activate the MySQL database. This process is outside the scope of this tutorial, so let me do it for you.

 MySQL uses its own user permissions table. During installation, a default user (root) will be created, which does not have a password. The database administrator can add users and grant users various permissions as needed, but this work can be written in another book, so we only use the root user. If you manage the server and database yourself, it is important to assign a password to the root user.

 In short, let’s continue talking about the database. Sorry for Win32 users, but you have to do some work under DOS. You have to use a DOS window, or type all commands in the Execute window. Don’t forget to include the directory name of MySQL/bin when entering the command. Unix users can enter commands in the MySQL bin directory, but the commands must start with ./ in order for the program to run.

 The first thing we need to do is actually create the database. At the command line, type the following command:

mysqladmin -u root create mydb

This creates a database named "mydb". The -u option tells MySQL that we are using the root user.

  Next, we need to add some data. The example data we use here is the employee database that everyone likes to use. We'll be using the data files I mentioned earlier. If you want to know more about this, you can check the manual provided by MySQL or visit the http://www.turbolift.com/mysql/ website. <

BR>
 Copy the following text to a file and store the file in the bin directory of MySQL (I assume the file name is mydb.dump).

CREATE TABLE employees ( id tinyint(4) DEFAULT '0' NOT NULL
AUTO_INCREMENT, first varchar(20), last varchar(20),
address varchar(255), position varchar(50), PRIMARY KEY (id) ,
UNIQUE id (id));INSERT INTO employees VALUES (1,'Bob','Smith',
'128 Here St, Cityname','Marketing Manager');

INSERT INTO employees VALUES (2,'John ','Roberts','45 There St ,
Townville','Telephonist');

INSERT INTO employees VALUES (3,'Brad','Johnson','1/34 Nowhere Blvd,
Snowston','Doorman ');

 

If the text is wrapped, please make sure that each INSERT statement starts on a new line. Now, we are going to add the data to the mydb database. At the command line, type the following command:

  mysql -u root mydb < mydb.dump

  You should not encounter any errors at this time. If something goes wrong, please check carefully to see if the error is caused by the wrapping of the text above. >>
6. Test

  OK, now we have imported the data into the database. Now let's process this data. Save the following text into a file, and save the file in the document directory of the Web server with the suffix .php3.





$db = mysql_connect("localhost", "root");
mysql_select_db("mydb",$db);
$result = mysql_query( "SELECT * FROM employees",$db);
printf("First Name: %s
n", mysql_result($result,0,"first"));
printf("Last Name: %sprintf("Address: %s
n", mysql_result($result,0,"address"));
printf("Position: %s
n", mysql_result($result,0,"position"));
?>



 Let me explain the above code. The mysql_connect() function is responsible for connecting to the MySQL database on the specified machine (in this case the machine is localhost) with the specified user name (in this case the user name is root). If you want to specify a user password, you can also pass it to this function. The result of the connection is saved in the variable $db.

  Then, the mysql_select_db() function tells PHP that the database we want to read is mydb. We can connect to multiple databases on multiple machines at the same time in the program, but currently we are limited to connecting to one database.

 Next, the mysql_query() function completes the most complex part. Using the connection result identifier just obtained, this function sends a row of SQL statements to the MySQL server for processing. The returned result is stored in the variable $result.

Finally, the mysql_result() function displays the values ​​of each field obtained by the SQL query command. Using the variable $result, we can find the first record, the record number is 0, and display the values ​​of each field in it.

  If you have never used Perl or C language before, the syntax format of the printf function will seem strange. In each line of the program above, %s represents which variable in the second part of the expression (for example, mysql_result($result,0,"position")) should be displayed as a string. For a more in-depth understanding of printf, see the PHP documentation.

 That’s it for this lesson. We have successfully compiled, installed and set up MySQL and PHP, and run a simple program to read information from the database. In Lesson 2, we will do some more complex work to display data from multiple rows and even exchange data with the database.


Statement:
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