php - PDO - Dynamic Query Building -
is somehow possible built dynamic query pdo?
description:
have following function:
function
savecontent($roundid,$answer,$question_de,$question_en,$files_1_1,$files_1_2,$files_2_1,$files_2_2,$files_3_1,$files_3_2) { $sql_pictures = " update ".dbprefix."pictures set file_1_static=:files_1_1, file_1_animation=:files_1_2, file_2_static=:files_2_1, file_2_animation=:files_2_2, file_3_static=:files_3_1, file_3_animation=:files_3_2 roundid=:roundid"; try { $db = self::getconnection(); $stmt_pictures = $db->prepare($sql_pictures); $stmt_pictures->bindparam("roundid", $roundid); $stmt_pictures->bindparam("files_1_1", $$question_de); $stmt_pictures->bindparam("files_1_2", $question_en); $stmt_pictures->bindparam("files_2_1", $roundid); $stmt_pictures->bindparam("files_2_2", $$question_de); $stmt_pictures->bindparam("files_3_1", $question_en); $stmt_pictures->bindparam("files_3_2", $question_en); $stmt_pictures->execute(); $db = null; return true; } catch(pdoexception $e) { echo $e->getmessage(); } }
the important part in "sql_pictures". i'm calling function passing necessary data function, this:
if (isset($_post['save'])) { $savecontent = $helper->savecontent( $_post['roundid'], $_post['answer'], $_post['question_de'], $_post['question_en'], $_files["files_1_1"], $_files["files_1_2"], $_files["files_2_1"], $_files["files_2_2"], $_files["files_3_1"], $_files["files_3_2"] ); }
as of maybe notice, it's multiple file upload.
main problem is, don't want update fields when either string empty (not set) or value didn't changed (i.e $files_1_1 didn't changed or empty).
how can achieve that?
other question:
maybe better use
<input type="file" name="files[]" id="file" />
instead of
<input type="file" name="files_1_2" id="file" />
for each input field?
, how can refactor function then? i'm sitting on many hours, no clue. hint nice! :)
thanks!
for insert/update queries dynamic query building quite simple task. create array key names equal field names , corresponding values , process them in loop.
i don't want update fields when either string empty (not set) or value didn't changed
the last 1 doesn't matter. if value didn't change - won't changed in table either.
other values create array values suits (i.e not empty) , use helper function create set statement dynamically. can use 1 pdo tag wiki example
other question:
personally prefer files_1, files_2, files_3...
way lets me iterate on $_files
array using simple foreach
Comments
Post a Comment