0

If I have a class like this

class User {
    public $id;
    public $first_name;
    public $last_name;

}

how to map those properties to its corresponding database fields.

later , If I want to update a row, I can use something like this instead of passing some parameters to the update method

 $user->first_name="john";
    $user->update();

I have seen people are mapping object properties.

why and how to do it , I am new to OOP. please help me.Thanks.

2 Answers 2

0

What you are describing is called "Object-relational mapping" (ORM). It is a technique (or design pattern) of accessing a relational database (like MySQL) from a code written in object-oriented way.

There are several popular PHP ORM libraries that you can use out-of-the-box to achieve what you described. (doctrine, Propel etc.) And most of the PHP frameworks come with a bundled ORM.

In case you want to try implemnting you own ORM in PHP as a lerning exercise, refer this guide.

0

YOUR EXPECTED RESULT

 $InputArray['cal1'] =  $_POST['cal1'];
$InputArray['collabc'] =  $_POST['collabc'];
$InputArray['col123'] =  $_POST['col123'];
$InputArray['clofoo'] =  $_POST['clofoo'];
$InputArray['coldef'] =  $_POST['coldef'];

if (count($inputArray) > 0) {
        while (list($key, $val) = each($inputArray)) {
            if(!empty($val)){
                $fields.= $key . ',';
                $valset.= "'". $val ."',";
            }
        }
    }   

    $fields = trim($fields, ',');
    $valset = trim($valset, ',');
    $sql = "INSERT INTO $tableName ($fields) VALUES ($valset)";

REFER PDO insert based on array keys as column names

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.