I was going through this article today.
http://vinothbabu.com/2010/05/08/update-and-insert-differences-in-syntax-is-an-inconvenience/
I was not able to understand this part of the code written by the author.
list($sets,$cols,$values)=escape_arr($sets);
$insert_sql=”INSERT INTO `avatars` “.implode(’,',$cols).”
VALU开发者_如何学PythonES(”.implode(’,',$values).”)”;
$update_sql=”UPDATE `avatars` SET “.implode(’,',$sets).”
WHERE userid=$userid LIMIT 1″;
and finally the conclusion part of the article.
The PHP implode turns the array of column names into a comma separated string. It does the same for the values in the INSERT statement.
$sets starts off as an associative array of column name / value pairs. This statement:
list($sets, $cols, $values) = escape_arr($sets);
reassigns the $sets variable to be a regular array containing strings like "column_name = 'value'". It does this with the helper function escape_arr in the article, which returns 3 arrays. Check the documentation for list if you're unsure what it does.
Then it uses the implode
function again to build one big comma separated string of the $sets
array. So effectively, it builds both INSERT and UPDATE statements given an associative array containing column names as keys, and their values as well... values.
Was that the question? You can insert some var_dump statements in the code to follow what it's doing at every step.
Edit: sorry for the messy explanation, but I gotta run for now :)
On a side note, in MySQL INSERTs can use the UPDATE syntax:
INSERT [INTO] tbl
SET col1 = 'value', col2 = 'value', col3 = 'value', ...
Refer to the MySQL INSERT syntax for the full documentation.
That does not make any sense. He suggests to hardcode your queries because that way you can avoid thinking about them as objects (WTF?) then goes on to tell hardcoding is bad, apparently not realizing that is exactly what he is doing. Also. WHERE userid=$userid LIMIT 1
is bad coding practice, omitting quotes can result in SQL injection. And why the LIMIT 1? He is using non-unique userid?
There are a lot of saner solutions for separation of database layer, such as data access objects, object-relational mapping, active records...
精彩评论