php在mysql中随机插入数据

来源:互联网 发布:带文字单页源码 编辑:程序博客网 时间:2024/05/22 04:25

数据库结构:

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | int(11)     | NO   |     | NULL    |       |
| username | varchar(15) | NO   |     | NULL    |       |
| sex      | char(1)     | NO   |     | NULL    |       |
| brith    | date        | NO   |     | NULL    |       |
| city     | varchar(20) | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+

<?
class rand_sql
{
    private $con;
    private $sexarray = array('F','M');
    private $usernamearry = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
    private $cityarray = array('北京市','天津市','上海市','重庆市','合肥','宿州','淮北','马鞍山','郑州','洛阳','齐齐哈尔',
                            '黑河','大庆','伊春','鹤岗','佳木斯','武汉','兰州','嘉峪关','金昌','酒泉','庆阳','龙海','漳平',
                            '石狮','福安','清远','广州','梅州','汕头','惠州','东莞','中山','江门','普宁','廉江','雷州');
    
    public function __construct()
    {
        ini_set("max_execution_time",600000000);
    }
    //连接数据库
    public function mysql_connect($host,$user,$pwd,$usedb)
    {
        $this->con = mysql_connect($host,$user,$pwd) or die(mysql_error());
        mysql_select_db($usedb,$this->con);
        mysql_query("set names gb2312");
    }
    
    public function mysql_insert()
    {
        echo'start insert'."<br/>";
        for ($i=714134;$i<2000000;$i++)//可以更改插入条数
        {
            $user = $this->createname();
            $sex = $this->createsex();
            $birth = $this->createbrith();
            $city = $this->createcity();
            
            $sql = "insert into mytable value ('$i','$user','$sex','$birth','$city')";
            $query = mysql_query($sql,$this->con);
        }
        echo 'insert ok';
    }
    
    private function createname()
    {
        for ($i=0;$i<5;$i++)
        {
            $name = rand(0,25);
            $namestr .= $this->usernamearry[$name];
        }
        return $namestr;
    }
    
    private function createsex()
    {
        $sex = rand(0,1);
        return $this->sexarray[$sex];
    }
    
    private function createbrith()
    {
        $start=mktime(0,0,0,1,1,1974);
        $end=mktime(23,59,59,1,1,2024);
        $rand=rand($start,$end);
        $year=date("Y",$rand)-24;
        return $year.date("-m-d",$rand);
    }
    
    private function createcity()
    {
        $city = rand(0,count($this->cityarray)-1);
        return $this->cityarray[$city];
    }
    
    public function __destruct()
    {
        mysql_close($this->con);
    }
}

$randsql = new rand_sql();
$randsql->mysql_connect('localhost','root','root','test');
$randsql->mysql_insert();

0 0
原创粉丝点击