在网站后台,经常要与 数据库 打交道。本文 介绍 如何使用XAMPP来管理MySql 数据库 及如何用PHP来 访问 MySql 数据库 。 一.使用XAMPP来管理MySql 数据库 首先使用XAMPP打开MySql的管理页面。步骤如下:启动XAMPP后点击Admin进入XAMPP for Windows的主页面
在网站后台,经常要与数据库打交道。本文介绍如何使用XAMPP来管理MySql数据库及如何用PHP来访问MySql数据库。
一.使用XAMPP来管理MySql数据库
首先使用XAMPP打开MySql的管理页面。步骤如下:启动XAMPP后点击Admin进入XAMPP for Windows的主页面,在主页面中点击phpMyAdmin。
进入phpMyAdmin页面后,新建数据库test并在此数据库中建立t_student表,表共三个字段,编号id,姓名name,年龄age。
然后就可以开始用PHP来访问MySql数据库了。由于PHP已经对访问MySql数据库作了良好的封装,因此用PHP访问MySql是一件非常容易的事情。
二.PHP访问MySql数据库
下面的PHP程序访问test数据库中t_student表,读取数据并以表格的形式输出数据。全部程序代码如下:
<span> 1</span> <span>//</span><span> by MoreWindows( http://blog.csdn.net/MoreWindows ) </span><span> 2</span> <span>//定义常量</span> <span> 3</span> <span>define</span>(DB_HOST, 'localhost'<span>); </span><span> 4</span> <span>define</span>(DB_USER, 'root'<span>); </span><span> 5</span> <span>define</span>(DB_PASS, '111111'<span>); </span><span> 6</span> <span>define</span>(DB_DATABASENAME, 'test'<span>); </span><span> 7</span> <span>define</span>(DB_TABLENAME, 't_student'<span>); </span><span> 8</span> <span>//</span><span><strong>数据库</strong>表的列名</span> <span> 9</span> <span>$dbcolarray</span> = <span>array</span>('id', 'name', 'age'<span>); </span><span>10</span> <span>11</span> <span>//</span><span>mysql_connect</span> <span>12</span> <span>$conn</span> = <span>mysql_connect</span>(DB_HOST, DB_USER, DB_PASS) or <span>die</span>("connect failed" . <span>mysql_error</span><span>()); </span><span>13</span> <span>mysql_select_db</span>(DB_DATABASENAME, <span>$conn</span><span>); </span><span>14</span> <span>15</span> <span>//</span><span>读取表中纪录条数</span> <span>16</span> <span>$sql</span> = <span>sprintf</span>("select count(*) from %s",<span> DB_TABLENAME); </span><span>17</span> <span>$result</span> = <span>mysql_query</span>(<span>$sql</span>, <span>$conn</span><span>); </span><span>18</span> <span>if</span> (<span>$result</span><span>) </span><span>19</span> <span>{ </span><span>20</span> <span>$count</span> = <span>mysql_fetch_row</span>(<span>$result</span><span>); </span><span>21</span> <span>} </span><span>22</span> <span>else</span> <span>23</span> <span>{ </span><span>24</span> <span>die</span>("query failed"<span>); </span><span>25</span> <span>} </span><span>26</span> <span>echo</span> "表中有<span>$count</span>[0] 条记录<br>"<span>; </span><span>27</span> <span>28</span> <span>29</span> <span>$sql</span> = <span>sprintf</span>("select %s from %s", <span>implode</span>(",",<span>$dbcolarray</span>),<span> DB_TABLENAME); </span><span>30</span> <span>$result</span> = <span>mysql_query</span>(<span>$sql</span>, <span>$conn</span><span>); </span><span>31</span> <span>//</span><span>表格</span> <span>32</span> <span>echo</span> '
" . implode(" | ", $dbcolarray) . " | "; 35 echo $thstr; 36 //表中的内容 37 while ($row=mysql_fetch_array($result, MYSQL_ASSOC))//与$row=mysql_fetch_assoc($result)等价 38 { 39 echo "
---|
$row[$td] | "; 43 echo $tdstr; 44 echo "
运行结果如下:
这种HTML元素全由PHP输出的方式比较原始,可以进行优化。