Basically I've made an string out of pdf
file, and that string contains comma-separated values which I now need to insert into different columns in table. I would try similar question's answer here, but I don't get it for my need.
I already tried exploding that string into an array, so that comma is each element separator like so:
$array = explode(',', $text);
But since I have just 3 columns into table, I need to sort that values into those columns, so that each third string would go into first column and all following it into following columns. I tried doing it like so:
$duzina=count($array);
for($i=0;$i<$duzina;$i++) {
if ($i = 0 && $i < 3) {
$mysqli->query("INSERT INTO `test` (`name`, `surname`, `email`) VALUES
(
'" . trim($array[$i]) . "',
'" . addslashes($array[$i + 1]) . "',
'" . addslashes($array[$i + 2]) . "'
)
");
}
if ($i/3 == 0) {// has found a 3rd,6th,9th element of an $array
$mysqli->query("INSERT INTO `test` (`name`, `surname`, `email`) VALUES
(
'" . trim($array[$i]) . "',
'" . addslashes($array[$i + 1]) . "',
'" . addslashes($array[$i + 2]) . "'
)
");
} else {
$mysqli->query("INSERT INTO `test` (`name`, `surname`, `email`) VALUES
(
'" . trim($array[$i]) . "',
'" . addslashes($array[$i + 1]) . "',
'" . addslashes($array[$i + 2]) . "'
)
");
}
But all it does is inserting first 3 elements of $array
. Please help
Use prepared statements.
Restructure your data to be meaningful in code(useful for debugging)
Loop wisely(increment by 3)
Note, code below is not fieldtested, just proof of concept.
$array = loadpdfwhatever();
$length = count($array);
// Restructure the raw data to be meaningful to a human. Can be skipped,
// but this will help you debugging in + 3 weeks from now :-)
$restructured = [];
for($i=0;$i<$length;$i+=3) { // note the $i+3 to increment by 3.
$restructured[] = ['name'=> $array[$i],
'surname'=> $array[$i+1],
'email'=> $array[$i+2]];
}
// Using prepared statements we only have to build up the query once.
// Makes code faster and more efficient.
if ($stmt = mysqli_prepare($link, "INSERT INTO `test` (`name`, `surname`, `email`) VALUES ( ?, ?, ? ) ")) {
foreach($restructured as $insert) {
mysqli_stmt_bind_param($stmt,'sss',$insert['name'],
$insert['surname'],
$insert['email']);
mysqli_stmt_execute($stmt)
}
}
no the rest of division get by %
not /
, so replace this:
if ($i/3 == 0) {
with
if ($i%3 == 0) {
2 things :
first use if / elseif /else
if ($i = 0 && $i < 3) {
...
}
elseif ($i%3 == 0) {
...
}
else
{
....
}
Second :
its $i%3 == 0
and not $i/ 3 == 0