Malik Tauqeer Malik Tauqeer - 5 months ago 8
MySQL Question

PHP - MYSQL - Is it a good practice to use php class as below


  • Updates a current row in the database. takes an array of data, where
    the keys in the array are the column names and the values are the
    data that will be inserted into those columns. $table is the name of
    the table and $where is the sql where clause.




In this case, we pass an array of data, table name, and where clause.
and foreach loop is called as many times the data array passed. I just
wanted to know if it is a good way to update data or insert data. Why
I am asking is because in this situation, foreach will execute query
for each column separately which will take longer than data inserted
using single query.


public function update($data, $table, $where) {
foreach ($data as $column => $value) {
$sql = "UPDATE $table SET $column = $value WHERE $where";
mysql_query($sql) or die(mysql_error());
}
return true;
}

Answer

If you have a small amount of data, it is okay. However, a sql query inside a loop is usually considered not good because it takes longer. Instead, nest your $sql string in the loop and run the query once. Like this:

public function update($data, $table, $where) {
        $sql = "";
        foreach ($data as $column => $value) {
            $sql .= "UPDATE $table SET $column = $value WHERE $where";
        }
        mysql_query($sql) or die(mysql_error());
        return true;
    }