简体   繁体   中英

Using php, html to upload a .csv file to phpmyadmin

Hi I have this code that I grabbed from going through this question https://www.sitepoint.com/community/t/how-to-upload-a-csv-file-using-php/6270/13 and I have modified it to suit my needs, but I have seemed to come across a problem that the person from the question did not come across

Here is my code

   <?php
$has_title_row = true;
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){
        $filename = basename($_FILES['csvfile']['name']);
        
        if(substr($filename, -3) == 'csv'){
            $tmpfile = $_FILES['csvfile']['tmp_name'];
            if (($fh = fopen($tmpfile, "r")) !== FALSE) {
                $i = 0;
                while (($items = fgetcsv($fh, 10000, ",")) !== FALSE) {
                    if($has_title_row === true && $i == 0){ // skip the first row if there is a tile row in CSV file
                        $i++;
                        continue;
                    }
                   // print_r($items);
                  //  $i++;
                }
            }
        }
        else{
            die('Invalid file format uploaded. Please upload CSV.');
        }
    }
    else{
        die('Please upload a CSV file.');
    }
}

//data
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mine_water_test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}


$has_title_row = true;
$not_done = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){
        $filename = basename($_FILES['csvfile']['name']);
        
        if(substr($filename, -3) == 'csv'){
            $tmpfile = $_FILES['csvfile']['tmp_name'];
            if (($fh = fopen($tmpfile, "r")) !== FALSE) {
                $i = 0;
                while (($items = fgetcsv($fh, 10000, ",")) !== FALSE) {
                    if($has_title_row === true && $i == 0){ // skip the first row if there is a tile row in CSV file
                        $i++;
                        continue;
                    }
                    //print_r($items);
                    //$sql = "INSERT into water_info_test (Id,Namems,Owner,Nearbyrc,Capacity,Specifications)
                   //values (?,?,?,?,?,?)";
                   $sql = "INSERT INTO water_info_test SET
                            Id='{$items[1]}', 
                            Namems='{$items[2]}', 
                            Owner='{$items[3]}', 
                            Nearbyrc='{$items[4]}', 
                            Capacity='{$items[5]}', 
                            Specifications='{$items[6]}'"; 
                            if (mysqli_query($conn, $sql)) {
            echo "New record created successfully";
            } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
            }
                    $i++;
                }
            }
            // if there are any not done records found:
            if(!empty($not_done)){
                echo "<strong>There are some records could not be inseted</strong><br />";
                print_r($not_done);
            }
        }
        else{
            die('Invalid file format uploaded. Please upload CSV.');
        }
    }
    else{
        die('Please upload a CSV file.');
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <meta name="author" content="Raju Gautam" />
    <title>Test</title>
</head>
<body>
    <form enctype="multipart/form-data" action="" method="post" id="add-courses"> 
        <table cellpadding="5" cellspacing="0" width="500" border="0"> 
            <tr> 
                <td class="width"><label for="image">Upload CSV file : </label></td> 
                <td><input type="hidden" name="MAX_FILE_SIZE" value="10000000" /><input type="file" name="csvfile" id="csvfile" value=""/></td> 
                <td><input type="submit" name="uploadCSV" value="Upload" /></td> 
            </tr> 
        </table> 
    </form>
</body>
</html>

it keeps coming up with these error messages

(: ) Notice: Undefined offset: 6 in C.\wamp64\www\2021DIG\test.php on line 67 Call Stack

Time Memory Function Location

1 0.0005 411136 {main}( )...\test.php:0 Error: INSERT INTO water_info_test SET Id='Black Water Mining', Namems='John Mcgee', Owner='Mackay', Nearbyrc='200L', Capacity='Farming', Specifications='' Incorrect integer value: 'Black Water Mining' for column 'Id' at row 1 (: ) Notice: Undefined offset: 6 in C.\wamp64\www\2021DIG\test.php on line 67 Call Stack

Time Memory Function Location

1 0.0005 411136 {main}( )...\test.php:0 Error: INSERT INTO water_info_test SET Id='Dysart Mining', Namems='Bob Brown', Owner='Emerald', Nearbyrc='210L', Capacity='Power generation', Specifications='' Incorrect integer value: 'Dysart Mining' for column 'Id' at row 1 (: ) Notice: Undefined offset: 6 in C.\wamp64\www\2021DIG\test.php on line 67 Call Stack

Time Memory Function Location

1 0.0005 411136 {main}( )...\test.php:0 Error: INSERT INTO water_info_test SET Id='Emerald Mining', Namems='Kert Dolanld', Owner='Rockamption', Nearbyrc='160L', Capacity='Power generation', Specifications='' Incorrect integer value: 'Emerald Mining' for column 'Id' at row 1

here is the image if image is clearer error messages

The test data that I am using is

| Id | Namems | Owner | Nearbyrc | Capacity | Specifications |

| 4 | Black Water Mining | John Mcgee | Mackay | 200L | Farming |

| 5 | Dysart Mining | Bob Brown | Emerald | 210L | Power generation |

| 6 | Emerald Mining | Kert Donanld | Rockampton | 160L | Power generation |

If you can help, that would be great, grade 12 is already hard enough without having to do complex coding.

The answer was "You are using $items[1] for the ID, arrays start at 0 so this should be $items[0]. You should adjust all of the other indexes as well."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM