First, I need to tell you that I am pretty new in PHP OOP so please bear with me.
When I create the MySQL tables, I prefer to specify the name of the table in columns. For example instead of id in users table I use user_id, or instead of id in photos table I use photo_id. That helps me understand the MySQL statements easier when I check them later on. (I understand that different people have different preferences)
Now, the problem is, when I have a method in a class that uses the table's id but I want to use the in sub-classes that each target different tables. Here is an example:
I have two tables. One for users and one for photos. The user table have PK as user_id and the photo table and PK as photo_id. For each table I have a class with the same names. Also, both classes have many methods in comman, so I created one class and put these classes and sub-classes and mostly it is fine. The problem comes when I want to target a table based on it's ID, like the Save method below:
// updates a row if it exists, creates it if it doesn't
public function Save(){
return isset($this->user_id) ? $this->Update() : $this->Create();
}
//Creates a user in Database
public function Create(){
global $Database;
$Properties = $this->CleanProperties();
$Sql = "INSERT INTO " . self::$DBTable . "(" . implode(",", array_keys($Properties)) . ")";
$Sql .= "VALUE ('";
$Sql .= implode("', '", (array_values($Properties)));
$Sql .= "')";
if ($Database->Query($Sql)){
$this->user_id= $Database->InsertID();
return true;
} else {
return false;
}
}
/// Updates a user in Database
/// returns "true" if the row is affected
/// returns "false" if not
Public function Update(){
global $Database;
$Properties = $this->CleanProperties();
$PropertyPairs = array ();
foreach ($Properties as $Key => $Value){
$PropertyPairs[] = "{$Key}='{$Value}'";
}
$Sql = "UPDATE " . self::$DBTable . " SET ";
$Sql .= implode(", ", $PropertyPairs);
$Sql .= " WHERE user_id = " . $Database->EscapeString($this->user_id) ;
$Database->Query($Sql);
return (mysqli_affected_rows($Database->DBConnection) == 1) ? true : false;
}
/// Deletes a user row from MySQL base on the user ID
/// returns "true" if the row is affected
/// returns "false" if not
public function Delete(){
global $Database;
$Sql = "DELETE FROM " . self::$DBTable;
$Sql .= " WHERE user_id = ";
$Sql .= $Database->EscapeString($this->user_id);
$Sql .= " LIMIT 1";
$Database->Query($Sql);
return (mysqli_affected_rows($Database->DBConnection) == 1) ? true : false;
}
I searched for different solutions and what I found was a method called fetch_field_direct. But, using that made me more confused.
Does anyone have a solution for this? Thanks