PHP_相关问题(1)

1)Curl发送get请求:

<?php

    //初始化

    $curl = curl_init();

    //设置抓取的url

    curl_setopt($curl, CURLOPT_URL, 'http://www.baidu.com');

    //设置头文件的信息作为数据流输出

    curl_setopt($curl, CURLOPT_HEADER, 1);

    //设置获取的信息以文件流的形式返回,而不是直接输出。

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    //执行命令

    $data = curl_exec($curl);

    //关闭URL请求

    curl_close($curl);

    //显示获得的数据

    var_dump($data);

2)Curl发送post请求:

<?php

$data=array("appType"=>1,"IsJSON"=>1,"phone"=>18300000000);

$url = "http://app.ron20.com:809/smspost.php?";

$res=doCurlPostRequest($url, $data, 10);

var_dump($res);



function doCurlPostRequest($url, $requestString, $timeout = 5)

{

    if ($url == "" || $requestString == "" || $timeout <= 0) {

        return false;

    }

    $con = curl_init((string)$url);

    curl_setopt($con, CURLOPT_HEADER, false);

    curl_setopt($con, CURLOPT_POSTFIELDS, $requestString);

    curl_setopt($con, CURLOPT_POST, true);

    curl_setopt($con, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($con, CURLOPT_TIMEOUT, (int)$timeout);

    curl_exec($con);

}

3)php调用WEBSERVICE服务:

<?php



class webSrvClass

{

    //webservice 地址参数,调用webservice

    function soap($function, $par = array())

    {

        //链接 web service  需要注意下面的url地址是.net提供的,后面加个?wsdl才是描述定义文件哈,请各自取正确的wsdl地址(每种web服务都有的)

        $client = new SoapClient("http://www.sz56it11.net:8088/Transjp.svc?wsdl", array('exceptions' => 0));

        $require = $client->$function($par);

        //调用信息debug

        if (is_soap_fault($require)) {

            echo "远程接口" . $function . "调用失败!";

            exit();

        }

        //获取返回值

        $function_result = $function . "Result";

        $str = $require->$function_result;

        return $str;

    }





     //接口通讯记录

    /*function soap_log($class, $function, $in, $out)

    {

        $log = date("Y-m-d H:i:s");

        $log .= " " . $class . "->" . $function . " input:";

        $input = "";

        if ($in != array()) {

            foreach ($in as $key => $vlaue) {

                $input .= $key . "=" . $vlaue;

            }

            $log .= $input . " output:" . var_export($rows) . "\n";

        }

    }*/

}



//调用方法

$webserv = new webSrvClass;

//这里是调用方法给传递的参数  

$a = array("trackid" => "121211", "username" => "jpwl1", "password" => "jpwl888111");

echo 'server echo:' . ($webserv->soap("querystatus", $a));



?>
View Code

 4)php获取页面完整url:

<?php

    function get_page_url(){

        $url=(isset($_SERVER['SERVER_PORT'])&&$_SERVER['SERVER_PORT']=='443')? 'https://':'http://';

        $url.=$_SERVER['HTTP_HOST'];

        $url.=isset($_SERVER['REQUEST_URL'])?$_SERVER['REQUEST_URL']:$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];

        return $url;

    }

?>

 5)php无限极分类:

//无限极函数

private function treelist($data, $cid, $deep = 1) {

        static $tree = array ();

        foreach ( $data as $row ) {

            if ($row ['cid'] == $cid) {

                $row ['lever'] = $deep;

                $tree [] = $row;

                $this->treelist ( $data, $row ['id'], $deep + 1 );

            }

        }

        return $tree;

    }

//取得数据

public function getList() {

        // 获取所有分类数据

        $data = $this->fetchAll ();

        //list就是所有排序之后的数据

        $list = $this->treeList ( $data, 0 );

        return $list;

    }



//在页面中展示

<div class="subnav">

     {foreach from=$cdata item='value'} 

    {if $value['lever']==1}

       <div>

        <span class="left"> {$value['name']} </span>

        <span class="right subnav_right">

        <img src="Public/Home/view/images/line.gif" border="0"

            id="categorie_ico3"></span>

       </div>

    {/if}



    <ul id="m3" style="display: block">

        {if $value['lever']==2}

              <li>&nbsp;<a href="#"> {$value['name']} </a></li>

        {/if}

    </ul>

     {/foreach}

