Home >Backend Development >PHP Tutorial >Basic tutorial on PHP and MySQL (1)
The content of this article is about the basic tutorial of PHP and MySQL (1). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Interaction between HTML and php and MySQL
Why do we need to use a database?
The World Wide Web (WWW) is more than just a place for information. If you have something, make a website and share it with people all over the world. However, this is not an easy task. When the website gets bigger and bigger, you may encounter such problems:
The website contains too many things, so that visitors cannot get what they want quickly. This problem is fatal to a website to some extent.
Visitors want to provide you with information, and this information must be saved for later use.
Both the above two problems can be solved through the database!
In the world of WWW, databases are everywhere. As large as Yahoo!, Amazon, eBay, or as small as a simple message board, you can see the use of databases. It can even be said that the database is the foundation of all advanced applications.
Why use PHP and MYSQL
As far as I know, almost all major commercial website databases are based on SQL. Probably the most popular of these is Oracle. It's powerful and, of course, expensive. SQL is not an application, but a language. It is the abbreviation of Structured Query Language (Structured Query Language), which is used to operate and query the database.
In recent years, a number of companies have developed "open code" SQL applications, perhaps the most famous of which is MySQL. It is not only free, but for general small and medium-sized database applications, its performance is not inferior to Oracle.
To run MySQL on a website, you need a scripting language to interact with the database. In the past, Perl was the most popular. But now it seems that PHP is better. Don't ask me what's the difference?? I used to use Perl and it worked fine, but now everyone seems to prefer PHP. There is certainly a reason for its popularity.
Required software
This part of the content has been introduced in a previous article of ChinaByte Network Academy. Readers can refer to the article "Setting up local PHP development for win98". No further details will be given here.
HTML and PHP
Let’s see how PHP works. Take a look at the code below:
< html> < body> < ?php PRint "Hello, world."; ?> < /body> < /html>
When this page is requested, it will display "Hello, world" in the browser.
As you can see, the PHP script is embedded in the HTML file. It starts with " dd189d21cb00c2ed0988fa79d7d12853 ". Not only that, we can even embed HTML tags in PHP scripts:
< ?php print "< html>"; print "< body>"; print "Hello, world."; print "< /body>"; print "< /html>"; ?>
The two methods achieve the same goal, and the effect is the same. But in some special cases, it is more convenient to choose one of them.
PHP’s prints statement
The simplest interaction between PHP and HTML is achieved through the print statement:
< ?php print "Hello, world."; ?>
print is the simplest and most used function, used to display some text in the browser window , the echo function is similar to print, but you can use "," to separate multiple contents to be displayed, which is more convenient when displaying mixed string constants and variables.
There is also a printf function, which is used to format the output of numbers. You can display a number as an integer or in scientific notation.
In these functions, the use of parentheses is different:
echo must not have parentheses
printf must have
print optional
To display a string or a number It's very simple, just put the variable name or constant after the print statement. However, if you want to display an array, should you also write it like this:
print $myarray;
The output result will be "Array", and PHP tells you that $myarray is an array. This has some use when you're not sure whether a variable is an array, but right now we want to see the contents of the array.
You can use the implode function to convert an array into a string. It contains two parameters, the first is the array variable name, and the second is the delimiter of the array content. When the conversion is completed, the contents of the array are connected by delimiters to form a string:
$implodedarray = implode ($myarray, ", "); print $implodedarray;
You can also use the array_walk function to display the array. This function performs the same functional operation on each content of the array. For example:
function printelement ($element) { print ("$element< p>"); } array_walk($myarray, "printelement");
How to send data to MySQL with PHP
You should be familiar with HTML forms. The following piece of code is a very simple HTML form:
< html> < body> < form action=submitform.php3 method=GET> 姓 : < input type=text name=first_name size=25 maxlength=25> 名 : < input type=text name=last_name size=25 maxlength=25> < p> < input type=submit> < /form> < /body> < /html>
当你输入数据,并按下 submit 按钮后,这个表单将把数据发送到 submitform.php3 。再由这个 PHP 脚本来处理收到的数据,下面就是 submitform.php3 的代码:
< html> < body> < ?php mysql_connect (localhost, username, passWord); mysql_select_db (dbname); mysql_query ("INSERT INTO tablename (first_name, last_name) VALUES ('$first_name', '$last_name') "); print ($first_name); print (" "); print ($last_name); print ("< p>"); print (" 感谢填写注册表 "); ?> < /body> < /html>
在代码的第三行中的 "username" 和 "password" 分别代表你登陆 MySQL 数据库的账号和密码。在第五行中的 "dbname" 表示 MySQL 数据库的名称。在第十三行中的 "tablename" 是数据库中的一个数据表的名称。
当你按下 submit 之后,可以看到你输入的名字被显示在一个新的页面中。再看一看浏览器的 URL 栏,它的内容应该是像这样的:
… /submitform.php3?first_name=Fred&last_name=Flintstone
因为我们用到的是表单 GET 方法,因此数据是通过 URL 来传送到 submitform.php3 的。显然, GET 方法是有局限性的,当要传递的内容很多时,就不能用 GET 了,只能用 POST 方法。但不管用什么方法,当数据传送完成后, PHP 自动的为每一个表单中的字段建立一个和他们的名字(表单的 name 属性)相同的变量。
PHP 变量都已用一个美元符号开头的,这样,在 submitform.php3 脚本处理的过程中,就会有 $first_name 和 $last_name 这两个变量了,变量的内容就是你输入的内容。
我们来检查一下你输入的名字是否真的被输入到数据库中了。启动 MySQL, 在 mysql> 提示符下输入:
mysql> select * from tablename;
你应该可以得到一个表,内容就是你刚才输入的了:
+------------+------------+ | first_name | last_name | +------------+------------+ | 柳 | 如风 +------------+------------+ 1 rows in set (0.00 sec)
我们再来分析一下 submitform.php3 是如何工作的:
脚本的开始两行是:
mysql_connect (localhost, username, password); mysql_select_db (dbname);
这两个函数调用用来打开 MySQL 数据库,具体的参数的含义刚才已经说过了。
下面的一行是执行一个 SQL 语句 :
mysql_query ("INSERT INTO tablename (first_name, last_name) VALUES ('$first_name', '$last_name') ");
mysql_query 函数就是用来对选定的数据库执行一个 SQL 查询。你可以在 mysql_query 函数中执行任何的 SQL 语句。被执行的 SQL 语句必须作为一个字符串用双引号括起来,在其中的变量要用单引号括起来。
有一个要注意的事情: MySQL 的语句要用一个分号 (;) 结束,一行 PHP 代码同样也是这样,但是在 PHP 脚本中的 MySQL 语句是不能有分号的。也就是说,当你在 mysql> 的提示符下输入 MySQL 命令,你应该加上分号:
INSERT INTO tablename (first_name, last_name) VALUES ('$first_name', '$last_name');
但是如果这个命令出现在 PHP 脚本中,就要去掉那个分号了。之所以这样做,是因为有的语句,如 SELECT 和 INSERT ,有没有分号都可以工作。但是还有一些语句,如 UPDATE ,加上分号就不行了。为了避免麻烦,记住这条规则就好了。
PHP 如何从 MySQL 中提取数据
现在我们建立另外一个 HTML 表单来执行这个任务:
< html> < body> < form action=searchform.php3 method=GET> 请输入您的查询内容 : < p> 姓: < input type=text name=first_name size=25 maxlength=25> < p> 名 : < input type=text name=last_name size=25 maxlength=25> < p> < input type=submit> < /form> < /body> < /html>
同样,还要有一个 php 脚本来处理这个表单,我们再建立一个 searchform.php3 文件:
< html> < body> < ?php mysql_connect (localhost, username, password); mysql_select_db (dbname); if ($first_name == "") {$first_name = '%';} if ($last_name == "") {$last_name = '%';} $result = mysql_query ("SELECT * FROM tablename WHERE first_name LIKE '$first_name%' AND last_name LIKE '$last_name%' "); if ($row = mysql_fetch_array($result)) { do { print $row["first_name"]; print (" "); print $row["last_name"]; print ("< p>"); } while($row = mysql_fetch_array($result)); } else {print " 对不起,再我们的数据库中,没有找到符合的纪录。 ";} ?> < /body> < /html>
当你在表单中输入了要检索的内容,再按下 SUBMIT 按钮后,就会进入一个新的页面,其中列出了所有匹配的搜索结果。下面再来看看这段脚本到底是怎样完成搜索任务的。
前面的几条语句和上面讲到的一样,先是建立数据库连接,然后选定数据库和数据表,这些是每个数据库应用所必需的。然后有这样的几条语句:
if ($first_name == "") {$first_name = '%';} if ($last_name == "") {$last_name = '%';}
这几行用来检查表单的各字段是否为空。要注意的是那两个等号,因为 PHP 的语法大多源于 C 语言,这儿等号的用法也同 C 一样:一个等号是赋值号,两个等号才代表逻辑等于。还应该注意的是:当 IF 后条件为真时,后面要执行的语句是放在“ { ”和“ } ”中的,并且其中的每一条语句后面都要加上分号表示语句结束。
百分号 % 是 SQL 语言的通配符,理解了之一点后,就该知道这两行的意思了:如果“ FIRST_NAME ”字段为空,那么将列出所有的 FIRST_NAME 。后面的两句也是同样的意思。
$result = mysql_query ("SELECT * FROM tablename WHERE first_name LIKE '$first_name%' AND last_name LIKE '$last_name%'" ");
这一行完成了搜索的大部分工作。当 mysql_query 函数完成一个查询后,它返回一个整数标志。
查询从所有的记录中选出那些 first_name 列和 $first_name 变量相同,并且 last_name 列和 $last_name 变量值也相同的记录,放到暂存的记录集中,并用返回的整数作为这个记录集的标志。
if ($row = mysql_fetch_array($result)) { do { print $row["first_name"]; print (" "); print $row["last_name"]; print ("< p>"); } while($row = mysql_fetch_array($result)); } else { print " 对不起,再我们的数据库中,没有找到符合的纪录。 "; }
这是最后的一步,就是显示部分了。 mysql_fetch_array 函数先提取出查询结果的第一行的内容,在用 PRINT 语句显示出来。这个函数的参数就是 mysql_query 函数返回的整数标志。而 mysql_fetch_array 执行成功后,记录集指针会自动下移,这样当再一次执行 mysql_fetch_array 时,得到的就是下一行纪录的内容了。
数组变量 $row 被 mysql_fetch_array 函数建立并用查询的结果字段来填充,数组的每一个分量对应于查询结果的每一个字段。
如果有符合的纪录被找到,变量 $row 不会空,这时就会执行花括号中的语句:
do { print $row["first_name"]; print (" "); print $row["last_name"]; print ("< p>"); } while($row = mysql_fetch_array($result));
这是一个 do … while 循环。与 while 循环不同的是,它是先执行一遍循环循环体,然后在检查循环条件是否满足。由于已经知道在纪录集不为空的情况下,肯定至少要把循环体执行一遍,所以应该用到的是 do … while 而不是 while 循环了。在花括号中的就是要执行的循环体:
print $row["first_name"]; print (" "); print $row["last_name"]; print ("< p>");
然后就是检查 while 条件是否满足。 Mysql_fetch_array 函数再次被调用,来得到当前纪录的内容。这个过程一直循环,当没有下一条纪录存在时, mysql_fetch_array 返回 false ,循环结束,纪录集也就被完全的遍历了一次。
mysql_fetch_array($result) 返回的数组,不仅可以用字段名来调用,也可以像一般的数组那样,用下标来引用数组的各个分量。这样,上面的代码还可以写成这样:
print $row[0]; print (" "); print $row[1]; print ("< p>");
我们还可以用 echo 函数来把这四条语句写的紧凑一些:
echo $row[0], " ", $row[1], "< p>";
当没有任何匹配的纪录被找到时,在 $row 中就不会有任何内容,这时就会调用 if 语句的 else 子句了:
else { print " 对不起,再我们的数据库中,没有找到符合的纪录。 "; }
检查查询是否正常工作
你的那些 SELECT , DELETE 或者其它的查询是否能够正常工作呢?这是必须要搞清楚的,并且,千万不要轻易的就下结论。
检查一个 INSERT 查询相对的简单一些:
$result = mysql_query ("INSERT INTO tablename (first_name, last_name) VALUES ('$first_name', '$last_name') "); if(!$result) { echo "< b>INSERT 查询失败 :< /b> ", mysql_error(); exit; }
但是这个检查的方法对于 SELECT 查询是行不通的,这时,应该这样作:
$selectresult = mysql_query ("SELECT * FROM tablename WHERE first_name = '$first_name' AND last_name = '$last_name' "); if (mysql_num_rows($selectresult) == 1) { print "SELECT 查询成功。 "; } elseif (mysql_num_rows($selectresult) == 0) { print "SELECT 查询失败。 "; exit; }
而对于 DELETE 查询,就应该是这样了:
$deleteresult = mysql_query ("DELETE FROM tablename WHERE first_name = '$first_name' AND last_name = '$last_name' "); if (mysql_affected_rows($deleteresult) == 1) { print "DELETE 查询成功 "; } elseif (mysql_affected_rows($deleteresult) != 1) { print "DELETE 查询失败 "; exit; }
以上就是PHP 和 MySQL 基础教程(一)的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!
相关推荐:
mysql手册教程://m.sbmmt.com/course/37.html
mysql视频教程://m.sbmmt.com/course/list/51.html