I have created a web application to allow users to upload CSV files into SQL Server. I have 8 columns in total. The id column in SQL Server is auto-increment so minus that column. The upload was successful however data imported are all null in each column. Also the number of records in my CSV is less than 100 however my SQL Server is showing more than 100 records imported which doesn't tally. Can anyone help to check what is wrong with my code?
Below is my code and a screenshot of my CSV file and SQL Server table.
<?php
$self = $_SERVER['PHP_SELF'];
$request = $_SERVER['REQUEST_METHOD'];
if (!isset($_GET['success'])) {
$get_success = "";
}
else {
$get_success = $_GET['success'];
}
if (!empty($_FILES)) {
/* Format the errors and die */
function get_last_error() {
$retErrors = sqlsrv_errors(SQLSRV_ERR_ALL);
$errorMessage = 'No errors found';
if ($retErrors != null) {
$errorMessage = '';
foreach ($retErrors as $arrError) {
$errorMessage .= "SQLState: ".$arrError['SQLSTATE']."<br>\n";
$errorMessage .= "Error Code: ".$arrError['code']."<br>\n";
$errorMessage .= "Message: ".$arrError['message']."<br>\n";
}
}
die ($errorMessage);
}
/* connect */
function connect() {
if (!function_exists('sqlsrv_num_rows')) { // Insure sqlsrv_1.1 is loaded.
die ('sqlsrv_1.1 is not available');
}
/* Log all Errors */
sqlsrv_configure("WarningsReturnAsErrors", TRUE); // BE SURE TO NOT ERROR ON A WARNING
sqlsrv_configure("LogSubsystems", SQLSRV_LOG_SYSTEM_ALL);
sqlsrv_configure("LogSeverity", SQLSRV_LOG_SEVERITY_ALL);
$conn = sqlsrv_connect('servername', array
(
'UID' => '',
'PWD' => '',
'Database' => 'databasename',
'CharacterSet' => 'UTF-8',
'MultipleActiveResultSets' => true,
'ConnectionPooling' => true,
'ReturnDatesAsStrings' => true,
));
if ($conn === FALSE) {
get_last_error();
}
return $conn;
}
function query($conn, $query) {
$result = sqlsrv_query($conn, $query);
if ($result === FALSE) {
get_last_error();
}
return $result;
}
/* Prepare a reusable query (prepare/execute) */
function prepare ( $conn, $query, $params ) {
$result = sqlsrv_prepare($conn, $query, $params);
if ($result === FALSE) {
get_last_error();
}
return $result;
}
/*
do the deed. once prepared, execute can be called multiple times
getting different values from the variable references.
*/
function execute ( $stmt ) {
$result = sqlsrv_execute($stmt);
if ($result === FALSE) {
get_last_error();
}
return $result;
}
function fetch_array($query) {
$result = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC);
if ($result === FALSE) {
get_last_error();
}
return $result;
}
$conn = connect();
/* prepare the statement */
$query = "INSERT TABLEName values ( ? , ? , ? , ?, ?, ?, ?, ?)";
$param1 = null; // this will hold col1 from the CSV
$param2 = null; // this will hold col2 from the CSV
$param3 = null; // this will hold col3 from the CSV
$param4 = null; // this will hold col4 from the CSV
$param5 = null; // this will hold col5 from the CSV
$param6 = null; // this will hold col6 from the CSV
$param7 = null; // this will hold col7 from the CSV
$param8 = null; // this will hold col8 from the CSV
$params = array( $param1, $param2, $param3, $param4, $param5, $param6, $param7, $param8 );
$prep = prepare ( $conn, $query, $params );
//$result = execute ( $prep );
//get the csv file
$file = $_FILES["csv"]["tmp_name"];
/*
Here is where you read in and parse your CSV file into an array.
That may get too large, so you would have to read smaller chunks of rows.
*/
$csv_array = file($file);
foreach ($csv_array as $row_num => $row) {
$row = trim ($row);
$column = explode ( ',' , $row );
$param1 = $column[0];
$param2 = $column[1];
$param3 = $column[2];
$param4 = $column[3];
$param5 = $column[4];
$param6 = $column[5];
$param7 = $column[6];
$param8 = $column[7];
// insert the row
$result = execute ( $prep );
}
/* Free statement and connection resources. */
sqlsrv_close($conn);
header( "Location: uploadcsv.php?success=1" );
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>CSV Upload</title>
</head>
<body>
<?php if (!empty($get_success)) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="uploadcsv" id="uploadcsv">
Upload a CSV file from your computer: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
<body>
</html>
CSV data file
sqlserver table

