简体   繁体   中英

How can i use the output of a php page to import data on a database?

I have an exercise where i've been given a link where there's data stored on a.csv file.

Now:

  1. My php page (using fgetcsv) already parses for the csv fields from the link so i have an identical page but in html
  2. I already created a database with the same identical structure so i can import my data

I couldn't find anything useful around.. my questions are:

  1. How can i proceed to import the data from the output i have on my php page?
  2. Is what i'm trying to do actually a good way to solve this case?

Thanks in advance

@RiggsFolly
The code i use that parses and displays the data i need is:
UPDATED CODE:

$servername = "localhost";
$username = "user";
$password = "psw";

$conn = mysqli_connect("localhost","user" ,"psw","dbname");

if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
    echo "you did it";
}
$row = 1;
if (($handle = fopen("givenurl.csv", "r")) !== FALSE) {
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $num = count($data);
    $row++;
    for ($c=0; $c < $num; $c++) { 
$sql = "INSERT INTO tablename($columns) VALUES ($data[$c])";
    }
  }
  fclose($handle);
}

I'm actually wondering how to make the matching between the arrays i got parsing the csv and the columns i have on the database

I'll give an example of the arrays i get: [0] name; surname; email; [1] john; cleon; johncleon@gmail.com;

(The first array matches the database structure)

ps maybe i got something wrong and i should declare the columns with the

If you're already parsing the the CSV using fgetcsv to display it in HTML then you just need to write the CSV data (from the array that fgetcsv gives you) to your database table (many examples around if you just need help writing the array to mysql).

I'd suggest if you're going to store to a local database, you would be better then retrieving the data from your database to display on your page - rather than relying on the external linked CSV file.

If the CSV data changes regularly you'll need to think about how to handle those changes in terms of either updating your local database (assuming there's a unique ID in the CSV you can use to identify the right row in your table to update), or drop the existing data and replace at intervals. This could be done to a schedule (cron job perhaps) or perhaps a manual import script you run when you're aware the data has been changed.

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