i need to join those two peice of code the first peice of code takes a csv file from a textarea formats it and put it into a mutidimentional array

<?php
if(isset($_POST['TextArea1'])){
    $str = $_POST['TextArea1'];
$patterns = array("/\t+/", "/ +/"); //set up an array of items to replace
  $str = preg_replace($patterns, ' ', $str);
    $lines = explode("\n", $str);
    $parsedArray = array();
    foreach ($lines as $line) {
        $parsedArray[] = str_getcsv($line, ' ', '"', '\\');
    }
    echo "<pre>";
    print_r($parsedArray);
    echo "</pre>";
}
?>
<form method="post" >
 <textarea name="TextArea1" id="TextArea1" rows="10" cols="50"></textarea>
<input type="submit" value="Parse" name="submit" />
</form>

now i need to insert the data into my database for this i have this peice of code

$array = csv_array(); // this is  array from csv

$id = $array[0][0];
$Name = $array[0][1];
$Position = $array[0][2];
$Reference = $array[0][3];
$cityguards = $array[0][4];
$ballistas = $array[0][5];
$rangers = $array[0][6];
$guardians = $array[0][7];
$templars = $array[0][8];
$berserkers = $array[0][9];
$mages = $array[0][10];
$scouts = $array[0][11];
$crossbowmen = $array[0][12];
$paladins = $array[0][13];
$knights = $array[0][14];
$warlocks = $array[0][15];
$rams = $array[0][16];
$catapults = $array[0][17];
$frigates = $array[0][18];
$sloops = $array[0][19];
$wargalleons = $array[0][20];
$barons = $array[0][21];
$total = $array[0][22];
$total1 = $array[0][23];
$host = 'localhost';
$user = 'xxxxxx';
$pass = 'xxxxxxxx';
$db = 'xxxxxx';



for($i = 1; $i < count($array); $i++){
    //this is where  sql goes
   // connect to database 
$link = mysql_connect ($host,$user,$pass) or die ('Erreur : '.mysql_error() ) ;
mysql_select_db($db) or die ('Erreur :'.mysql_error()) ;

    $sql = "INSERT INTO military($id, $Name,  $Position, $Reference, $cityguards, $ballistas, $rangers, $guardians, $templars, $berserkers, $mages, $scouts, $crossbowmen, $paladins, $knights, $warlocks, $rams, $catapults, $frigates, $sloops, $wargalleons, $barons, $total, $total1 ) 
    VALUES($array[$i][0], $array[$i][1], $array[$i][2], $array[$i][3], $array[$i][4], $array[$i][5], $array[$i][6], $array[$i][7], $array[$i][8], $array[$i][9], $array[$i][10], $array[$i][11], $array[$i][12], $array[$i][13], $array[$i][14], $array[$i][15], $array[$i][16], $array[$i][17], $array[$i][18], $array[$i][19], $array[$i][20], $array[$i][21], $array[$i][22], $array[$i][23],)";


    $db->mysql_query($sql,$link);

my question is can i do this $array = $parsedArray(); and put the second part of the code inside the loop of the first code replacing the print_r ?

ty

jethaya

Recommended Answers

All 39 Replies

I am not sure if I understood your problem correctly but there are some thoughts:

  1. Put the mysql_connect and mysql_select_db outside the loop, somewhere on the beginning; it is preferred to execute this code only once
  2. check for the existence of each $array element, since the data comes from textarea and is not quaranted that it will exist; use isset function: if(isset($array[0][0])) {$id = $array[0][0];} else {// set default value}
  3. use foreach loop to iterate through $array, it is more handy (but not necessary, really)
  4. construct one query that inserts multiple values (begin the query before the loop, add values within the loop, execute the query after the loop)
  5. switch to safer mysqli extension ASAP

Here is how to construct the query (see the comments):

// begin the query
$sql = "INSERT INTO military (";

// add DB field names (assumming they are an array in the first element of the $array)
for($i = 0; $i < count($array[0]); $i++) {
    $sql .= "`{$array[0][$i]}`";
    // if it is not the last field, add comma
    // if it is the last field, add parentheses
    $sql .= $i < (count($array[0]) - 1) ? ', ' : ') ';
}
// add the VALUES part
$sql .= 'VALUES ';

// add the values from the $array
for($i = 1; $i < count($array); $i++) {
    // each element of $array is also an array so loop through it
    for($j = 0; $j < count($array[$i]); $j++) {
        // check for the existence of the element
        if(isset($array[$i][$j])) {
            // DO NOT FORGET to escape the data
            $current = mysql_real_escape_string($array[$i][$j]);
        } else {
            // e.g. provide some default value
            $current = '';
        }
        // if first element of inner array, add starting parenthesis
        // if not first and not last element of inner array, add comma
        // if last element of inner array, add ending parenthesis
        if($j == 0) { 
            $sql .= '('; 
        }
        elseif($j > 0 && $j < (count($array[$i]) - 1) ) {
            $sql .= "'$current', ";
        }
        else {
            $sql .= "'$current')";
        }
    }
    // if not the last element of the $array array add coma between the set of values
    $sql .= $i < (count($array) - 1) ? ', ' : '';
}

// just for debugging:
// echo the query and stop the script for testing (comment that out when it works OK)
die($sql);

The code looks complex but it is not if you study it line by line :-)

ok i see i was not clear in my explanation i am sorry
the table in the database is already defined all the feilds etc
the user copy paste a csv file he gets from a ''game tool'' into the text area.
that file contains the values of the feilds (always the same 23 feilds) the only thing i dont know is how many lines there will be
the first part of my code is needed to ''format the data''
the csv file is tab delimited and has some extra spaces in a few places that need to be removed

i think what i need to do is a mix of the 2 sections read the first line format it
load it in the database go to second line format it load it etc up to the last line
ty for your input you gave me a lot to think about (in game term ''i am a noob ''when it comes to coding)

You actually do not have to mix the two code snippets. The first part is OK, it formats the data from the textarea and puts it in a two-dimesional array. In the second part of the code I suggested you just loop through the array of data and construct a multiple insert statement which you then send to the database in one go. Just replace the second part of your code with my code (and add the database connection code on the beginning) and it should work. The query you will get is something like:

INSERT INTO  military (`field1`, `field2`, `field3`, `field4`) VALUES
('value11', 'value12', 'value13', 'value14'),
('value21', 'value22', 'value23', 'value24'),
('value31', 'value32', 'value33', 'value34')

which is one long query but it get sent to the database only once.

ok i reworked the code here is what i got so far

<?php


if(isset($_POST['TextArea1'])){
 $db = mysql_connect('localhost', 'xxxxxxx', 'xxxxxxx');  // connect to DB
     mysql_select_db('xxxxxxx',$db);                  // select db
    $str = $_POST['TextArea1'];
$patterns = array("/\t+/", "/ +/"); //set up an array of items to replace
  $str = preg_replace($patterns, ' ', $str);
    $lines = explode("\n", $str);
    $parsedArray = array();
    foreach ($lines as $line) {
        $parsedArray[] = str_getcsv($line, ' ', '"', '\\');
 $sql = "INSERT INTO military(id, Name, Position, Reference, cityguards, ballistas, rangers, guardians, templars, berserkers, mages, scouts, crossbowmen, paladins, knights, warlocks, rams, catapults, frigates, sloops, wargalleons, barons, total, total1 ) 
    VALUES( $parsedArray[0], $parsedArray[1], $parsedArray[2], $parsedArray[3], $parsedArray[4], $parsedArray[5], $parsedArray[6], $parsedArray[7], $parsedArray[8], $parsedArray[9], $parsedArray[10], $parsedArray[11], $parsedArray[12], $parsedArray[13], $parsedArray[14], $parsedArray[15], $parsedArray[16], $parsedArray[17], $parsedArray[18], $parsedArray[19], $parsedArray[20], $parsedArray[21], $parsedArray[22], $parsedArray[23])";
    mysql_query($sql) or die('Erreur SQL !'.$sql.'<br>'.mysql_error()); 
    }
    echo !!!sucess!!!!
}
?>
<form method="post" >
 <textarea name="TextArea1" id="TextArea1" rows="10" cols="50"></textarea>
<input type="submit" value="Parse" name="submit" />
</form>

server is down for a few hours cant test this :( do you think i am on the right track ?
jethaya

This should work if there are no glitches in the code. But you are sending a lot of insert statements to the DB server, which is not a critical issue but these days you try to avoid too many consecutive calls to the DB if you can do it in one call. It is up to you, though. Let us know how it works once the server is up and running.

It would be a good idea to at least escape the values so you do not expose the server to SQL injection attack.

BTW: do you not have a local environment for testing?

i get this error message
Erreur SQL !INSERT INTO military(id, Name, Position, Reference, cityguards, ballistas, rangers, guardians, templars, berserkers, mages, scouts, crossbowmen, paladins, knights, warlocks, rams, catapults, frigates, sloops, wargalleons, barons, total, total1 ) VALUES( Array, , , , , , , , , , , , , , , , , , , , , , , )
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , , , , , , , , , , , , , , , , , , , , )' at line 2

i must say i have no idea is it the bracket it doesnt like should i use ( and ) instead?
also i would like to send it all at once but i am afraid i dont understand how to do it
its not your explication its just my thick head
those loop make me feel like i am the guy in the movie 13th floor..
i will look into getting a local environement would be useful

ty

Jethaya

BroJ i think i finaly understand what you mean just one detail tho when you put field1 in your code
should i replace it by the name of that feild in my DB ?or will the value be putted in the first feild regardless of the name i gave it in the db? for the values i am not sure how to proceed because the number of lines is always differents

Yes, the example I gave is just a generalized way of doing it. I presume you have field names in the $array[0], which is an array holding one row. So the following code extracts the field names for the first part of the query:

// add DB field names (assumming they are an array in the first element of the $array)
for($i = 0; $i < count($array[0]); $i++) {
    $sql .= "`{$array[0][$i]}`";
    // if it is not the last field, add comma
    // if it is the last field, add parentheses
    $sql .= $i < (count($array[0]) - 1) ? ', ' : ') ';
}

then you add the real values of the rows. Each row of values is within parentheses and separated by comma. The generalized example shows that. In reality your query should look like:

INSERT INTO military (`id`, `Name`, `Position`, ... etc ...) VALUES
('some value 1', 'some value 2', ... etc ...),
('some value 3', 'some value 4', ... etc ...),
('some value 5', 'some value 5', ... etc ...)

But I do not know the values so I am making them up.

sorry i am even more lost now like i said before i do not have the feild name at all in the array
all i have is the values 23 values per line no clue how many lines
my real probleme is i was thinking the value to insert into each feild was contained in
$parsedArray[number of feild here] but when i ran my code i got an error message i dont understand
my guess is i am not using the right variable but i am not sure

What is the error message?

Erreur SQL !INSERT INTO military(id, Name, Position, Reference, cityguards, ballistas, rangers, guardians, templars, berserkers, mages, scouts, crossbowmen, paladins, knights, warlocks, rams, catapults, frigates, sloops, wargalleons, barons, total, total1 ) VALUES( Array, , , , , , , , , , , , , , , , , , , , , , , )
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , , , , , , , , , , , , , , , , , , , , )' at line 2