</div>
View Code

 6)php简单的将数据输出到excel表格:

<?php

header("Content-Type:text/html;   charset=utf-8"); 

Header( "Content-type:   application/octet-stream "); 

Header( "Accept-Ranges:   bytes "); 

Header( "Content-type:application/vnd.ms-excel ");   

Header( "Content-Disposition:attachment;filename=test.xls ");

$con = mysql_connect("localhost","root","root");

mysql_select_db("key");

mysql_query('set names utf8');

if(isset($_POST['submit'])){

    $pici=$_POST['pici'];

    $sql = "select id,time,pici,skey from security_code where pici=$pici";

    }

    $result = mysql_query($sql,$con);

    echo "id\ttime\tpici\tskey";

    while ($rs=mysql_fetch_array($result)){

        echo "\n";

        echo $rs['id']."\t".$rs['time']."\t".$rs['pici']."\t".$rs['skey'];

    }
View Code

7)checkbox批量删除:

<?php

    mysql_connect('localhost','root','111111');

    mysql_select_db('project');

    mysql_query('set names gb2312');

    $query="select * from message order by id";

    $result=mysql_query($query);

?>

<script>

    function display(flag){

        var id=document.getElementsByName('id[]');

        for(var i=0;i<id.length;i++){

            if(flag==1){

                id[i].checked=true;

            }

            else if(flag==2){

                id[i].checked=false;

            }

            else{

                id[i].checked=id[i].checked?false:true;

            }

        }

    }

</script>

<form method="POST" action="demo11_delete.php">

<table border="1" width="100%">

    <tr>

        <td>序号</td>

        <td>标题</td>

        <td>内容</td>

        <td>时间</td>

        <td>

            <input type="button" value="全选" onclick="display(1)" />

            <input type="button" value="取消" onclick="display(2)" />

            <input type="button" value="反选" onclick="display(3)" />

        </td>

    </tr>

    <?php

        $i=1;

        while($row=mysql_fetch_array($result)):

    ?>

    <tr>

        <td><?php echo $i++;?></td>

        <td><?php echo $row['title']?></td>

        <td><?php echo $row['content']?></td>

        <td><?php echo $row['ctime']?></td>

        <td><input type="checkbox" value="<?php echo $row['id']?>" name="id[]"></td>

    </tr>

    <?php

        endwhile;

    ?>

    <tr>

        <td colspan="4"></td>

        <td><input type="submit" name="submit" value="批量删除" onclick="return confirm('?')" /></td>

    </tr>

</table>

</form>

*********************************************************

delete.php

<?php

    //判断点击

    if(isset($_POST['submit'])){

        //获取所有被选中的复选框的值

        $id=$_POST['id'];    //id是一个数组

        //拼接sql语句

        $query='delete from message where id in (';

        $where=implode(',',$id);    //   101,200,208,10

        $query=$query.$where.')';

        mysql_connect('localhost','root','111111');

        mysql_select_db('project');

        mysql_query('set names gb2312');    

        mysql_query($query);

        mysql_close();

        header('location:demo11.php');

    }



?>
View Code

8)php_ajax无刷新分页:

 a)前台展示页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script type="text/javascript" src="js/jquery.js"></script> <!-- 载jquery -->

<title>Ajax 实现无刷新页面</title>

<style type="text/css">

    body {

        font-size:12px;    

    }

</style>

</head>

<body>

    <div id="fpage">数据加载中...</div>

</body>

</html>

<script type="text/javascript">

    /**

     * setPage(url) 根据 url 从 __URL__/ajax 中获取数据

     * @param int pageNum 页码

     * @return string

     */

    var cache=new Array(); // 缓存变量,当数据被访问过之后放置在缓存中,加快访问速度

    function setPage(pageNum) {

        var fpage = document.getElementById('fpage'); // 获取 fpage 对象

        // 如果缓存中存在数据,那么直接从缓存中读取;如果不存在数据,那么就从数据库中读取,并把数据存入缓存

        if (typeof(cache[pageNum])=='undefined') {

            $.ajax({

                type:"GET",

                url:"article.php",

                data:"page="+pageNum,

                beforeSend:function(){

                    $('#fpage').html("正在努力加载中...");

                },

                success:function(data){

                    fpage.innerHTML = data; // fpage对象的内容是从article.php 中取来的

                    cache[pageNum] = data;

                }

            });

        } else {

            fpage.innerHTML = cache[pageNum];

        }

    }

    setPage(1); // 默认执行

</script>
index.html

  b)数据库配置文件和后台处理文件:

<?php

/*config.inc.php*/

header('Content-Type:text/html;Charset=utf-8');

define('ROOT_PATH', dirname(__FILE__)); // 网站根目录

define('UPDIR', '/upload/'); // 上传文件路径

define('DB_DSN', 'mysql:host=localhost;dbname=test');

define('DB_USER', 'root');

define('DB_PWD', 'root');

// 自动加载文件类

function __autoload($className) {

    require_once ROOT_PATH . '/includes/'. ucfirst($className) .'.class.php';

}
配置文件 config.inc.php
<?php

/**

* $Id: article.php

* Last modify $Date: 2012-01-21 16:53:05 $

*/

require_once './config.inc.php';

$m = new Model();

$page = new ajaxPage($m->total('article'),10); // $m->total('article') 获取 article 表的记录数;10为每页显示十条

$result = $m->fetchAll('article', '*', '', '', $page->limit); // 取出数据,^_^,很方便吧

echo '<table align="center" border="1" width="1100" style="border-collapse:collapse;font-size:14px;" bordercolor="#666">';

echo '<caption><h1>资讯</h1></caption>';

echo '<tr height="25"><th>ID</th><th>Title</th><th>Author</th><th>Source</th><th>Date</th></tr>';

foreach ($result as $v) {

    echo "<tr height='21'><td align='center'>{$v['id']}</td><td>{$v['title']}</td><td align='center'>{$v['author']}</td><td align='center'>{$v['source']}</td><td align='center'>{$v['date']}</td></tr>";

}

echo '<tr><td align="right" colspan="5">'.$page->fpage().'</td></tr>';

echo '</table>';
处理文件 article.php

  c)用到的类:

<?php

/* indlude/AjaxPage.class.php*/

class ajaxPage {

    private $total;   //数据表中总记录数

    private $listRows;//每页显示行数

    private $limit;

    private $uri;

    private $pageNum; //页数

    private $config=array('header'=>"个记录", "prev"=>"上一页", "next"=>"下一页", "first"=>"首 页", "last"=>"尾 页");

    private $listNum=8;

    /*

     * $total 

     * $listRows

     */

    public function __construct($total, $listRows=10, $pa=""){

        $this->total=$total;

        $this->listRows=$listRows;

        $this->uri=$this->getUri($pa);

        $this->page=!empty($_GET["page"]) ? $_GET["page"] : 1;

        $this->pageNum=ceil($this->total/$this->listRows);

        $this->limit=$this->setLimit();

    }



    private function setLimit(){

        return ($this->page-1)*$this->listRows.", {$this->listRows}";

    }



    private function getUri($pa){

        $url=$_SERVER["REQUEST_URI"].(strpos($_SERVER["REQUEST_URI"], '?')?'':"?").$pa;

        $parse=parse_url($url);

        if(isset($parse["query"])){

            parse_str($parse['query'],$params);

            unset($params["page"]);

            $url=$parse['path'].'?'.http_build_query($params);    

        }

        return $url;

    }



    private function __get($args){

        if($args=="limit")

            return $this->limit;

        else

            return null;

    }



    private function start(){

        if($this->total==0)

            return 0;

        else

            return ($this->page-1)*$this->listRows+1;

    }



    private function end(){

        return min($this->page*$this->listRows,$this->total);

    }



    private function first(){

        $html="";

        if($this->page==1)

            $html.='';

        else

            $html.="&nbsp;&nbsp;<a href='javascript:setPage(1)'>{$this->config["first"]}</a>&nbsp;&nbsp;";

        return $html;

    }



    private function prev(){

        $html="";

        if($this->page==1)

            $html.='';

        else

            $html.="&nbsp;&nbsp;<a href='javascript:setPage(". ($this->page-1) .")'>{$this->config["prev"]}</a>&nbsp;&nbsp;";

        return $html;

    }



