首页 > 代码库 > 基于docker的php调用基于docker的mysql数据库的方法

基于docker的php调用基于docker的mysql数据库的方法

1:建立基于docker的mysql,参考

Mac上将brew安装的MySql改用Docker执行

2:建立基于docker?php image

在当前目录,建立Dockerfile,内容如下

FROM php:7.0-cli MAINTAINER Terry Zhang <zterry@qq.com> RUN docker-php-ext-install pdo_mysql mysqli

3.建立php镜像

docker build -t php-mysql .

4. 编写php脚本,可以从mysql数据库读取数据:

<?php $host = ‘mysql‘; $user = ‘root‘; $pwd = ‘password‘; $db = ‘test‘; $mysqli = new mysqli($host, $user, $pwd, $db); if ($mysqli->connect_errno) { echo "Errno: " . $mysqli->connect_errno . "\n"; } $sql = ‘SELECT * FROM users‘; if ($res = $mysqli->query($sql)) { while ($row = $res->fetch_assoc()) { print_r($row); } } ?>

5. 执行php的容器,参数如下: bash docker run -it --rm -v (pwd):/var --link my-mysql-server1:mysql php-mysql:latest php /var/mysql.php

需要注意的地方是--link参数,这里调用的是名为my-mysql-server1的容器,其在php容器中的host为mysql。可以通过如下命令进行验证:

docker run -it --rm php-mysql ping mysql

如果一切顺利,则会看到输出结果;如果有问题,自行调试。

Then it‘s just a case of writing the PHP switch statement:

switch ($getDay) { case ‘Monday‘: $comment = "Worst Day of the Week!"; break; case ‘Tuesday‘: $comment = "1 Day Better Than Monday!"; break; case ‘Wednesday‘: $comment = "Half Way There!"; break; case ‘Thursday‘: $comment = "Getting There!"; break; case ‘Friday‘: $comment = "Weekend At 5pm!"; break; case ‘Saturday‘: $comment = "Relaxing Saturday!"; break; case ‘Sunday‘: $comment = "Work Tomorrow!"; break; }

The $getDay is the that each case is checked against, and each case is one of the potential values of $getDay . So if it‘s ‘Monday‘, then the variable will be ‘Monday‘ and that‘ll match the first case value, so it‘ll set the variable to the string "Worst Day of the Week!".

Finally this can be output on the page using:

echo "Today is " . $getDay . " - " . $comment;

So this would echo out - Today is Monday - Worst Day of the Week! .

基于docker的php调用基于docker的mysql数据库的方法