PHP基本连接数据库

由于要调试JS的AJAX,Java写感觉不够轻便,所以直接捡起了原来的PHP,来做测试用。

最简单的代码

connect.php

  1. <?php  
  2. $host="localhost";  
  3. $db_user="root";  
  4. $db_pass="";  
  5. $db_name="demo";  
  6. $timezone="Asia/Shanghai";  
  7.   
  8. $link=mysql_connect($host,$db_user,$db_pass);  
  9. mysql_select_db($db_name,$link);  
  10. mysql_query("SET names UTF8");  
  11.   
  12. header("Content-Type: text/html; charset=utf-8");  
  13. ?>  

search.php

  1. <?php  
  2. include_once("connect.php");  
  3.   
  4. $q = strtolower($_GET["term"]);  
  5. $query=mysql_query("select * from test where title like '$q%' limit 0,10");  
  6.   
  7. while ($row=mysql_fetch_array($query)) {  
  8.     $result[] = array(  
  9.             'id' => $row['id'],  
  10.             'label' => $row['title']  
  11.     );  
  12. }  
  13. echo json_encode($result);  
  14. ?>  

sql
  1. CREATE TABLE `art` (  
  2.   `id` int(11) NOT NULL auto_increment,  
  3.   `title` varchar(100) NOT NULL,  
  4.   PRIMARY KEY  (`id`)  
  5. ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=15 ;  
  6.   
  7.   
  8. INSERT INTO `art` (`id`, `title`) VALUES  
  9. (1, 'jstest1'),  
  10. (2, 'jstest2'),  
  11. (3, 'jstest3'),  
  12. (4, 'jstest4'),  
  13. (5, 'jstest5'),  
  14. (6, 'jstest6');  

分开写的连接数据库

common.ini

  1. <?php  
  2.   
  3. //非法调用判断  
  4. if(!defined('Inc_Tag')){  
  5.     exit("非法调用");  
  6. }  
  7. //硬路径转换  
  8. define('ROOT_PATH', substr(dirname(__FILE__), 0,-8));  
  9.   
  10. //版本判断  
  11. if (PHP_VERSION<4.0){  
  12.     exit("版本太低");  
  13. }  
  14. require ROOT_PATH.'\includes\global.func.php';  
  15. require ROOT_PATH.'\includes\mysql.func.php';  
  16. define('start_time', _runtime());  
  17.   
  18. //数据库连接  
  19. define('DB_HOST','Localhost');  
  20. define('DB_NAME','test');  
  21. define('DB_USER','root');  
  22. define('DB_PASSWORD','123456');  
  23. //初始化数据库  
  24. _connect();   //连接MYSQL数据库  
  25. _select_db();   //选择指定的数据库  
  26. _set_names();   //设置字符集  
  27.   
  28. ?>  

mysql.php
  1. <?php  
  2. //防止恶意调用  
  3. if(!defined('Inc_Tag')){  
  4.     exit();  
  5. }  
  6. /**  
  7.    _connect()数据库连接函数  
  8.  */  
  9. function _connect() {  
  10.     //global表示全局变量的意思,意思是此变量在函数外部也可使用  
  11.     global $_conn;  
  12.     if(!$conn=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD)){  
  13.         exit("数据库连接失败".mysql_error());  
  14.     }  
  15. }  
  16.   
  17. /**  
  18.  *   
  19.  * _select_db()选择数据库  
  20.  */  
  21. function _select_db(){  
  22.     if(!mysql_select_db(DB_NAME)){  
  23.         exit("ERROR".mysql_error());  
  24.     }  
  25. }  
  26.   
  27. /**  
  28.  *   
  29.  * _set_names()设置字符集  
  30.  */  
  31. function _set_names(){  
  32.     if(!mysql_query('SET NAMES UTF8')){  
  33.         exit('ERROR'.mysql_error());  
  34.     }  
  35. }  
  36. /**  
  37.  *   
  38.  * _query()查询语句  
  39.  * @param unknown_type $sql  
  40.  */  
  41. function _query($_sql){  
  42.     if (!$_result=mysql_query($_sql)){  
  43.         exit('SQL FAILED'.mysql_error());  
  44.     }  
  45.     return $_result;  
  46. }  
  47.   
  48. /**  
  49.  *   
  50.  * Enter description here ...  
  51.  * @param unknown_type $_sql  
  52.  */  
  53. function _fetch_array($_sql){  
  54.     return mysql_fetch_array(_query($_sql),MYSQL_ASSOC);  
  55. }  
  56.   
  57. /**  
  58.  *   
  59.  * fetch_array_list($_result)在结果中读取关联数组  
  60.  * @param unknown_type $_result  
  61.  */  
  62. function _fetch_array_list($_result){  
  63.    return mysql_fetch_array($_result,MYSQL_ASSOC);    
  64. }  
  65.   
  66. /**  
  67.  *   
  68.  * Enter description here ...  
  69.  * @param unknown_type $_sql  
  70.  * @param unknown_type $_info  
  71.  */  
  72. function _is_repeat($_sql,$_info){  
  73.     if(_fetch_array($_sql)){  
  74.         _alert_back($_info);  
  75.     }  
  76. }  
  77.   
  78. /**  
  79.  *   
  80.  * Enter description here ...  
  81.  */  
  82. function _affected_rows() {  
  83.     return mysql_affected_rows();  
  84. }  
  85.   
  86.   
  87.   
  88.   
  89.   
  90. /**  
  91.  *   
  92.  * _close关闭数据库连接  
  93.  */  
  94. function _close(){  
  95.     if (!mysql_close()){  
  96.         exit("关闭异常".mysql_error());  
  97.     }  
  98. }  
  99.   
  100.   
  101. ?>  

