Writing a PHP file to read from CSV and execute SQL Query

前端 未结 6 1719
深忆病人
深忆病人 2020-12-30 12:39

I would like a PHP script to read the contents from a CSV file in the following format

id, sku
1,104101
2,105213

there are a total of 1486

相关标签:
6条回答
  • 2020-12-30 12:39

    fgetcsv can be used to parse CSV files. mysql_query method could be used to perform MySQL queries.

    The complete code is as follows:

    <?php
    $fin = fopen('catalog_product_entity.csv','r') or die('cant open file');
    $link = mysql_connect('localhost', 'm118', 'pw');
    If (!$link) {
        die ('Could not connect: ' . mysql_error());
    }
    @mysql_select_db('m118') or die ('Unable to select database');
    echo "Connection succeeded <br />\n";
    while (($data=fgetcsv($fin,1000,","))!==FALSE) {
        $query = "UPDATE catalog_product_entity SET sku='$data[1]' WHERE entity_id='$data[0]'";
        mysql_query($query);
        echo "Record updated <br />\n";
        }
    fclose($fin);
    mysql_close();
    ?>
    
    0 讨论(0)
  • 2020-12-30 12:40

    Ok man, I wont write the code for you because you wont learn if I do. But I will point you in the right direction. Check out this link http://us.php.net/fgetcsv for information on parsing a CSV file in PHP. A simple google search should also give you the necessary information on entering it into a MySQL table.

    0 讨论(0)
  • 2020-12-30 12:54

    Goblyn27 is correct. Take a look at fgetcsv() and mysql_query() on php.net. There are even examples in the docs for how to do this.

    0 讨论(0)
  • 2020-12-30 12:58

    Well done on learning :)

    You should perhaps now learn about PDO in PHP, as it's (in my opinion) the best, safest and fastest way to execute MySQL queries in PHP:

    <?php
    $fin = fopen('catalog_product_entity.csv','r') or die('cant open file');
    try {
        $link = new PDO('mysql:dbname=m118;host=localhost', 'm118', 'pw');
        echo 'Connection succeeded <br />' . PHP_EOL;
        $stmt = $db->prepare('UPDATE catalog_product_entity SET sku = :sku WHERE entity_id = :id');
        //Only give the length parameter if you **KNOW** that no line will be longer than that
        while (($data=fgetcsv($fin,1000,","))!==FALSE) {
            if ($stmt->execute(array(':sku' => $data[1], ':id' => $data[0]))) {
                echo 'Record updated <br />' . PHP_EOL;
            } else {
                $err = $stmt->errorInfo();
                echo 'Update Failed: ' . $err[2] . PHP_EOL;
            }
        }
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    fclose($fin);
    

    The PDO script has the following advantages over yours:

    • It's safer: PDO automatically quotes the data being inserted as needed. This prevents SQL injection attacks.
    • It's faster: PDO caches the query (in the prepare), and then uses the parameters passed in execute.
    • It's portable: PDO can connect to various types DB's, not just MySQL, so if you need to switchs DB's, its much easier.
    0 讨论(0)
  • 2020-12-30 13:04
    <?php
    include ("dbsanjog.php");
    $uploadedfile=$_REQUEST['uploadedfile'];
      $target_path = "dataupload/";
      $user=$_REQUEST['username'];
    $target_path = $target_path.$user.".csv"; 
    
    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
    {
        echo "The file ".  basename( $_FILES['uploadedfile']['name']). "has been uploaded";
    } 
    
    //echo $target_path; die;
    //$row = 1;
    $handle = fopen($target_path, 'r');
    //$sql="update agents_det set where user='$user'";
    
    
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
    {
        $query = "UPDATE agents_det SET contact='$data[3]' WHERE user='$user'";   
    
    }
    
    fclose($handle);
    //mysql_query($test);
    //echo ($test[1]); die;
    //echo $test; die;
    
    
    ?>
    
    0 讨论(0)
  • 2020-12-30 13:05

    You will need to do something like:

    $filename = "file_name_on_server.csv"
    $fp = fopen( $filename ,"r");
    while ($line = fgets ($fp))
    {
    

    now use Split to get an array of the comma delimited values

        $arr = split (",", $line);
    

    Now you have an array for the comma delimited values on $line. You can do simple string formatting to stick those values into an SQL query.

        $query = "INSERT INTO `TableBlah` (Field1, Field2) VALUES (" . $arr[0] . "," . $arr[1] . ")";
    

    Use the mysql api to send those queries to the database

    }
    fclose($fp);
    
    0 讨论(0)
提交回复
热议问题