如何将PHP对象转储到SQL表中?

如何将PHP对象转储到SQL表中?

问题描述:

I'm wondering if there is a quick way to do the following:

I have a PHP object with multiple attributes. For example

$person;
$person->height = 165;
$person->name = 'john';

I would like to dump this into an SQLite MySQL DB while creating each column automatically from the attribute names of the PHP object. So for example, if I were to dump the above object into mySQL, it would look something like this:

Table : people
Name(Column, VARCHAR)  -  "John"
Height(Column, INT)  -  165 

The reason I am asking this is because the number of attributes is growing constantly, and having to create and manage the table columns manually is a lot of work. I am wondering if there is an automated way of doing this.

我想知道是否有快速的方法来执行以下操作: p> 我有一个具有多个属性的PHP对象。 例如 p>

  $ person; 
 $ person-> height = 165; 
 $ person-> name ='john'; 
  code>  
 
 

我想将这个转储到SQLite MySQL数据库中,同时从PHP对象的属性名称自动创建每一列。 例如,如果我将上述对象转储到mySQL中,它看起来像这样: p>

 表:people 
Name(Column,VARCHAR) - “John”  
Height(Column,INT) -  165 
  code>  pre> 
 
 

我问这个的原因是因为属性的数量不断增加,并且必须创建和管理表 手动列是很多工作。 我想知道是否有自动执行此操作的方法。 p> div>

First you need to convert object into array and then you can iterate through it and can create table and insert values in it.

Something like below:

Step 1: Convert object to array

Step 2: Get keys(fields) and values out of array

Step 3: Generate sql queries

    <?php
    //Step 1: convert object to array
    //$persion =  (array) $yourObject;

    //Step 2: get keys(fields) and values out of array
    $person = array(
        "height" => "165",
        "name" => "john",
        "age" => "23"
    );

    function data_type($val) {
        if(is_numeric($val)) { 
            return "int"; 
        } 
        else {
            return "varchar(15)";
        }   
    }

    //Step 3: sql query, only including sql query
    function create_table($person) {
        $create = "CREATE TABLE IF NOT EXISTS people";
        $ctr = 0;
        foreach($person as $key => $value) {
            if($ctr == 0) {
                $field_query = $key." ".data_type($value);
            } else {
                $field_query .= ", ".$key." ".data_type($value);
            }
            $ctr++;
        }
        echo $create .= " (".$field_query.")";
        echo "<br/>";
    }
    create_table($person);

    function insert_table($person) {
        $ctr = 0;
        foreach($person as $key => $value) {
            if($ctr == 0) {
                $field_query = $key;
                $value_query = $value;
            } else {
                $field_query .= ", ".$key;
                $value_query .= ", ".$value;
            }
            $ctr++;
        }
        echo $insert = "INSERT INTO people"." (".$field_query.") VALUES (".$value_query.")";
    }
    insert_table($person);

    ?>

Hope this will help you in some way(y).