global.fun

  1. <?php  
  2. function _runtime(){  
  3.     $_mtime=explode(' ', microtime());  
  4. $_temp_time=$_mtime[1]+$_mtime[0];  
  5. return $_temp_time;  
  6. }  
  7. /**  
  8.  *   
  9.  * _alert_back()对话框弹出函数,然后返回一步  
  10.  * @param  $msg //弹出对话框消息  
  11.  * @return void  
  12.  */  
  13. function _alert_back($msg){  
  14.     echo "<script type='text/javascript'>alert('".$msg."');history.back();</script>";  
  15.     exit();  
  16. }  
  17.   
  18.   
  19. /**  
  20.  *   
  21.  * _alert_close()弹出消息,关闭  
  22.  * @param unknown_type $msg  
  23.  */  
  24.   
  25. function _alert_close($msg){  
  26.     echo "<script type='text/javascript'>alert('".$msg."');window.close();</script>";  
  27.     exit();  
  28. }  
  29.   
  30.   
  31. function _get_xml($_xml_file){  
  32.     if (file_exists($_xml_file)){  
  33.         $_xml=file_get_contents($_xml_file);  
  34.         preg_match_all('/<vip>(.*)<\/vip>/s',$_xml,$_dom);  
  35.         echo $_dom[1];  
  36.     foreach ($_dom[1] as $_value) {  
  37.             preg_match_all('/<id>(.*)<\/id>/s',$_value,$_id);  
  38.             print_r($_id);  
  39.             preg_match_all('/<username>(.*)<\/username>/s',$_value,$_username);  
  40.             preg_match_all( '/<sex>(.*)<\/sex>/s', $_value, $_sex);  
  41.             preg_match_all( '/<face>(.*)<\/face>/s', $_value, $_face);  
  42.             preg_match_all( '/<email>(.*)<\/email>/s', $_value, $_email);  
  43.             preg_match_all( '/<url>(.*)<\/url>/s', $_value, $_url);  
  44.             $_html['id'] = $_id[1][0];  
  45.             $_html['username'] = $_username[1][0];  
  46.             $_html['sex'] = $_sex[1][0];  
  47.             $_html['face'] = $_face[1][0];  
  48.             $_html['email'] = $_email[1][0];  
  49.             $_html['url'] = $_url[1][0];  
  50.         }  
  51.     } else {  
  52.         echo '文件不存在';  
  53.     }  
  54.     return $_html;  
  55. }  
  56. /**  
  57.  *   
  58.  * Enter description here ...  
  59.  * @param unknown_type $_xmlfile  
  60.  * @param unknown_type $_clean  
  61.  */  
  62. function _set_xml($_xmlfile,$_clean) {  
  63.     $_fp = @fopen('new.xml','w');  
  64.     if (!$_fp) {  
  65.         exit('系统错误,文件不存在!');  
  66.     }  
  67.     flock($_fp,LOCK_EX);  
  68.       
  69.     $_string = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";  
  70.     fwrite($_fp,$_string,strlen($_string));  
  71.     $_string = "<vip>\r\n";  
  72.     fwrite($_fp,$_string,strlen($_string));  
  73.     $_string = "\t<id>{$_clean['id']}</id>\r\n";  
  74.     fwrite($_fp,$_string,strlen($_string));  
  75.     $_string = "\t<username>{$_clean['username']}</username>\r\n";  
  76.     fwrite($_fp,$_string,strlen($_string));  
  77.     $_string = "\t<sex>{$_clean['sex']}</sex>\r\n";  
  78.     fwrite($_fp,$_string,strlen($_string));  
  79.     $_string = "\t<face>{$_clean['face']}</face>\r\n";  
  80.     fwrite($_fp,$_string,strlen($_string));  
  81.     $_string = "\t<email>{$_clean['email']}</email>\r\n";  
  82.     fwrite($_fp,$_string,strlen($_string));  
  83.     $_string = "\t<url>{$_clean['url']}</url>\r\n";  
  84.     fwrite($_fp,$_string,strlen($_string));  
  85.     $_string = "</vip>";  
  86.     fwrite($_fp,$_string,strlen($_string));  
  87.       
  88.     flock($_fp,LOCK_UN);  
  89.     fclose($_fp);  
  90. }  
  91. /**  
  92.  *   
  93.  * _location()跳转函数  
  94.  * @param unknown_type $_msg  
  95.  * @param unknown_type $_url  
  96.  */  
  97.   
  98. function _location($_msg,$_url){  
  99.     if (!empty($_msg)){  
  100.     echo "<script type='text/javascript'>alert('$_msg');location.href='$_url';</script>";  
  101.     exit();  
  102.     }else {  
  103.         header('location:'.$_url);  
  104.     }  
  105.       
  106. }  
  107.   
  108. function _title($_string){  
  109.     if(mb_strlen($_string,'utf-8')>14){  
  110.         return mb_substr($_string, 1,6,'utf-8').'...';  
  111.     }  
  112.     return $_string;  
  113. }  
  114.   
  115. /**  
  116.  *   
  117.  * _html()对数组或者字符串进行html过滤  
  118.  * @param array or string $_string  
  119.  * @return string or array  
  120.  */  
  121. function _html($_string){  
  122.     if (is_array($_string)){  
  123.         foreach ($_string as $_key=>$_value){  
  124.             $_string[$_key]=_html($_value);//采用递归对其进行html过滤  
  125.         }  
  126.     }else {  
  127.         $_string=htmlspecialchars($_string);  
  128.     }  
  129.     return $_string;  
  130. }  
  131.   
  132. /**  
  133.  *   
  134.  * _page()对查询的进行分页处理,  
  135.  * @param unknown_type $_sql  
  136.  * @param unknown_type $_size  
  137.  */  
  138. function _page($_sql,$_size) {  
  139.     //将里面的所有变量取出来,外部可以访问  
  140.     global $_page,$_pagesize,$_pagenum,$_pageabsolute,$_num;  
  141.     if (isset($_GET['page'])) {  
  142.         $_page=$_GET['page'];  
  143.         if (empty($_page) || $_page < 0 || !is_numeric($_page)) {  
  144.             $_page=1;  
  145.         } else {  
  146.             $_page=intval($_page);  
  147.         }  
  148.     } else {  
  149.         $_page=1;  
  150.     }  
  151.     $_pagesize=$_size;  
  152.     $_num=mysql_num_rows(_query($_sql));  
  153.     if ($_num==0) {  
  154.         $_pageabsolute=1;  
  155.     } else {  
  156.         $_pageabsolute=ceil($_num/$_pagesize);  
  157.     }  
  158.     if ($_page>$_pageabsolute) {  
  159.         $_page=$_pageabsolute;  
  160.     }  
  161.     $_pagenum=($_page - 1) * $_pagesize;  
  162. }  
  163.   
  164. /**  
  165.  *   
  166.  */  
  167. function _paging($_type) {  
  168.     global $_page,$_pageabsolute,$_num;  
  169.     if ($_type==1) {  
  170.         echo '<div id="page_num">';  
  171.         echo '<ul>';  
  172.                 for ($i=0;$i<$_pageabsolute;$i++) {  
  173.                         if ($_page==($i+1)) {  
  174.                             echo '<li><a href="'.Script.'.php?page='.($i+1).'" class="selected">'.($i+1).'</a></li>';  
  175.                         } else {  
  176.                             echo '<li><a href="'.Script.'.php?page='.($i+1).'">'.($i+1).'</a></li>';  
  177.                         }  
  178.                 }  
  179.         echo '</ul>';  
  180.         echo '</div>';  
  181.     } elseif ($_type==2) {  
  182.         echo '<div id="page_text">';  
  183.         echo '<ul>';  
  184.         echo '<li>'.$_page.'/'.$_pageabsolute.'页 | </li>';  
  185.         echo '<li>共有<strong>'.$_num.'</strong>个会员 | </li>';  
  186.                 if ($_page==1) {  
  187.                     echo '<li>首页 | </li>';  
  188.                     echo '<li>上一页 | </li>';  
  189.                 } else {  
  190.                     echo '<li><a href="'.SCRIPT.'.php">首页</a> | </li>';  
  191.                     echo '<li><a href="'.SCRIPT.'.php?page='.($_page-1).'">上一页</a> | </li>';  
  192.                 }  
  193.                 if ($_page==$_pageabsolute) {  
  194.                     echo '<li>下一页 | </li>';  
  195.                     echo '<li>尾页</li>';  
  196.                 } else {  
  197.                     echo '<li><a href="'.SCRIPT.'.php?page='.($_page+1).'">下一页</a> | </li>';  
  198.                     echo '<li><a href="'.SCRIPT.'.php?page='.$_pageabsolute.'">尾页</a></li>';  
  199.                 }  
  200.         echo '</ul>';  
  201.         echo '</div>';  
  202.     }  
  203. }  
  204.   
  205.   
  206.   
  207. function _unsetcookies(){  
  208.     setcookie('username','',time()-1);  
  209.     setcookie('uniqid','',time()-1);  
  210.     session_destroy();  
  211.     _location(null,'index.php');  
  212. }  
  213. /**  
  214.  * _code() 注册码函数  
  215.  * @access public  
  216.  * @param $_width 验证码图片宽  
  217.  * @param $_height 验证码图片高  
  218.  * @param $_rnd_code 验证码位数  
  219.  * @param $_flag 是否显示黑色边框  
  220.  * @return void 返回一验证码图片  
  221.  */  
  222.   
  223. function _code($_width=75,$_height=25,$_rnd_code=4,$flag=FALSE){  
  224.   
  225.   
  226. //创建随机码  
  227. for ($i=0;$i<$_rnd_code;$i++) {  
  228.     $_nmsg .dechex(mt_rand(0,15));  
  229. }  
  230.   
  231. //保存在session  
  232. $_SESSION['code'] = $_nmsg;  
  233.   
  234.   
  235.   
  236. //创建一张图像  
  237. $_img = imagecreatetruecolor($_width,$_height);  
  238.   
  239. //白色  
  240. $_white = imagecolorallocate($_img,255,255,255);  
  241.   
  242. //填充  
  243. imagefill($_img,0,0,$_white);  
  244.   
  245. $_flag = false;  
  246.   
  247. if ($_flag) {  
  248.     //黑色,边框  
  249.     $_black = imagecolorallocate($_img,0,0,0);  
  250.     imagerectangle($_img,0,0,$_width-1,$_height-1,$_black);  
  251. }  
  252.   
  253. //随即画出6个线条  
  254. for ($i=0;$i<6;$i++) {  
  255.     $_rnd_color = imagecolorallocate($_img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));  
  256.     imageline($_img,mt_rand(0,$_width),mt_rand(0,$_height),mt_rand(0,$_width),mt_rand(0,$_height),$_rnd_color);  
  257. }  
  258.   
  259. //随即雪花  
  260. for ($i=0;$i<100;$i++) {  
  261.     $_rnd_color = imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));  
  262.     imagestring($_img,1,mt_rand(1,$_width),mt_rand(1,$_height),'*',$_rnd_color);  
  263. }  
  264.   
  265. //输出验证码  
  266. for ($i=0;$i<strlen($_SESSION['code']);$i++) {  
  267.     $_rnd_color = imagecolorallocate($_img,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200));  
  268.     imagestring($_img,5,$i*$_width/$_rnd_code+mt_rand(1,10),mt_rand(1,$_height/2),$_SESSION['code'][$i],$_rnd_color);  
  269. }  
  270.   
  271. //输出图像  
  272. header('Content-Type: image/png');  
  273. imagepng($_img);  
  274.   
  275. //销毁  
  276. imagedestroy($_img);  
  277. }  
  278.   
  279. function _sha1_uniqid(){  
  280.     return sha1(uniqid(rand(),TRUE));  
  281. }  
  282.   
  283. ?>  