    private function pageList(){

        $linkPage="";

        $inum=floor($this->listNum/2);

    

        for($i=$inum; $i>=1; $i--){

            $page=$this->page-$i;

            if($page<1)

                continue;

            $linkPage.="&nbsp;<a href='javascript:setPage({$page})'>{$page}</a>&nbsp;";



        }

        $linkPage.="&nbsp;{$this->page}&nbsp;";

        for($i=1; $i<=$inum; $i++){

            $page=$this->page+$i;

            if($page<=$this->pageNum)

                $linkPage.="&nbsp;<a href='javascript:setPage({$page})'>{$page}</a>&nbsp;";

            else

                break;

        }

        return $linkPage;

    }



    private function next(){

        $html="";

        if($this->page==$this->pageNum)

            $html.='';

        else

            $html.="&nbsp;&nbsp;<a href='javascript:setPage(". ($this->page+1) .")'>{$this->config["next"]}</a>&nbsp;&nbsp;";

        return $html;

    }



    private function last(){

        $html="";

        if($this->page==$this->pageNum)

            $html.='';

        else

            $html.="&nbsp;&nbsp;<a href='javascript:setPage(". ($this->pageNum) .")'>{$this->config["last"]}</a>&nbsp;&nbsp;";

        return $html;

    }



    private function goPage(){

        return '&nbsp;&nbsp;<input type="text" onkeydown="javascript:if(event.keyCode==13){var page=(this.value>'.$this->pageNum.')?'.$this->pageNum.':this.value;setPage(page)}" value="'.$this->page.'" style="width:25px"><input type="button" value="GO" onclick="javascript:var page=(this.previousSibling.value>'.$this->pageNum.')?'.$this->pageNum.':this.previousSibling.value;setPage(page)">&nbsp;&nbsp;';

    }

    function fpage($display=array(0,1,2,3,4,5,6,7,8)){

        $html[0]="&nbsp;&nbsp;共有<b>{$this->total}</b>{$this->config["header"]}&nbsp;&nbsp;";

        $html[1]="&nbsp;&nbsp;每页显示<b>".($this->end()-$this->start()+1)."</b>条,本页<b>{$this->start()}-{$this->end()}</b>条&nbsp;&nbsp;";

        $html[2]="&nbsp;&nbsp;<b>{$this->page}/{$this->pageNum}</b>页&nbsp;&nbsp;";

        $html[3]=$this->first();

        $html[4]=$this->prev();

        $html[5]=$this->pageList();

        $html[6]=$this->next();

        $html[7]=$this->last();

        $html[8]=$this->goPage();

        $fpage='';

        foreach($display as $index){

            $fpage.=$html[$index];

        }

        return $fpage;

    }

}

?>
AjaxPage.class.php
<?php

/*include/Db.class.php*/

// 连接数据库

class Db {

    static public function getDB() {

        try {

            $pdo = new PDO(DB_DSN, DB_USER, DB_PWD);

            $pdo->setAttribute(PDO::ATTR_PERSISTENT, true);    // 设置数据库连接为持久连接

            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  // 设置抛出错误

            $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true);  // 设置当字符串为空转换为 SQL 的 NULL

            $pdo->query('SET NAMES utf8');  // 设置数据库编码

        } catch (PDOException $e) {

            exit('数据库连接错误,错误信息:'. $e->getMessage());

        }

        return $pdo;

    }

}

?>
Db.class.php
<?php 

/*include/Model.class.php*/

/** 

* 数据库操作类库 

* Last modify $Date: 2012-1-19 13:59;04 $ 

*/  

class Model {  

     

    /** 

     * 数据库添加操作 

     * @param string $tName 表名 

     * @param array $field 字段数组 

     * @param array $val 值数组 

     * @param bool $is_lastInsertId 是否返回添加ID 

     * @return int 默认返回成功与否,$is_lastInsertId 为true,返回添加ID 

     */  

