PHP中的简单ORM MySQL更新连接表

I'm currently trying to write a simple ORM with PHP and mysql. I want the orm class to be able to work with joined tables. So here's my problem, the following code shows how I map the data the query yields into an array.

public function execute_query($db_connection)
{
    $query = '';

    foreach($this->sql_query as $query_part)
        $query .= $query_part;

    $result = $db_connection->query($query);
    while($row = $result->fetch_assoc())
    {
        array_push($this->m_Data, $row);
    }
}

db_connection is a mysqli object. sql_query contains all the different query parts (e.g. sql_query['join'] etc.). m_Data is the array that contains the data read from the db.

My specific problem now is when I'm using a join statement in my query this function will just override fields with the same name in my m_Data array. Also if I dont save the name's of the table the specific field data is coming from, I later can't update the tables with the same join statement.

tl,dr. I need to be able to not only save the table data like this: m_Data{ 'field_name' => 'value' } but I also need to save the table name the field is selected from. I could then save the data like this m_Data{ 'table_name.field_name' => 'value' } which enables me later to generate a query to update the joined tables successfully.

I cant seem to find any information on how to get the origin table name for each field I pull out of the result.

If it isnt possible with mysqli I'd much appreciate it if you point me in the right direction.

extra short problem statement: I need to get a result set and read each row seperatly. For each row I need the following information for every field selected: field_name, table_name, value.

There must be a simple answer to this but I seem to be searching for the wrong keywords to find a solution.

I hope I've written this understandable enough.

Seems to me that you should store table column values in an object, so if you have a related table, the column values would be stored in a separate object - and so would not interfere with the values in your primary table.

In general you might work with the ORM this way:

// Make joined query
$rows = ...

foreach($rows as $row)
{
    // $row just refers to the primary table
    echo $row->id;

    // You get a many:1 related table this way
    echo $row->getRelatedRow()->value;

    // You get a 1:many rows this way
    $rows = $row->getOtherRelatedRows();
}

Depending on how you set up your query options, getting related data may or may not initiate further SELECTs to get the required data.

mysqli_result::fetch_fields has useful things:

http://www.php.net/manual/en/mysqli-result.fetch-fields.php

  • table
  • orgtable
  • field type
  • etc