I have been asked to do in PHP a script that automatically inserts values from a csv to the database, but although I have some idea of PHP (little thing, I'm learning on the fly) I have no idea of MySQL.
The script works fine, but the responses have a id_pregunta
field that remains at 0 after importing them from the csv. So my question is:
How can I extract the id from the table questions and give it to the 4 answers inserted in the table?
I mean that the last 4 answers have the same id_pregunta
.
At the moment I have this:
<?php
//conexiones, conexiones everywhere
ini_set('display_errors', 1);
error_reporting(E_ALL);
$db_host = 'localhost';
$db_user = '**';
$db_pass = '**';
$database = '**';
if (!@mysql_connect($db_host, $db_user, $db_pass))
die("No se pudo establecer conexión a la base de datos");
if (!@mysql_select_db($database))
die("base de datos no existe");
if(isset($_POST['submit']))
{
//Aquí es donde seleccionamos nuestro csv
$fname = $_FILES['sel_file']['name'];
echo 'Cargando nombre del archivo: '.$fname.' <br>';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "csv")
{
//si es correcto, entonces damos permisos de lectura para subir
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename, "r");
$data = fgetcsv($handle, 1000, ",");
$sql1 = "INSERT into preguntas(pregunta, pregunta_asturiano, juego, dificultad, url_imagen, url_video) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($sql1) or die('Error: '.mysql_error());
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$sql2 = "INSERT into respuestas(respuesta, respuesta_asturiano, correcta) values('$data[0]','$data[1]','$data[2]','$data[3]')";
mysql_query($sql2) or die('Error: '.mysql_error());
}
}
else
{
//si aparece esto es posible que el archivo no tenga el formato adecuado, inclusive cuando es cvs, revisarlo para
//ver si esta separado por " , "
echo "Archivo invalido!";
}
}
?>