PHP头条
热点:

PHP and MySQL Web Development习题作业集,mysqldevelopment


php和数据库的学习,来自于书本PHP and MySQL web Development.每章都是重点介绍还有些代码。

ubuntu安转mysql

Ubuntu上安装MySQL非常简单只需要几条命令就可以完成。

1. sudo apt-get install mysql-server

2. apt-get isntall mysql-client

3.  sudo apt-get install libmysqlclient-dev

安装过程中会提示设置密码什么的,注意设置了不要忘了,安装完成之后可以使用如下命令来检查是否安装成功:

sudo netstat -tap | grep mysql

通过上述命令检查之后,如果看到有mysql 的socket处于 listen 状态则表示安装成功。

登陆mysql数据库可以通过如下命令:

mysql -u root -p

-u 表示选择登陆的用户名, -p 表示登陆的用户密码,上面命令输入之后会提示输入密码,此时输入密码就可以登录到mysql。

安装php

apt-get install php5

安装php-fpm

apt-get install php5-fpm

修改nginx配置文件,碰到php的传递到php处理

        location ~ \.php$ {
            include fastcgi_params;
            fastcgi_pass localhost:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /data/php/$fastcgi_script_name;
            fastcgi_param QUERY_STRING $query_string;
        }
记得 nginx -s reload 重启生效

修改php-fpm配置文件

 vim /etc/php5/fpm/php-fpm.conf

增加端口处理,

listen = 127.0.0.1:9000

记得重启生效

/etc/init.d/php5-fpm restart

验证

新建/data/php/ 目录下 index.php文件

<?php
    echo "php"
?>
输入网址

http://47.93.38.195/index.php

回复php表示成功

静态的网址成功,接下来需要动态的数据,实现数据的上传和返回。

首先还是需要配置nginx.conf文件

        location ~ \.php$ {
            fastcgi_pass localhost:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /data/php/$fastcgi_script_name;
            fastcgi_param QUERY_STRING $query_string;

            fastcgi_param REDIRECT_STATUS 200;
            fastcgi_param REQUEST_METHOD  $request_method;
            fastcgi_param CONTENT_TYPE    $content_type;
            fastcgi_param CONTENT_LENGTH  $content_length;
        }

fastcgi_param REDIRECT_STATUS 200;
参数不知道什么意思,因为不知道,因为这个参数获取的post值为空,网上到处查资料也没有教给我,还是要多看nginx配置手册才是,网上讲得乱七八糟的。

编写orderform.php文件

<form action="processorder.php" method="post">
    <table >
        <tr >
            <td >Item</td>
            <td >Quantity</td>
        </tr>

        <tr>
            <td>Tires</td>
            <td><input type="text" name="tireqty" size="3" maxlength="3"/></td>
        </tr>

        <tr>
            <td>Oil</td>
            <td><input type="text" name="oilqty" size="3" maxlength="3" /></td>
        </tr>

        <tr>
            <td>Spark Plugs</td>
            <td><input type="text" name="sparkqty" size="3" maxlength="3"/></td>
        </tr>

        <tr>
            <td colspan="2" >
            <input type="submit" value="Submit Order" /></td>

        </tr>



    </table>



</form>

编写它的处理函数processorder.php

<!DOCTYPE html>

<html>

<head>
    <title>
        Bob's Auto Parts - Order Results

    </title>

    <h1>Bob's Auto Parts</h1>
    <h2>Order Results</h2>

    <?php
        echo '<p>Order processed.</p?>';
    ?>

    <?php
        echo "<p>Order processed at ".date('H:i, jS F Y')."</p>";
    ?>

    <?php
        // create short variable names
    $tireqty = $_POST['tireqty'];
    $oilqty = $_POST['oilqty'];
    $sparkqty = $_POST['sparkqty'];

    ?>

    <?php

    echo '<p>Your order is as followes:</p>';
    echo htmlspecialchars($tireqty).' tires<br/>';
    echo htmlspecialchars($oilqty).' bottles of oil<br/>';
    echo htmlspecialchars($sparkqty).' spark plugs<br />';
    ?>

</head>

</html>
输入http://47.93.38.195/orderform.php

输入数据

CTYPE html>
Bob's Auto Parts
Order Results

Order processed.

