|
jpadie (TechnicalUser) |
18 Aug 11 13:12 |
not tested but this might get you started. key thing is to ensure that each field in your form is listed (case sensitively) in the $fields array at the top of the script. the field names MUST match the form names (case sensitive again). to trigger a download point your browser at the script and add here is the code CODE <?php ob_start(); $fields = array('name','emailaddress','message'); $host = 'localhost'; $dbname = 'mydb'; $user = 'myuser'; $pwd = 'mypwd';
if (isset($_REQUEST['action'])): switch (strtolower($_REQUEST['action'])): case 'save': savedata(); showthankyoupage(); break; case 'download': downloaddata(); break; endswitch; else: displayform(); endif;
function connectdb(){ global $host, $dbname, $user, $pwd; global $pdo; $pdo = new PDO( "mysql:host=$hose;dbname=$dbname", $user, $pwd array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" ); } function savedata(){ global $fields; foreach($fields as $field): $placeholder[] = '?'; $params[] = empty($_REQUEST[$field]) ? '' : trim($_REQUEST[$field]; endforeach; connectdb(); global $pdo; $s = $pdo->prepare("Insert into formdata (". implode(',', $fields) . ") VALUES (". implode(',',$placeholder) .")"); $pdo->execute($params); return true; }
function showthankyoupage(){ ob_end_clean(); include 'thankyoupagetemplate.php'; exit; }
function downloaddata(){ global $fields; connectdb(); global $pdo; $s = $pdo->prepare("select * from formdata"); $s->execute(); $output = <<<OP <table> <thead> <tr> <th> OP; $output .= implode('</th><th>', $fields); $output .= '</th></tr></thead>'; $output .= '<tbody>'; while ($row = $s->fetchObject()): $inner = array(); foreach($fields as $field): $inner[] = '<td>' . htmlspecialchars($row->$field) . '</td>'; endforeach; $output .= '<tr>' . implode("\n", $inner) . '</tr>'; endwhile; $output .= "</tbody></thead>"; ob_end_clean(); header("Content-Disposition: attachment; filename=\"formData.xls\""); header("Content-Type: application/vnd.ms-excel"); echo $output; }
function displayform(){ include 'formpage.php'; } ?>
|
|