I think you variable for the values needs to be in single quotes

$parsedArray[20]

Should be:

'$parsedArray[20]'

ty ill try this

when i try this it like this VALUES('.$parsedArray[0]', '.$parsedArray[1]',
i get this error message

Erreur SQL !INSERT INTO military(id, Name, Position, Reference, cityguards, ballistas, rangers, guardians, templars, berserkers, mages, scouts, crossbowmen, paladins, knights, warlocks, rams, catapults, frigates, sloops, wargalleons, barons, total, total1 ) VALUES('.Array', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.')
Duplicate entry '.Array' for key 'PRIMARY'

my primary key isnt the word array or an array its a series of number like this "15204609" i also tried it with out the period in front of the variable almost same error message

Please post the content of the $array. Put this code on the beginning after if(isset($_POST['TextArea1'])){:

    // put this debug line here
    die(print_r($array, 1));

and post here the output.

when i put your line of code right at the biggining i get a blank page now using your debug line and replacing the variable i was able to figure out its the coding i added to load the data in the DB that is wrong if i remove that part and use the following code

<?php

if(isset($_POST['TextArea1'])){

 $db = mysql_connect('localhost', '651075', '2cold4you');  // connexion à la base
     mysql_select_db('651075',$db);                  // sélection de la base 
    $str = $_POST['TextArea1'];
$patterns = array("/\t+/", "/ +/"); //set up an array of items to replace
  $str = preg_replace($patterns, ' ', $str);
    $lines = explode("\n", $str);

    $parsedArray = array();

    foreach ($lines as $line) {

        $parsedArray[] = str_getcsv($line, ' ', '"', '\\');


    }
     echo "<pre>";
    print_r($parsedArray);
    echo "</pre>";
}
?>
<form method="post" >
 <textarea name="TextArea1" id="TextArea1" rows="10" cols="50"></textarea>
<input type="submit" value="Parse" name="submit" />
</form>

i get this result

Array
(
    [0] => Array
        (
            [0] => 15204609
            [1] => City of Jethaya
            [2] => '257:232
            [3] => 
            [4] => 0
            [5] => 0
            [6] => 0
            [7] => 0
            [8] => 0
            [9] => 623
            [10] => 0
            [11] => 0
            [12] => 0
            [13] => 0
            [14] => 0
            [15] => 0
            [16] => 0
            [17] => 0
            [18] => 0
            [19] => 0
            [20] => 0
            [21] => 0
            [22] => 623
            [23] => 623 berserkers
        )

    [1] => Array
        (
            [0] => Total
            [1] => Total
            [2] => '
            [3] => 
            [4] => 0
            [5] => 0
            [6] => 0
            [7] => 0
            [8] => 0
            [9] => 623
            [10] => 0
            [11] => 0
            [12] => 0
            [13] => 0
            [14] => 0
            [15] => 0
            [16] => 0
            [17] => 0
            [18] => 0
            [19] => 0
            [20] => 0
            [21] => 0
            [22] => 623
            [23] => 623 berserkers
        )

what i need to understand is how to get each set of those 24 result (0-23 incl.) into a row in the table of the database
now this exemple had only one city in it.(each city is a row in the table military)
so i get two set of result , the second array the one starting with the total feild is always at the end
but depending on the user the number of cities will change so ill get multiples arrays
each of those array is a row with 24 feilds or col. in my table

now i was assuming that the first time i go into the loop $parsedArray[0] would contain the id of the city ([0] => 15204609) ent contain [0] => Total the last time it went into the loop but i was wrong

Jeth

Sorry, but I am not sure if I understood your questions. Hope the following helps.

what i need to understand is how to get each set of those 24 result (0-23 incl.) into a row in the table of the database

If you are really sure that each set of results will contain 24 elements then you can just loop through them. But you have to have two loops: outer loop will loop through rows (which are arrays as I understand) and inner loop will loop through the elements of each row (which are field values as I understand). This concept has been shown in my above post. Here is the code again but with indexes for both loops changed to $row and $field so you know where you are and with omitted field names in the query

// begin the query (I will omit the field names sice you say they are always 24 values)
$sql = "INSERT INTO military ";

// outer loop iterates through rows
// the max condition is $row < (count($parsedArray) - 1) which omits the list row (which is total, right?)
for($row = 0; $row < (count($parsedArray) - 1); $row++) {

    // inner loop iterates through 24 field values
    for($field = 0; $field < count($parsedArray[$row]); $field++) {

        // read the current value (this is just for clarity)
        $current = mysql_real_escape_string($parsedArray[$row][$field]);

        // if first element of inner array, add starting parenthesis
        // if not first and not last element of inner array, add comma
        // if last element of inner array, add ending parenthesis
        if($field == 0) {
            $sql .= '(';
        }
        elseif($field > 0 && $field < (count($parsedArray[$row]) - 1) ) {
            $sql .= "'$current', ";
        }
        else {
            $sql .= "'$current')";
        }
    }

    // if not the last iteration of the loop add coma between the set of values
    $sql .= $i < (count($parsedArray) - 2) ? ', ' : '';
}

ok when i use this code i get no error message but nothing goes into the database it stays empty

<?php


if(isset($_POST['TextArea1'])){
 $db = mysql_connect('localhost', 'xxxxxxx', 'xxxxxxxx');  // connexion à la base
     mysql_select_db('xxxxxxx',$db);                  // sélection de la base 
    $str = $_POST['TextArea1'];
$patterns = array("/\t+/", "/ +/"); //set up an array of items to replace
  $str = preg_replace($patterns, ' ', $str);
    $lines = explode("\n", $str);
    $parsedArray = array();
    foreach ($lines as $line) {
        $parsedArray[] = str_getcsv($line, ' ', '"', '\\');
 // begin the query (I will omit the field names sice you say they are always 24 values)
$sql = "INSERT INTO military ";
// outer loop iterates through rows
// the max condition is $row < (count($parsedArray) - 1) which omits the list row (which is total, right?)
for($row = 0; $row < (count($parsedArray) - 1); $row++) {
    // inner loop iterates through 24 field values
    for($field = 0; $field < count($parsedArray[$row]); $field++) {
        // read the current value (this is just for clarity)
        $current = mysql_real_escape_string($parsedArray[$row][$field]);
        // if first element of inner array, add starting parenthesis
        // if not first and not last element of inner array, add comma
        // if last element of inner array, add ending parenthesis
        if($field == 0) {
            $sql .= '(';
        }
        elseif($field > 0 && $field < (count($parsedArray[$row]) - 1) ) {
            $sql .= "'$current', ";
        }
        else {
            $sql .= "'$current')";
        }
    }
    // if not the last iteration of the loop add coma between the set of values
    $sql .= $i < (count($parsedArray) - 2) ? ', ' : '';
}
    }
  echo 'salut';
 }
?>
<form method="post" >
 <textarea name="TextArea1" id="TextArea1" rows="10" cols="50"></textarea>
<input type="submit" value="Parse" name="submit" />
</form>

did i forget something ?

not sure but after a insert into Military should it be a Value?

OOps. Yes the VALUES keyword is missing, sorry. Change line 15 to

$sql = "INSERT INTO military VALUES ";

it doesnt work the table is empty wish i understood why :)

Member Avatar for diafol

I'd rewind a bit and do some checking. You should count each array to see if they contain 24 items, also to see if they contain the right datatype ("0" can be checked with is_numeric(), for example). Also all input to DB should be cleaned with array_map() and mysql_real_escape_string() if you're going to use mysql - NOT RECOMMENDED - as broj says, use mysqli (or even PDO).

If all is OK, you can build a function to build your query:

function buildValues($data){
    return "('" . implode("', '", $data) . "')";
}

$records = array();

foreach($array as $d){
    $records[] = buildValues($d);
}

$recs = implode(",",$records);

$SQL = "INSERT INTO table (...) VALUES $recs";

it doesnt work the table is empty wish i understood why :)

There can be many reasons. Please do echo the created query whichever method you are using to create it. Put the following debug code just before the echo 'salut'; (after line 39):

die($sql);

and post the output here (and of course test it in phpmyadmin).

when i add the line you said i get this result i get on the page but the table in the database stays empty

INSERT INTO military ('City of Jethaya', '\'257:232', '', '0', '0', '0', '0', '0', '609', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '609', '609 berserkers')

i am missing the first data wich is ''ID'' its a number i store in a varchar 10 in the db

the data i putted in the textArea was

"15204609"  "City of Jethaya"   "'257:232"  ""  "0" "0" "0" "0" "0" "609"   "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "609"   "609 berserkers"
"Total" "Total" "'" ""  "0" "0" "0" "0" "0" "609"   "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "609"   "609 berserkers"

loosing the total line is perfect but the "15204609" is needed
this is really close

jethaya

This is due to my error, sory. Change line 27 in my code to:

$sql .= '($current, ';

Sory for that, :-).

now i get this result
INSERT INTO military Value ($current, 'City of Jethaya', '\'257:232', '', '0', '0', '0', '0', '0', '609', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '609', '609 berserkers')

still nothing in the table i will conduct some test to make sure i can write in it
jeth

i tried to add this line mysql_query($sql) or die('Erreur SQL !'.$sql.'<br>'.mysql_error());

to see and i got

Erreur SQL ! INSERT INTO military VALUES ($current, 'City of Jethaya', '\'257:232', '', '0', '0', '0', '0', '0', '609', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '609', '609 berserkers')

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

my test on the database where positive i can write in the table military

ok i found out one of the problems my 4th data is usually empty so i had to change the table to accept a null
but i still get this error
Erreur SQL ! INSERT INTO military VALUES ($current, 'City of Jethaya', '\'257:232', '', '0', '0', '0', '0', '0', '601', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '601', '601 berserkers') Unknown column '$current' in 'field list'
and i think it comes from $sql .= '($current, '; instead of $current i should get '15204609'

jeth

try '$current'

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.