    public function add($tName, $field, $val, $is_lastInsertId=FALSE) {  

        try {  

            if (!is_array($field) || !is_array($val)) exit($this->getError(__FUNCTION__, __LINE__));  

            $pdo = Db::getDB();  

            $field = $this->formatArr($field);  

            $val = $this->formatArr($val, false);  

            if (!$is_lastInsertId) {  

                $row = $pdo->exec("INSERT INTO {$tName} ({$field}) VALUES ({$val})");  

                $pdo = null;  

                return $row;  

            } else {  

                $pdo->exec("INSERT INTO {$tName} ({$field}) VALUES ({$val})");  

                $lastId = $pdo->lastInsertId();  

                $pdo = null;  

                return $lastId;  

            }  

        } catch (PDOException $e) {  

            exit($e->getMessage());  

        }  

    }  

      

    /** 

     * 数据库修改操作 

     * @param string $tName 表名 

     * @param array $field 字段数组 

     * @param array $val 值数组 

     * @param string $condition 条件 

     * @return int 受影响的行数 

     */  

    public function update($tName, $fieldVal, $condition) {  

        try {  

            if (!is_array($fieldVal) || !is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__));  

            $pdo = Db::getDB();  

            foreach ($fieldVal as $k=>$v) {  

                $upStr .= $k . '=' . '\'' . $v . '\'' . ',';  

            }  

            $upStr = rtrim($upStr, ',');  

            $row = $pdo->exec("UPDATE {$tName} SET {$upStr} WHERE {$condition}");  

            $pdo = null;  

            return $row;  

        } catch (PDOException $e) {  

            exit($e->getMessage());  

        }  

    }  

      

    /** 

     * 数据库删除操作(注:必须添加 where 条件) 

     * @param string $tName 表名 

     * @param string $condition 条件 

     * @return int 受影响的行数 

     */  

    public function del($tName, $condition) {  

        try {  

            if (!is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__));  

            $pdo = Db::getDB();  

            $row = $pdo->exec("DELETE FROM {$tName} WHERE {$condition}");  

            return $row;  

            $pdo = null;  

        } catch (PDOException $e) {  

            exit($e->getMessage());  

        }  

    }  

      

    /** 

     * 返回表总个数 

     * @param string $tName 表名 

     * @param string $condition 条件 

     * @return int 

     */  

    public function total($tName, $condition='') {  

        try {  

            if (!is_string($tName)) exit($this->getError(__FUNCTION__, __LINE__));  

            $pdo = Db::getDB();  

            $re = $pdo->query("SELECT COUNT(*) AS total FROM {$tName}" . ($condition=='' ? '' : ' WHERE ' . $condition));  

            foreach ($re as $v) {  

                $total = $v['total'];  

            }  

            return $total;  

        } catch (PDOException $e) {  

            exit($e->getMessage());  

        }  

    }  

      

    /** 

     * 数据库删除多条数据 

     * @param string $tName 表名 

     * @param string $field 依赖字段 

     * @param array $ids 删除数组 

     * @return int 受影响的行数 

     */  

    public function delMulti($tName, $field, $ids) {  

        try {  

            if (!is_string($tName) || !is_array($ids)) exit($this->getError(__FUNCTION__, __LINE__));  

            $pdo = Db::getDB();  

            foreach ($ids as $v) {  

                $delStr .= $v . ',';  

            }  

            $delStr = rtrim($delStr, ',');  

            $row = $pdo->exec("DELETE FROM {$tName} WHERE {$field} IN ({$delStr})");  

            $pdo = null;  

            return $row;  

        } catch (PDOException $e) {  

            exit($e->getMessage());  

        }  

    }  

      

    /** 

     * 获取表格的最后主键(注:针对 INT 类型) 

     * @param string $tName 表名 

     * @param string $primaryName 依赖字段 

     * @return int 

     */  

    public function lastId($tName, $primaryName) {  

        try {  

            if (!is_string($tName) || !is_string($primaryName)) exit($this->getError(__FUNCTION__, __LINE__));  

            $pdo = Db::getDB();  

            $re = $pdo->query("SELECT {$primaryName} FROM {$tName} ORDER BY {$primaryName} DESC LIMIT 1");  

            $lastId = null;  

            foreach ($re as $v) {  

                $lastId = $v[$primaryName];  

            }  

            $pdo = null;  

            return $lastId;  

        } catch (PDOException $e) {  

            exit($e->getMessage());  

        }  

    }  

      

    /**  

     * 返回全部数据,返回 PDOStatement 对象 

     * @param string $sql 

     * @return PDOStatement 

     */  

    public function getAll($sql) {  

        try {  

            if (!is_string($sql)) exit($this->getError(__FUNCTION__, __LINE__));  

            $pdo = Db::getDB();  

            $result = $pdo->query($sql);  

            $pdo = null;

            return $result;  

        } catch (PDOException $e) {  

            exit($e->getMessage());  

        }  

    }  

      

    /**

     * 检查数据是否已经存在(依赖条件)

     * @param string $tName 表名 

     * @param string $field 依赖的字段

     * @return bool

     */

    public function isExists($tName, $condition) {

        try {

            if (!is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__));

            $pdo = Db::getDB();

            $result = $pdo->query("SELECT COUNT(*) AS total FROM {$tName} WHERE {$condition}");

            foreach ($result as $v) {

                 $b = $v['total'];

            }

            $pdo = null;

            if ($b) {

                return true;

            } else {

                return false;

            }

        } catch (PDOException $e) {

            exit($e->getMessage());

        }

    }



    /**

     * 检查数据是否已经存在(依赖 INT 主键)

     * @param string $tName 表名 

     * @param string $primary 主键

     * @param int $id 主键值

     * @return bool

     */

    public function isExistsByIntPrimary($tName, $primary, $id) {

        try {

            if (!is_string($tName) || !is_string($primary) || !is_int($id)) exit($this->getError(__FUNCTION__, __LINE__));

            $pdo = Db::getDB();

            $result = $pdo->query("SELECT COUNT(*) AS total FROM {$tName} WHERE {$primary} = ". $id);

            foreach ($result as $v) {

                 $b = $v['total'];

            }

            $pdo = null;

            if ($b) {

                return true;

            } else {

                return false;

            }

        } catch (PDOException $e) {

            exit($e->getMessage());

        }

    }

      

    /** 

     * 预处理添加数据(推荐使用)

     * @param string $tableName  表格名 

     * @param array $fieldArr  字段名数组 

     * @param array $valArr  字段值数组 

     * @param bool  $mult  是否添加多条数据,如果是那么 $valArr 为二维数组

     * @return int  返回添加的记录数,添加单条为1,多条为多

     */  

    public function insert($tableName, $fieldArr, $valArr, $mult=FALSE) {  

        try {  

            if (!is_string($tableName) || !is_array($fieldArr) || !is_array($valArr) || !is_bool($mult)) exit($this->getError(__FUNCTION__, __LINE__));  

            $pdo = Db::getDB();

            $fields = $this->formatArr($fieldArr);

            $arrCount = count($fieldArr);

            $mark = $this->formatMark($arrCount);

            $stmt = $pdo->prepare("INSERT INTO {$tableName} ({$fields}) VALUES ({$mark})");

            if (!$mult) {

                $row = $stmt->execute($valArr); // 添加单条数据

            } else {

                $row = 0;

                for ($i=0; $i<count($valArr); $i++) {

                    if ($stmt->execute($valArr[$i])) {

                        $row++;

                    }

                }

            }

            $pdo = null;  

            return $row;  

        } catch (PDOException $e) {  

            exit($e->getMessage());  

        }  

    }  

    

    /**

     * 预处理删除(注:针对主键为 INT 类型,推荐使用)

     * @param string $tName 表名

     * @param string $primary 主键字段

     * @param int or array or string $ids 如果是删除一条为 INT,多条为 array,删除一个范围为 string

     * @return int 返回受影响的行数

     */

    public function remove($tName, $primary, $ids, $mult=FALSE) {

        try {

            if (!is_string($tName) || !is_string($primary) || (!is_int($ids) && !is_array($ids) && !is_string($ids)) || !is_bool($mult)) exit($this->getError(__FUNCTION__, __LINE__));

            $pdo = Db::getDB();

            $stmt = $pdo->prepare("DELETE FROM {$tName} WHERE {$primary}=?");

            if (!$mult) {

                $stmt->bindParam(1, $ids);

                $row = $stmt->execute();

            } else {

                if (is_array($ids)) {

                    $row = 0;

                    foreach ($ids as $v) {

                        $stmt->bindParam(1, $v);

                        if ($stmt->execute()) {

                            $row++;

                        }

                    }

                } elseif (is_string($ids)) {

                    if (!strpos($ids, '-')) exit($this->getError(__FUNCTION__, __LINE__));

                    $split = explode('-', $ids);

                    if (count($split)!=2 || $split[0]>$split[1]) exit($this->getError(__FUNCTION__, __LINE__));

                    $i = null;

                    $count = $split[1]-$split[0]+1;

                    for ($i=0; $i<$count; $i++) {

                        $idArr[$i] = $split[0]++;

                    }

                    foreach ($idArr as $id) {

                        $idStr .= $id . ',';

                    }

                    $idStr = rtrim($idStr, ',');

                    $row = $pdo->exec("DELETE FROM {$tName} WHERE {$primary} in ({$idStr})");            

                }

            }

            return $row;

            $pdo = null;

        } catch (PDOException $e) {

            exit($e->getMessage());

        }

    }

    

    /**

     * 返回单条数据

     * @param string $tName 表名

     * @param string $condition 条件

     * @param string or array $fields 返回的字段,默认是*

     * @return PDOStatement

     */

    public function getOne($tName, $condition, $fields="*") {

        try {

            if (!is_string($tName) || !is_string($condition) || !is_string($fields)) exit($this->getError(__FUNCTION__, __LINE__));

            $pdo = Db::getDB();

            $data = $pdo->query("SELECT {$fields} FROM {$tName} WHERE {$condition} LIMIT 1");

            $pdo = null;

            return $data;

        } catch (PDOException $e) {

            exit($e->getMessage());

        }

    }

    

    /**

     * 返回全部数据

     * @param string $tName 表名

     * @param string $fields 返回字段,默认为*

     * @param string $condition 条件

     * @param string $order 排序

     * @param string $limit 显示个数

     * @return PDOStatement

     */

    public function fetchAll($tName, $fields='*', $condition='', $order='', $limit='') {

        try {

            if (!is_string($tName) || !is_string($fields) || !is_string($condition) || !is_string($order) || !is_string($limit)) exit($this->getError(__FUNCTION__, __LINE__));

            $fields = ($fields=='*' || $fields=='') ? '*' : $fields;

            $condition = $condition=='' ? '' : " WHERE ". $condition ;

            $order = $order=='' ? '' : " ORDER BY ". $order;

            $limit = $limit=='' ? '' : " LIMIT ". $limit;

            $pdo = Db::getDB();

            $re = $pdo->query("SELECT {$fields} FROM {$tName} {$condition} {$order} {$limit}");

            return $re;

        } catch (PDOException $e) {

            exit($e->getMessage());

        }

    }

    

    /** 

     * 格式化数组(表结构和值) 

     * @param array $field 

     * @param bool $isField 

     * @return string 

     */  

    private function formatArr($field, $isField=TRUE) {  

        if (!is_array($field)) exit($this->getError(__FUNCTION__, __LINE__));  

        if ($isField) {  

            foreach ($field as $v) {  

                $fields .= $v.',';  

            }  

        } else {  

            foreach ($field as $v) {  

                $fields .= '\''.$v.'\''.',';  

            }  

        }  

        $fields = rtrim($fields, ',');  

        return $fields;  

    }

    

    /**

     * 格式化问号

     * @param int $count 数量

     * @return string 返回格式化后的字符串

     */

    private function formatMark($count) {

        if (!is_int($count)) exit($this->getError(__FUNCTION__, __LINE__));

        if ($count==1) return '?';

        for ($i=0; $i<$count; $i++) {

            $str .= '?,';

        }

        return rtrim($str, ',');

    }

    

    /** 

     * 错误提示 

     * @param string $fun 

     * @return string 

     */  

    private function getError($fun, $line) {  

        return __CLASS__  . '->' . $fun . '() line<font color="red">'. $line .'</font> ERROR!';  

    }  

}  

?>
Model.class.php

 9)生成6位手机验证码

//生成手机验证码

    function get_mobile_code()

    {

        $forbidden_num = "1989:10086:12590:1259:10010:10001:10000:";

        do

        {

            $mobile_code = substr(microtime(), 2, 6);

        }

        while (preg_match($mobile_code.':', $forbidden_num));

        return $mobile_code;

    }

 

你可能感兴趣的:(PHP)