1

Scenario:

I am exporting a table Named "Registration" from access database and writing into a file named "isl.txt" in php using pdo. Fields separated by "," and Records separated by "\\"(i know it should be "\n" for convenience but it cant take a new line in text file. Don't know why !! so i have chosen "\\")

Registration Table in Access:

Roll_Num,Course,Marks,Discipline,Session

0,CS-101,89,CS,Fall94

0,CS-102,70,CS,Fall94

0,CS-103,59,CS,Fall94

Code:

$fl = fopen('isl.txt', 'w');
$db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=D:\Islamabad.mdb;Uid=;Pwd=;");
$results = $db->query("select * from `Registration`");

while ($row = $results->fetch()) {

foreach ($row as $value) {
   $lastv = end($row);

    if ($value != $lastv){

        fwrite($fl, $value.",");
        }

}
 fwrite($fl, $value."\\");
}
 fclose($fl);

Output:

0,0,CS-101,CS-101,89,89,CS,CS,Fall94\0,0,CS-102,CS-102,70,70,CS,CS,Fall94\0,0,CS-103,CS-103,59,59,CS,CS,Fall94

Problem:

As u see, every single value of record is repeating two times. Please Check whats wrong with my code!!

1 Answer 1

2

The repeating values are because you are not specifying a fetch_style in $results->fetch([fetch_style]). According to the manual - http://php.net/manual/en/pdostatement.fetch.php - when fetch_style is not specified, it defaults to value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to PDO::FETCH_BOTH).

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

Try changing to -

while ($row = $results->fetch(PDO::FETCH_ASSOC)) {

OR

while ($row = $results->fetch(PDO::FETCH_NUM)) {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.