Order processed at 20:55, 20th August 2017

Your order is as followes:
5 tires
48 bottles of oil
20 spark plugs

至此,动态网站已经建立。

Introduction

Reading this book will enable you to build real-world, dynamic web application. If you've built websites using plain HTML, you realize the limitations of this approach.

Static content from a pure HTML. website is just that -- static. It stays the same unless you physically update it.


Chapter 1 PHP Crash Course

1. This chapter begins with the example of an online product order form to show how variables, operators, and expressions are used in PHP. It also covers variables types and operator precedence. You will learn how to access form variables and manipulate them by working out the total and tax on a customer order.

2. The PHP has been interpreted and executed on the web server, as distinct from JavaScript and other client-side technologies interpreted and executed within a web browser on a user's machine.

3. The PHP code in the preceding example began with <?php and ended with ?>

Any text between the tags is interpreted as PHP.

Any text outside these tags is treated as normal HTML.

4. Semicolons separate statements in PHP much like periods separate sentences in English.

5. You can recognize variable names in PHP because they all start with a dollar sign($).

$_POST['tireqty]

$_POST is an array containing data submitted via a HTTP POST request - that is, the form method was set to POST.

There are three of these arrays that may contain form data: $_POST, $_GET, $_REQUEST.

5. The following statement creates a new variable name $tireqty and copies the contents of $_POST['tireqty] into new variable

$tireqty = $_POST['tireqty];

6. The period is the string concatenation operator, which adds strings (pieces of text) together.

echo htmlspecialchars($tireqty). ' tires<br/>';

7.或者

$tireqty = htmlspecialchars($tireqty);
echo "$tireqty tires<br/>";
8. PHP tries to evaluate strings in double quotation marks, resulting in the behavior shown earlier. Single-quoted strings are treated as true literals.

9. Data type

Integer Float String Boolean Array Object

NULL, resource, callable

Callables are essentially functions that are passed to other functions.

主要讲述基本的语法和前面学习过的语言类似,所以后面看代码再熟悉。


第二章 数据存储

这章主要讲述open write read close 与文件相关的函数,进行数据的存储。

在使用fopen在服务器创建文件的时候,首先会碰到权限不够的问题。

第一步就是手动在服务器上创建文件,文件的目录和文件名如果没有指定document_root的话,就用绝对路径,

然后还要修改文件的权限,一般默认文件的权限是644,所以这里需要修改成666

用以下命令

chmod 666 orders.txt

完整的文件读写的php示例

<?php
    // create short variable names
    $tireqty = (int) $_POST['tireqty'];
    $oilqty = (int) $_POST['oilqty'];
    $sparkqty = (int) $_POST['sparkqty'];
    $address = preg_replace('/\t|\R/', ' ', $_POST['address']);
    $document_root = $_SERVER['DOCUMENT_ROOT'];
    $date = date('H:i, jS F Y');
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Bob's Auto Parts - Order Results</title>

    </head>
    <body>
        <h1>
            Bob's Auto Parts
        </h1>
        <h2>Order Results</h2>
    <?php
        echo '<p>Order processed at '.$date.'</p>';
        echo '<p>Your order is as follows: </p>';
        $totalqty = 0;
        $totalamount = 0.00;
        define ('TIREPRICE', 100);
        define ('OILPRICE', 10);
        define ('SPARKPRICE', 4);

        $totalqty = $tireqty + $oilqty + $sparkqty;
        echo '<p>Items ordered: '.$totalqty.'<br/>';
        if ($totalqty == 0) {
            echo 'You did not order anything on the previous page!<br/>';
        } else {
            if ($tireqty > 0)
                echo htmlspecialchars($tireqty).' tires<br/>';
            if ($oilqty > 0)
                echo htmlspecialchars($oilqty).' bottles of oil<br/>';
            if ($sparkqty > 0)
                echo htmlspecialchars($sparkqty).' spark plugs<br/>';
        }

        $totalamount = $tireqty * TIREPRICE + $oilqty * OILPRICE + $sparkqty * SPARKPRICE;
        echo 'Subtotal: $'.number_format($totalamount, 2).'<br/>';
        $taxrate = 0.10;
        $totalamount = $totalamount * (1 + $taxrate);
        echo 'Total including tax: $'.number_format($totalamount, 2)."</p>";
        echo '<p>Address to ship to is '.htmlspecialchars($address).'</p>';
        $outputstring = $date.'\t'.$tireqty.' tires\t'.$oilqty.' oil\t'.$sparkqty.
            ' spark plugs\t$'.$totalamount.'\t'.$address.'\n';

        // open file for appending
        @$fp = fopen('/data/php/orders/orders.txt', 'ab');
        if (!$fp) {
            echo '<p><strong>Your order could not be processed at this time Please try again later.</strong></p>';
            exit;
        }
        flock($fp, LOCK_EX);
        fwrite($fp, $outputstring, strlen($outputstring));
        flock($fp, LOCK_UN);
        fclose($fp);
        echo '<p>Order written </p>';
    ?>

    </body>

</html>
读取文件方式

<?php
    $document_root = $_SERVER['DOCUMENT_ROOT'];
?>

<html>
    <head>
        <title>Bob's Auto Parts - Order Results</title>
    </head>
<body>
    <h1>Bob's Auto Parts</h1>
<h2>Costomer Orders</h2>
<?php
    @$fp = fopen("$document_root/orders/orders.txt", 'rb');
    flock($fp, LOCK_SH);

    if (!$fp) {
        echo "<p><strong>No orders pending.<br/>Please try again later.</strong></p>";
        exit;
    }
    while (!feof($fp)) {
        $order = fgets($fp);
        echo htmlspecialchars($order). "<br/>";
    }
    flock($fp, LOCK_UN);
    fclose($fp);
?>

</body>

</html>
$order = fgetcsv($fp, 0, "\t");

This code would retrieve line from the file and break it up wherever a tab (\t) was encountered. The results are returned in an arry.

readfile

file_exists()

filesize()

delete a file: unlink()

rewind()

fseek()

ftell

Lock files

LOCK_UN The existing lock is released.

数据库存储数据


第三章 使用数组

$products = array(‘Tires', 'Oil', 'Spark Plugs');

$products = array('Tires', 'Oil', 'Spark Plugs'];

遍历数组

排序 sort()

asort()

ksort()

array_multisort()

终于又进步了一点点

显示图片,是利用的html读取图片的规则,并没有使用什么其它的技术,有个问题是无法使用php读取图片,所以这里都是无奈之举。

  1 <?php
  2     $pictures = array("http://47.93.38.195/flowers/flower_honeysuckle.JPG",
  3         "http://47.93.38.195/flowers/flower_morning_glory.JPG",
  4         "http://47.93.38.195/flowers/flower_peachblossom.JPG");
  5     shuffle($pictures);
  6 ?>
  7 
  8 <!DOCTYPE HTML>
  9 <html>
 10 <head>
 11     <title>Beautiful Flowers</title>
 12 </head>
 13 <body>
 14     <div align="center">
 15         <table >
 16             <tr>
 17                 <?php
 18                     for ($i = 0; $i < 3; $i++) {
 19                         echo "<td style=\"width: 33%\"><img src=\"";
 20                         echo $pictures[$i];
 21                         echo "\" style=\"width: 100%\"/></td>";
 22                    }
 23                 ?>
 24             </tr>
 25 
 26         </table>
 27 
 28     </div>
 29 
 30 </body>
 31 </html>

如何使用数组

<?php
    // create short variable name
    $document_root = $_SERVER['DOCUMENT_ROOT'];
?>

<!DOCTYPE html>

<html>
<head>
    <title>Bob's Auto Parts - Customer Orders</title>
    <style type="text/css">
        table, th, td {
            border-collapse: collapse;
            border: 1px solid black;
            padding: 6px;
        }

        th {
            background: #ccccff;
        }

    </style>
</head>
<body>
    <h1>Bob's Auto Parts</h1>
    <h2>Customer Orders</h2>
    <?php
        $orders = file("$document_root/orders/orders.txt");
        $number_of_orders = count($orders);

        if ($number_of_orders == 0) {
            echo "<p><strong>No orders pending.<br/>Please try again later.</strong></p>";
        }
        echo "<table>\n";
        echo "<tr>
            <th>Order Date</th>
            <th>Tires</th>
            <th>Oil</th>
            <th>Spark</th>
            <th>Total</th>
            <th>Address</th>
            </tr>";
        for ($i = 0; $i < $number_of_orders; $i++) {
            $line = explode("\t", $orders[$i]);
            // keep only the number of items ordered
            $line[1] = intval($line[1]);
            $line[2] = intval($line[2]);
            $line[3] = intval($line[3]);
            echo "<tr>
                   <td>$line[0]</td>
                   <td style='text-align: right'>$line[1]</td>
                   <td style='text-align: right'>$line[2]</td>
                   <td style='text-align: right'>$line[3]</td>
                   <td style='text-align: right'>$line[4]</td>
                    <td>$line[5]</td>
                    </tr>";
        }
        echo "</table>";
    ?>
</body>
</html>
结果如下图所示

The explode function has the follwing prototype

array explode(string separator, string string [, int limit])

还有很多其它的处理函数


第四章 字符串处理函数以及常规表达式

The nl2br() function takes a string as a parameter and replaces all the new lines in it with the HTML.

<p><?php echo nl2br(htmlspecialchars($feedback)); ?></p>
<?php
    // create short variable names
    $name=$_POST['name'];
    $email=$_POST['email'];
    $feedback=$_POST['feedback'];

    // set up some static information
    $toaddress = "client@example.com";
    $subject = "Feedback from web site";
    $mailcontent = "Customer name: ".filter_var($name)."\n".
        "Customer email: ".$email. "\n".
        "Customer comments:\n".$feedback."\n";
    $fromaddress = "From: wangrl2016@gmail.com";

    // invoke mail() function to send mail
    mail($toaddress, $subject, $mailcontent, $fromaddress);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Bob's Auto Parts - Feedback Submitted</title>
</head>
<body>
    <h1>Feedback submitted</h1>
    <p>Your feedback has been sent.</p>

</body>

</html>
<html>
<head>
    <title>Bob's Auto Parts - Customer Feedback</title>
</head>
<h1>Customer Feedback</h1>
<p>Please tell us what you think.</p>
<form action="processfeedback.php" method="post">
    <p>Your name:<br/><input type="text" name="name" size="40"/></p>
    <p>Your email address:<br/><input type="text" name="email" size="40"/></p>
    <p>Your feedback:<br/>
    <textarea name="feedback" row="8" cols="40" wrap="virtual"></textarea></p>
    <p><input type="submit" value="Send feedback" /></p>

</form>
</html>
邮件无法发送,可能是协议的原因。

有很多的字符串操作函数

<?php
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $feedback = trim($_POST['feedback']);
?>

<html>
<head>

</head>
<body>
    <h1>Feedback submitted</h1>
    <p>Your feedback (shown below) has been sent.</p>
    <p><?php echo nl2br(htmlspecialchars($feedback)); ?></p>

</body>
</html>

strstr() strchr() strrchr()

strpos()

正则表达式

字符匹配

match literal

/http:\/\//

/.at/ matches the string "cat", "sat"

/[a-z]at/

/[^a-z] not between a -z


第五章 重用代码和写功能函数

PHP provides two very simple, yet very useful, statements to allow you to reuse code. Using a require() or include() statement, you can load a file into your php script.

The file can contain anything you would normally have in a script including PHP statements, text, HTML, tags, PHP functions , or PHP classes.

require的用法

<?php
    echo "This is the main file.<br/>";
    require ('reuseable.php');
    echo "The script will end now.<br/>"
?>
<?php
    echo "Here is a very simple PHP statement.<br/>";
?>

怎么样连接这些css呢?赶紧加配置文件啊,配置nginx.conf服务器。

配置php.ini文件

auto_prepend_file = "/path/to/header.php"

auto_append_file = "/path/to/footer.php"

把一个网页文件分成三部分

<html>
<head>
    <title>TLA Consulting Pty Ltd</title>
    <link href="styles.css" type="text/css" rel="stylesheet" media="screen" />
</head>
<body>

<!-- page header -->
<div class="header">
    <img class="header-logo" src="logo.gif" alt="TLA logo"/>
    <h1 class="header-text">TLA Consulting</h1>
</div>
<!-- menu -->
<div class="menu">
    <div class="menuitem">
        <a href="home.html">
            <img src="s-logo.gif" alt="" height="20" width="20" />
            <span class="menutext">Home</span></td>
        </a>
    </div>
    <div class="menuitem">
        <a href="contact.html">
            <img src="s-logo.gif" alt="" height="20" width="20" />
            <span class="menutext">Contact</span></td>
        </a>
    </div>
    <div class="menuitem">
        <a href="services.html">
            <img src="s-logo.gif" alt="" height="20" width="20" />
            <span class="menutext">Services</span></td>
        </a>
    </div>
    <div class="menuitem">
        <a href="about.html">
            <img src="s-logo.gif" alt="" height="20" width="20" />
            <span class="menutext">About</span></td>
        </a>
    </div>
</div>

<!-- page content -->
<p>Welcome to the home of TLA Consulting.
    Please take some time to get to know us.</p>
<p>We specialize in serving your business needs
    and hope to hear from you soon.</p>

<!-- page footer -->
<div class="footer">
    <p class="foot">&copy; TLA Consulting Pty Ltd.</p>
    <p class="foot">Please see our
        <a href="legal.php">legal information page</a></p>
</div>
</body>
</html>

使用函数

A function declaration creates or declares a new function.

function my_function() {
    echo "My function was called";
}
函数中可以带参数。

参数作用域

定义在函数以内的,只有局部作用域,

定义在函数以外的全局变量,从定义开始,到文件末尾。

引用

function increment(&$value, $amount = 1) {
 $value = $value + amount;
}
匿名函数也叫作closures.

array_walk($array, function($value){ echo "$value <br/>";});


第六章 php面向对象编程

和c++基本上相同,A constructor have a special type of operation called a constructor.

命名规则 __construct();

class的属性

class classname {
    public $attribute;
   function operation($param) {
        $this->attribute = $param;
        echo $this->attribures;
    }
}
__get()和__set()函数。

function __set($name, $value) {
    if (($name=="attribute") && ($value >= 0) && ($value <= 100)) {
        $this->attribute = $value;
    }
}
继承和c++相似

也有private和protected说法

overloading也有

<?php
    class A {
        public $attribute = "default value";
        function operation() {
            echo "Something <br/>";
            echo $this->attribute;
        }
    }
    class B extends A {
        public $attribute = "different value";
        function operation()
        {
            echo $this->attribute."<br/>";
        }
    }
?>
也有final,不能被重写。

不支持多继承。

支持接口

interface Displayable {
    function display();
}
实现接口

class webPage implements Displayable {
    function display() {
    }
}
The key different between interfaces and traits is that traits include an implementation, as oppose to merely specifying an interface that must be implemented.

<?php
    trait logger {
        public function logmessage($message, $level='DEBUG') {
            // write $message to a log
        }
    }
    class fileStorage {
        use logger;
        function store($data) {
            $this->logmessage($data);
        }
    }
?>
If you implement a function called __toString() in your class, it will be  called when you try to print the class.


第七章 错误和异常处理

和java基本相似

try {

    // code goes here

}

try {
    // do something, maybe throw some exception
} catch (Exception $e) {
    // handle exception
} finally {
    echo "Always runs!";
}
<?php
    try {
        throw new Exception("A terrible error has occurred", 42);
    } catch (Exception $e) {
        echo "Exception ".$e->getCode(). ": ".$e->getMessage()."</br>".
            " in ".$e->getFile()." on line ".$e->getLine(). "<br/>";
    }
?>
Exception 函数

getCode() getMessage() getFile() getLine() getTrace()

自定义异常类

和c++基本上是相同的。

可以继承


第八章 设计自己的网络数据库

tables

The identifying column in a table is called the key or the primary key.

Databases usually consist of multiple tables and use a key as reference from one table to another.

现在有两个数据库, Customer 和Order,两个数据库relational database,通过一个数据库的keyID定位另外一个数据库。

Schemas

A schema should show the tables along with their columns, the primary key of each table and any foreign keys.

Customers(CustomerID, Name, Address, City);
Orders(OrderID, CustomerID, Amount, Date);
设计自己的网络数据库

Brower -> WebServer -> PHP Engine -> MySQL Server


第九章 创建网络数据库

mysql -u username -p

mysql> create database books
    -> ;
CREATE user_info

GRANT privileges ON item TO user_info

The privileges clause should be a comma-separated list of privileges.

You can grant privileges on all the databases by specifying *.* as the item.

SELECT INSERT UPDATE DELETE INDEX ALTER

mysql> grant all
    -> on *.*
    -> to 'username' identified by 'password'
    -> with grant option;
Query OK, 0 rows affected (0.00 sec)

mysql> revoke all privileges, grant option
    -> from 'username'
    -> ;
Query OK, 0 rows affected (0.00 sec)
mysql> grant usage
    -> on books.*
    -> to 'username'@'localhost' identified by 'password'
    -> ;
Query OK, 0 rows affected (0.00 sec)

mysql> grant select, insert, update, delete, index, alter, create, drop
    -> on books.*
    -> to 'username'@'localhost';
Query OK, 0 rows affected (0.00 sec)
The general form of a CREATE TABLE statement is

CREATE TABLE tablename(columns)

Customers(CustomerID, name, Address, City)

Orders(OrderID, CustomerID, Amount, Date)

删除数据库显示数据库

mysql> DROP DATABASE books
    -> ;
Query OK, 0 rows affected (0.00 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)

使用sql文件创建数据库

root@wangrl:~# mysql -h localhost  -u root -p  < /data/sql/wangrl.sql

create database books;

use books;

create table customers
( customerid int unsigned not null auto_increment primary key,
  name char(50) not null,
  address char(100) not null,
  city char(30) not null
);

create table orders
( orderid int unsigned not null auto_increment primary key,
  customerid int unsigned not null,
  amount float(6,2),
  date date not null,

  foreign key (customerid) references customers(customerid)
);

create table books
(  isbn char(13) not null primary key,
   author char(50),
   title char(100),
   price float(4,2)
);

create table order_items
( orderid int unsigned not null,
  isbn char(13) not null,
  quantity tinyint unsigned,

  primary key (orderid, isbn),
  foreign key (orderid) references orders(orderid),
  foreign key (isbn) references books(isbn)
);

create table book_reviews
(
  isbn char(13) not null primary key,
  review text,
 
  foreign key(isbn) references books(isbn)
);
创建的结果

mysql> use books;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-----------------+
| Tables_in_books |
+-----------------+
| book_reviews    |
| books           |
| customers       |
| order_items     |
| orders          |
+-----------------+
5 rows in set (0.00 sec)

显示具体的内容

mysql> describe books
    -> ;
+--------+------------+------+-----+---------+-------+
| Field  | Type       | Null | Key | Default | Extra |
+--------+------------+------+-----+---------+-------+
| isbn   | char(13)   | NO   | PRI | NULL    |       |
| author | char(50)   | YES  |     | NULL    |       |
| title  | char(100)  | YES  |     | NULL    |       |
| price  | float(4,2) | YES  |     | NULL    |       |
+--------+------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

Now that you know how to create users, databases, and tables, you can concentrate on interacting with the database.


第十章 数据库的增删查改操作

数据库查询操作

mysql> select name, city
    -> from customers;
+-----------------+--------------+
| name            | city         |
+-----------------+--------------+
| Julie Smith     | Airport West |
| Alan Wong       | Box Hill     |
| Michelle Arthur | Yarraville   |
+-----------------+--------------+
3 rows in set (0.00 sec)

mysql> select *
    -> from orders
    -> where customerid = 3;
+---------+------------+--------+------------+
| orderid | customerid | amount | date       |
+---------+------------+--------+------------+
|       1 |          3 |  69.98 | 2007-04-02 |
|       4 |          3 |  24.99 | 2007-05-01 |
+---------+------------+--------+------------+
2 rows in set (0.00 sec)
综合查找

mysql> select orders.orderid, orders.amount, orders.date
    -> from customers, orders
    -> where customers.name = 'julie smith' and customers.customerid = orders.customerid;+---------+--------+------------+
| orderid | amount | date       |
+---------+--------+------------+
|       2 |  49.99 | 2007-04-15 |
+---------+--------+------------+
1 row in set (0.00 sec)
数据库增加操作

mysql> describe books;
+--------+------------+------+-----+---------+-------+
| Field  | Type       | Null | Key | Default | Extra |
+--------+------------+------+-----+---------+-------+
| isbn   | char(13)   | NO   | PRI | NULL    |       |
| author | char(50)   | YES  |     | NULL    |       |
| title  | char(100)  | YES  |     | NULL    |       |
| price  | float(4,2) | YES  |     | NULL    |       |
+--------+------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

mysql> select name, address
    -> from customers
    -> order by name;
+--------------------+--------------------+
| name               | address            |
+--------------------+--------------------+
| Alan Wong          | 1/47 Haines Avenue |
| Georage Napolitano | 177 Melbourne Road |
| Julie Smith        | 25 Oak Street      |
| Michelle Arthur    | 357 North Road     |
+--------------------+--------------------+
4 rows in set (0.00 sec)
mysql> select avg(amount)
    -> from orders;
+-------------+
| avg(amount) |
+-------------+
|   54.985002 |
+-------------+
1 row in set (0.00 sec)
mysql> select name
    -> from customers
    -> limit 2;
+-------------+
| name        |
+-------------+
| Julie Smith |
| Alan Wong   |
+-------------+
2 rows in set (0.00 sec)
mysql> select customerid, amount
    -> from orders
    -> where amount = (select max(amount) from orders);
+------------+--------+
| customerid | amount |
+------------+--------+
|          2 |  74.98 |
+------------+--------+
1 row in set (0.00 sec)
更改和删除操作

mysql> update books
    -> set price = price * 1.1;
Query OK, 4 rows affected (0.00 sec)
Rows matched: 4  Changed: 4  Warnings: 0

mysql> delete from customers
    -> where customerid = 5;
Query OK, 0 rows affected (0.01 sec)
DROP TABLE table;

删除表格.


第十一章 通过php访问数据库

写好两个一个网页.search.php

<!DOCTYPE html>
<html>
    <head>
        <title>Book-O-Rama Catalog Search</title>
    </head>

    <body>
        <h1>Book-O-Rama Catalog Search</h1>
        <form action="results.php" method="post">
            <p><strong>Choose Search Type:</strong><br/>
            <select name="searchtype">
                <option value="Author">Author</option>
                <option value="Title">Title</option>
                <option value="ISBN">ISBN</option>
            </select>
            </p>
            <p><strong>Enter Search Term:</strong><br/>
                <input name="searchterm" type="text" size="40">
            </p>
            <p><input type="submit" name="submit" value="Search"> </p>
        </form>
    </body>

</html>

通过这个网页进行查找.

然后在server端由这个网页开始执行

<html>
<head>
    <title>Book-O-Rama Search Results</title>
</head>
<body>
<h1>Book-O-Rama Search Results</h1>
<?php
// create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);

if (!$searchtype || !$searchterm) {
    echo 'You have not entered search details.  Please go back and try again.';
    exit;
}

// whitelist the searchtype
switch ($searchtype) {
    case 'Title':
    case 'Author':
    case 'ISBN':
        break;
    default:
        echo 'That is not a valid search type. Go back and try again.';
        exit;
}
$db = new mysqli('localhost', 'username', 'password', 'books', 3306);
if (mysqli_connect_errno()) {
    echo "<p>Error: Could not connect to database.  Please try again later.</p>";
    exit;
}

$query = "select * from books where $searchtype = ?";
$stmt = $db->prepare($query);
$stmt->bind_param('s', $searchterm);
$stmt->execute();
$stmt->store_result();

$stmt->bind_result($title, $author, $isbn, $price);

echo "<p>Number of books found: ".$stmt->num_rows."</p>";

while($stmt->fetch()) {
    echo "<p><strong>Title: ".$title."</strong>";
    echo "<br />Author: ".$author;
    echo "<br />ISBN: ".$isbn;
    echo "<br />Price: ".$price."</p>";
}

$stmt->free_result();
$db->close();

?>
</body>
</html>
在这个执行的过程中碰到了new mysqli没有返回的问题,卡了一段时间.

实际的解决办法是修改php.ini配置文件

1128 ; Allow accessing, from PHP's perspective, local files with LOAD DATA statements
1129 ; http://php.net/mysqli.allow_local_infile
1130 mysqli.allow_local_infile = On
这个前面的分好去掉,表示允许访问本地文件后成功.

输出如下的结果.

表明访问数据库成功

Book-O-Rama Search Results

Number of books found: 1

Title: 0-672-31697-8
Author: Michael Morgan
ISBN: Java 2 for Professional Developers
Price: 38.490001678467

伟大的胜利,至此,nginx, mysql, php,三者已经完美结合,剩下的都是开始编程,编程,编程.

后续将加上javascript库,加上一些第三方库,不要随便下载,或者更改配置文件,要在确认再确认的情况下进行修改,这个服务器要一直用下去.

数据库的插入操作和数据库的查询操作基本一样,就可能query相关的内容不同,流程都是一样的.

贴上两段代码

<html>
    <head>
        <title>Book-O-Rama - New Book Entry</title>
        <style type="text/css">
            fieldset {
                width: 75%;
                border: 2px solid #cccccc;
            }
            label {
                width: 75px;
                float: left;
                text-align: left;
                font-weight: bold;
            }
            input {
                border: 1px solid #000;
                padding: 3px;
            }
        </style>
    </head>
    <body>
        <h1>Book-O-Rama - New Book Entry</h1>
        <form action="insert_book.php" method="post">
            <fieldset>
                <p><label for="ISBN">ISBN</label>
                    <input type="text" id="ISBN" name="ISBN" maxlength="13" size="13" /></p>
                <p><label for="Author">Author</label>
                    <input type="text" id="Author" name="Author" maxlength="30" size="30" /></p>
                <p><label for="Title">Title</label>
                    <input type="text" id="Title" name="Title" maxlength="60" size="30" /></p>
                <p><label for="Price">Price</label>
                    <input type="text" id="Price" name="Price" maxlength="7" size="7" /></p>
            </fieldset>
            <p><input type="submit" value="Add New Book" /></p>

        </form>
    </body>
</html>
insert_book.php注意这是的用户名和密码填上自己的用户名和密码

<!DOCTYPE html>
<html>
<head>
    <title>Book-O-Rama Book Entry Results</title>
</head>
<body>
<h1>Book-O-Rama Book Entry Results</h1>
<?php
    // create short variable names
    $isbn=$_POST['ISBN'];
    $author=$_POST['Author'];
    $title=$_POST['Title'];
    $price=$_POST['Price'];
    $price=doubleval($price);
    @$db = new mysqli('localhost', 'username', 'password', 'books', 3306);

    if (mysqli_connect_errno()) {
        echo "<p>Error: Could not connect to database.<br/></p>";
        exit;
    }
    $query = "INSERT INTO books VALUES (?, ?, ?, ?)";
    $stmt = $db->prepare($query);
    $stmt->bind_param('sssd', $isbn, $author, $title, $price);
    $stmt->execute();
    if ($stmt->affected_rows > 0) {
        echo "<p>Book inserted into the database.</p>";
    } else {
        echo "<p>A error has occurred.</p>";
    }
    $db->close();
?>
</body>
</html>

第十二章 更多的MySQL使用和管理员权限

show语句的使用.

show tables from db;

最大化数据库

设计的最大化

权限

表格的最大化

使用下标

备份


第十三章 先进MySQL编程理念

支持不同的存储引擎

InnoDB

MyISAM

交易

查找操作

mysql> select * from orders where orderid=3;
+---------+------------+--------+------------+
| orderid | customerid | amount | date       |
+---------+------------+--------+------------+
|       3 |          2 |  74.98 | 2007-04-19 |
+---------+------------+--------+------------+
1 row in set (0.00 sec)
外围关键字

Php和数据库的基础知识已经学完,剩下的几张再巩固,已经看完超过1/2,0-331是基础部分,

331-600是提升部分,600-615的附件部分已经配置完成.

还有很多的任务要完成,比如用户的登录,用户上传文件,小型的文件系统,和android部分的知识怎么处理.

还要很多的努力,加油.


后面新开一部分再进行学习






















www.phpzy.comtrue/php/20784.htmlTechArticlePHP and MySQL Web Development习题作业集,mysqldevelopment php和数据库的学习,来自于书本PHP and MySQL web Development.每章都是重点介绍还有些代码。 ubuntu安转mysql Ubuntu上安装MySQL非常简单只需要几条...

相关文章

    暂无相关文章

PHP之友评论

今天推荐