Apache 配置CGI脚本操作数据库

来源:转载

关于Apache的配置请先参考博文 Apache配置
本文假设我们已经配置好了一个基本的Apache服务器,接下我们就要配置如何通过CGI脚本(UNIX shell、Perl、PHP、Python等脚本语言写成的程序)去实现一个网站的后端数据库连接及简单操作

PHP实现

1.在安装好的Apache服务其中安装配置php环境

yum install php -y

php的配置文件就不翻译了

[[email protected] html]# cat /etc/httpd/conf.d/php.conf ## Cause the PHP interpreter to handle files with a .php extension.#<FilesMatch /.php$> SetHandler application/x-httpd-php #在文件扩展名与特定的处理器之间建立映射</FilesMatch>## Allow php to handle Multiviews#AddType text/html .php## Add index.php to the list of files that will be served as directory# indexes.#DirectoryIndex index.php## Uncomment the following lines to allow PHP to pretty-print .phps# files as PHP source code:##<FilesMatch /.phps$># SetHandler application/x-httpd-php-source#</FilesMatch>## Apache specific PHP configuration options# those can be override in each configured vhost#php_value session.save_handler "files"php_value session.save_path "/var/lib/php/session"[[email protected] html]# 

2.安装php的数据库支持:

[[email protected] conf.d]# yum install -y php-mysql

注意:

注意当web服务器连接的数据库在远程时,需要改变Selinux:# setsebool -P httpd_can_network_connect_db=1# setsebool -P httpd_can_network_connect=1 (如果数据库的端口不是3306时,需要改此项)

重启httpd服务后,测试网页是否访问正常.
在网站根目录下建立一个php脚本文件(例如halo.php)

[[email protected] html]# cat halo.php <?phpecho "This is a test for PHP script!";?> [[email protected] html]# 

3. 测试数据库连接

例如我们在网站根目录下建立了一个文件index.php

[[email protected] html]# cat index.php <?php$servername = "localhost";$username = "root";$password = "halo";/ 创建连接$conn = new mysqli($servername, $username, $password);// 检测连接if ($conn->connect_error) { die("连接失败: " . $conn->connect_error);} echo "连接成功";?>[[email protected] html]# 

4.PHP简单操作数据库(创建一个数据库)

[[email protected] html]# cat halo.php <?phpecho "This is a test for PHP script!";?> [[email protected] html]# cat index.php <?php$servername = "localhost";$username = "root";$password = "halo";// 创建连接$conn = new mysqli($servername, $username, $password);// 检测连接if ($conn->connect_error) { die("连接失败: " . $conn->connect_error);}// 创建数据库$sql = "CREATE DATABASE lockeyDB";if ($conn->query($sql) === TRUE) { echo "数据库创建成功"; $sql1 = "SHOW DATABASES;"; $result = $conn->query($sql1);if ($result) { // 输出数据 var_dump($result);} else { echo "0 结果";}} else { echo "Error creating database: " . $conn->error;}$conn->close();?> [[email protected] html]# 

登录数据库验证操作

[[email protected] html]# mysql -uroot -phaloWelcome to the MariaDB monitor. Commands end with ; or /g.Your MariaDB connection id is 8Server version: 5.5.52-MariaDB MariaDB ServerCopyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.Type 'help;' or '/h' for help. Type '/c' to clear the current input statement.MariaDB [(none)]> SHOW DATABASES;+--------------------+| Database |+--------------------+| information_schema || lockeyDB || mysql || performance_schema |+--------------------+4 rows in set (0.01 sec)MariaDB [(none)]> 

分享给朋友:
您可能感兴趣的文章:
随机阅读: