Skip to content

Instantly share code, notes, and snippets.

@rlemon
Created February 8, 2012 21:48
Show Gist options
  • Select an option

  • Save rlemon/1774163 to your computer and use it in GitHub Desktop.

Select an option

Save rlemon/1774163 to your computer and use it in GitHub Desktop.
Easy Table Editor
<?php
class Database extends PDO {
public function __construct() {
parent::__construct( DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS );
}
}
$dbh = new Database();
if( !isset( $_GET['tablename'] ) ) {
die('<form method="get"><label>Table Name: <input type="text" name="tablename" /></label><input type="submit" value="Lookup Table" /></form>');
}
$tablename = $_GET['tablename'];
if( isset( $_POST['submit_form'] ) ) {
foreach( $_POST as $k => $v ) {
if( $k != 'submit_form' && $k != 'where_clause' ) {
foreach( $v as $rowKey => $rowData ) {
$q = $dbh->prepare("UPDATE `$tablename` SET `$tablename`.`$k` = '$rowData' WHERE ". $_POST['where_clause'][$rowKey].";");
$q->execute();
}
}
}
}
$q = $dbh->prepare("DESCRIBE $tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
$q = $dbh->prepare("SELECT * FROM $tablename");
$q->execute();
$table_rows = $q->fetchAll(PDO::FETCH_NUM);
$q = $dbh->prepare("SHOW KEYS FROM $tablename WHERE Key_name = 'PRIMARY'");
$q->execute();
$table_key = $q->fetchAll(PDO::FETCH_ASSOC);
?>
<form method="post" name="edit_table_form">
<table>
<thead>
<tr>
<?php foreach($table_fields as $table_field): ?>
<th><?php echo $table_field; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php for($i = 0, $l = count($table_rows); $i < $l; $i++): ?>
<tr>
<?php for($j = 0, $k = count($table_rows[$i]); $j < $k; $j++): ?>
<?php if( $table_fields[$j] == $table_key[0]['Column_name'] ): ?>
<td><input type="hidden" name="where_clause[]" value="`<?php echo $tablename.'`.`'.$table_key[0]['Column_name'].'`'; ?> = <?php echo $table_rows[$i][$j]; ?>" /><?php echo $table_rows[$i][$j]; ?></td>
<?php else: ?>
<td><input type="text" name="<?php echo $table_fields[$j]; ?>[]" value="<?php echo $table_rows[$i][$j]; ?>" /></td>
<?php endif; ?>
<?php endfor; ?>
</tr>
<?php endfor; ?>
</tbody>
</table>
<input type="submit" name="submit_form" value="Submit form" />
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment