Undefined offset: 2 [PHP]

Solved
Thibaut -  
 Thibaut -
Hello,
I’m making a script to import CSV content into a database.
When I display my variable $getData everything is perfect I have:

Array
(
[0] -> 1st data
[1] -> 2nd data
[2] -> 3rd data
)

But when I want to run my query, I get errors Undefined offset: 1 and Undefined offset: 2.
Nevertheless, some data pass (my 13th line in the csv for example passes NiQU and 2-3 others, but the rest error)

Here is my code:



$file = fopen('test2.csv', "r");
while (($getData = fgetcsv($file, 0 , ";")) !== FALSE)
{

$sql = "INSERT into matable (colone1,colone2,colone3,colone4,colone5)
values ('".$i."','".$y."','".$getData[0]."','".$getData[1]."','".$getData[2]."')";
$result = mysqli_query($con, $sql);
}
fclose($file);



For precision in my query:
$i=1 and $y=2
$getData[0] is a title
$getData[1] is a description (very long for most lines)
$getData[2] another title

The database I want to insert into is one from a Prestashop managed by phpMyAdmin.

Could someone guide me on the origin of the problem ?

Thanks in advance.

Configuration: Windows / Chrome 97.0.4692.99

4 answers

jordane45 Posted messages 30426 Registration date   Status Moderator Last intervention   4 830
 
Hello
You certainly have line breaks in your CSV (in the comments)
Which distorts the CSV reading in your loop.

--
.
Best regards,
Jordane
1
Thibaut
 
If that were the case, wouldn’t line breaks distort readability when I do a print_r of my $getData variable? Because in this instance, when I display it, everything looks fine...

I saw that you could escape certain characters in fgetcsv,
Do you think it’s possible to escape line breaks to run a test?
0
jordane45 Posted messages 30426 Registration date   Status Moderator Last intervention   4 830
 
There are different types of newline characters... \n \r\n ... which are “invisible” characters and are not interpreted by HTML ... and therefore by print_r
0
Thibaut
 
I added:


$order = array("\r\n", "\n", "\r");
$replace = '<br />';
$newstr = str_replace($order, $replace, $getData[1]);


9 requests out of 96 are passing fine, but the others still refuse....
0
jordane45 Posted messages 30426 Registration date   Status Moderator Last intervention   4 830
 
It isn’t when you read the getData that you should do it … but BEFORE reading the CSV. In short, you need to open the CSV (from your PHP script of course) 1- replace the \r\n with another character (for example µ) 2- then replace the \n with a space 3- replace µ with \r\n Thus you preserve the end-of-line breaks .. but you remove those that would be inside the fields of your CSV.. And once that’s done, you can then use your current script to parse the CSV correctly.
0
Thibaut
 
Thank you for your help I finally managed what you told me plus replace the quotes I had forgotten and everything worked
0