note 109269 added to function.implode

From: Date: Sun, 01 Jul 2012 12:15:03 +0000
Subject: note 109269 added to function.implode
Groups: php.notes 
Request: Send a blank email to php-notes+get-188989@lists.php.net to get a copy of this message
Interesting function I created will automatically get all the columns of a table and input the values dynamically into that table after form submission. A separate part of the script uses similar logic to generate the form fields. <?php function insertIntoDb($db, $table, $carry, $carryUrl) { mysql_select_db($db) or die("Could not select database. " . mysql_error()); $resultInsert = mysql_query("SHOW COLUMNS FROM " . $table); $fieldnames=array(); if (mysql_num_rows($resultInsert) > 0) { while ($row = mysql_fetch_array($resultInsert)) { $fieldnames[] = $row['Field']; $values = array_intersect_key( $_POST, array_flip($fieldnames) ); } } $sql = sprintf('INSERT INTO %s (%s) VALUES ("%s")', $table, implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values))); mysql_query($sql); if ($carry == 'yes') { redirect($carryUrl.'?id='.$_REQUEST['id']); } else { echo '<div class="success">Data was entered into the database successfully!<br><a href="view.php?type=recent">View listing?</a></div>'; } } function updateDbRecord($db, $table, $carry, $carryUrl) { mysql_select_db($db) or die("Could not select database. " . mysql_error()); $resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')"); $fieldnames=array(); if (mysql_num_rows($resultInsert) > 0) { while ($row = mysql_fetch_array($resultInsert)) { $fieldnames[] = $row['Field']; $array = array_intersect_key( $_POST, array_flip($fieldnames) ); } } foreach ($array as $key => $value) { $value = mysql_real_escape_string($value); $value = "'$value'"; $updates[] = "$key = $value"; } $implodeArray = implode(', ', $updates); $sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']); mysql_query($sql); if ($carry == 'yes') { redirect($carryUrl.'?id='.$_REQUEST['id']); } else { echo "Done!"; } } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 89.99.64.52 ---- Manual Page -- http://www.php.net/manual/en/function.implode.php Edit -- https://master.php.net/note/edit/109269 Del: integrated -- https://master.php.net/note/delete/109269/integrated Del: useless -- https://master.php.net/note/delete/109269/useless Del: bad code -- https://master.php.net/note/delete/109269/bad+code Del: spam -- https://master.php.net/note/delete/109269/spam Del: non-english -- https://master.php.net/note/delete/109269/non-english Del: in docs -- https://master.php.net/note/delete/109269/in+docs Del: other reasons-- https://master.php.net/note/delete/109269 Reject -- https://master.php.net/note/reject/109269 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188989) next »