Hello.

I've been learning a bit of PHP for a small school project. The project is almost done just that 1 thing is missing. I need a way to output something I searched into CSV / Excel.
I found a script which im using currently. It works beautifully I just can't figure out how to create a search form for it.

<?php

$DB_Server = "localhost"; //MySQL Server    
$DB_Username = "root"; //MySQL Username     
$DB_Password = "";             //MySQL Password     
$DB_DBName = "database";         //MySQL Database Name  
$DB_TBLName = "table"; //MySQL Table Name   
$filename = "search";         //File Name

//create MySQL connection 
$sql = "Select column1, column2 , ...  from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database   
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());   
//execute query 
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());    
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");

/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");    
//end of printing column names  
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }   
?>

Thats what im using currently. I want to be able to search, for example - ID1,ID2,ID3 and it outputs the search into a csv or excel file.
I really hope someone knows what im trying to do.
Thank you.

Dani AI

Generated

— your current script works but uses the old mysql_* functions and manually builds a tabbed “.xls”. A safer, more maintainable pattern is: accept a comma-separated list of IDs from a small form, split and validate those IDs, run a parameterized query (PDO or mysqli) using an IN(...) clause built from placeholders, then stream the result as a proper CSV with PHP’s fputcsv (Excel opens CSVs reliably). That avoids SQL injection and handles quoting/commas correctly.

Example (minimal, replace credentials/columns/table as needed):

<?php
$raw = $_POST['ids'] ?? '';
$items = preg_split('/\s*[,\r\n]+\s*/', trim($raw));
$items = array_values(array_filter($items, function($v){ return $v !== ''; }));
// optional: validate numeric IDs
$items = array_filter($items, function($v){ return preg_match('/^\d+$/', $v); });
if (!$items) exit('No IDs provided.');

$placeholders = implode(',', array_fill(0, count($items), '?'));
$pdo = new PDO('mysql:host=localhost;dbname=DB;charset=utf8mb4','user','pass',[
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$stmt = $pdo->prepare("SELECT col1, col2 FROM your_table WHERE id IN ($placeholders)");
$stmt->execute(array_values($items));

header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="export.csv"');
$out = fopen('php://output','w');
fwrite($out, "\xEF\xBB\xBF"); // UTF-8 BOM so Excel shows UTF-8 correctly
$first = true;
while ($row = $stmt->fetch()) {
  if ($first) { fputcsv($out, array_keys($row)); $first = false; }
  fputcsv($out, $row);
}
fclose($out);
exit;
?>

Notes and tips: never echo/print before headers; for non-numeric IDs skip the numeric check and still use prepared statements; for very large exports fetch and write rows in chunks (don’t load all rows into memory); Excel may strip leading zeros — if you must preserve them, format them as text or prefix appropriately; if you need a true .xlsx file, use a library such as PhpSpreadsheet. ’s advice to strengthen your PHP fundamentals is sound — once you learn PDO + fputcsv this becomes straightforward.

I think you're trying to find code rather than design and write code. That's going to be trouble for you as I rarely see members here write apps for others (unless well paid.)

So, with that out of the way, it's time to head back to school on PHP. https://www.phpschool.io/ has been noted by many here.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.