查询

  1. <?php  
  2. /**  
  3. * TestGuest Version1.0  
  4. * ================================================  
  5. * Copy 2010-2012 yc60  
  6. * Web: http://www.yc60.com  
  7. * ================================================  
  8. * Author: Lee  
  9. * Date:2011-9-7  
  10. */  
  11. error_reporting(E_ALL^E_NOTICE);  
  12. //定义常量,授权includes的包含文件  
  13. define('Inc_Tag', TRUE);  
  14. //定义常量,包含CSS文件  
  15. define('Script', 'blog');  
  16. //包含公共文件  
  17. require dirname(__FILE__).'/includes/common.inc.php';  
  18. ?>  
  19. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  20. <html xmlns="http://www.w3.org/1999/xhtml">  
  21. <head>  
  22. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  23. <title>hello gull记事本-博友界面</title>  
  24. <?php   
  25. //包含CSS文件  
  26. require ROOT_PATH.'includes/title.inc.php';  
  27. ?>  
  28. </head>  
  29. <body>  
  30. <?php   
  31. //包含头文件  
  32. require ROOT_PATH.'includes/header.inc.php';  
  33. //分页模块  
  34. global $_pagesize,$_pagenum;  
  35. _page("SELECT dg_id FROM tg_user",10);   //第一个参数获取总条数,第二个参数,指定每页多少条  
  36.   
  37.   
  38. //读取数据库信息  
  39. $_result=_query("SELECT t_username,t_sex,t_face FROM tg_user ORDER BY t_reg_time DESC limit $_pagenum,$_pagesize");  
  40. ?>  
  41.   
  42. <div id="blog">  
  43. <div>  
  44. <h2>博友信息</h2>  
  45.   
  46. <?php while (!!$rows=_fetch_array_list($_result)){?>  
  47. <dl>  
  48. <dd class="user"><?php echo $rows['t_username']?>(<?php echo $rows['t_sex']?>)</dd>  
  49. <dt><img src="<?php echo $rows['t_face']?>" /></dt>  
  50. <dd class="message">发消息</dd>  
  51. <dd class="friend">加为好友</dd>  
  52. <dd class="guest">写留言</dd>  
  53. <dd class="flower">给他送花</dd>  
  54. </dl>  
  55.   
  56. <?php }?>  
  57. <?php  
  58. _paging(1);  
  59. ?>  
  60. </div>  
  61. <?php   
  62. //包含尾部文件  
  63. require ROOT_PATH.'includes/footer.inc.php';  
  64. ?>  
  65.   
  66. </body>  
  67. </html> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值