Hello Everyone..!!

I am beginner at PHP. I would like to have solution for "\n" in textfile php.

$file = "testFile.txt";
$fh = fopen($file, 'a+') or die("can't open file");
$firstname = $_POST["prenom"];
$lastname = $_POST["nom"];
$mood = $_POST["humeur"];
$datestring = date("d/m/y ");
$timestring = date("H.i.s");
$data = "$firstname ; $lastname ; $mood ; $datestring : $timestring "\n" ";
fwrite($fh, $data);
fclose($fh);


Actual Result:
testprenom ; testnom ; bonne ; 19/10/12  : 11.09.23
;  ;  ; 19/10/12  : 11.09.25

Expected Result:
testprenom ; testnom ; bonne ; 19/10/12  : 11.09.23

Thanks a lot for your time in advanced.

$data = "$firstname ; $lastname ; $mood ; $datestring : $timestring\r\n";

Thanks a lot for reply but it seems it write twice the line.
Still i am getting this result:

terst56 ; test ; bonne ; 19/10/12 : 13.27.33
; ; ; 19/10/12 : 13.27.34

Let me lnow if you have any other idea.

I tested your code on my local windows machine:

$file = "testFile.txt";
$fh = fopen($file, 'a+') or die("can't open file");
$firstname = "firstName"; $lastname = "lastName"; $mood = "mood";
$datestring = date("d/m/y ");
$timestring = date("H.i.s");
$data   = "$firstname ; $lastname ; $mood ; $datestring : $timestring\r\n" ;
$data  .= "$firstname ; $lastname ; $mood ; $datestring : $timestring\r\n" ;
fwrite($fh, $data);
fclose($fh);

and it printed:

firstName ; lastName ; mood ; 19/10/12  : 12.00.35
firstName ; lastName ; mood ; 19/10/12  : 12.00.35

to the testFile.txt
I also tested it on my remote unix based host and it gave exactly the same result. Maybe I can see all the code concerned?

It seems you are absolutely right.

I don't know why but it also adds twice in my databse also. However i have write only once the sql query and above code.

test1 ; test1 ; bonne : 19/10/12 : 15.39.54
; ; : 19/10/12 : 15.39.55

test2 ; test2 ; pas bonne : 19/10/12 : 15.40.01
; ; : 19/10/12 : 15.40.02

In addition, i want to make sure to display error message if same person try to insert in same day. I have used DATETIME. I am trying to note down time taken by file to read and write the data also.

If you have any suggestion, please let me know.

Can i have ANY idea for this?

Here is my whole code:

    $prenom=$_POST['prenom'];
    $nom=$_POST['nom'];
    $humeur=$_POST['humeur'];
    $datelog=$_POST['datelog'];

    $query = "SELECT * FROM  `Humeur_log` WHERE  `prenom` =  '$prenom' AND  `datelog` =  '$datelog' LIMIT 0 , 30";
    $result = mysql_query($query);
    if (mysql_fetch_row($result)>0)
    {
        echo "<script type='text/javascript'>\n";
        echo "alert('Already registered..!!')\n";
        echo "</script>";
    }
    else
    {
        $sql="INSERT INTO `Humeur_log` (`logid`, `prenom`, `nom`, `datelog`) VALUES (NULL,'$_POST[prenom]','$_POST[nom]',CURRENT_TIMESTAMP)";
        $result = mysql_query($sql);
        // $result=mysql_query($sql);
        echo "<script type='text/javascript'>\n";
        echo "alert('Registered Successfully..!! ')\n";
        echo "</script>";
        echo "<br />";

        echo "Bonjour  ",$_POST["prenom  "];
        echo $_POST["nom"];
        echo "<br />";
        echo "Votre humeur  ",$_POST["humeur"];
        echo "<br />";
    }
    mysql_close($con);

    function microtime_float()
    {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
    $time_start = microtime_float();

    $file = "testFile.txt";
    $fh = fopen($file, 'a+') or die("can't open file");
    $firstname = $_POST["prenom"];
    $lastname = $_POST["nom"];
    $mood = $_POST["humeur"];
    $datestring = date("d/m/y");
    $timestring = date("H.i.s");
    $data = "$firstname ; $lastname ; $mood : $datestring : $timestring\r\n";
    fwrite($fh, $data);
    fclose($fh);
    $time_end = microtime_float();
    $time = $time_end - $time_start;
    echo "time ".round($time, 2)." seconde <br />";

Line 8: (mysql_fetch_row($result)>0) is this intended? do you mean (mysql_num_rows($result)>0) ?
All your database interactions should be ready for errors:
if (!$var = mysql_query()) die(mysql_error())
Line 16: the string $sql is wrong, look here to see why: http://www.daniweb.com/web-development/databases/mysql/threads/437020/php-mysql-wont-post#post1877407
Lines 24+27: You don't use a comma to concatenate a string.
Line 24: $_POST["prenom "] <- the key has whitespace.

As for the double entry into the database and the text file, is this ALL the code? I can't see where it is happeneing twice, or even how this script is running with the comma's for concatenation.

Member Avatar for LastMitch

@PriteshP23

I don't know why but it also adds twice in my databse also. However i have write only once the sql query and above code.

The reason why is double because you put $_POST[] in the VALUES

You already have $_POST[prenom] & $_POST[nom] you don't need to put another one in here:

$sql="INSERT INTO 'Humeur_log' ('logid', 'prenom', 'nom', 'datelog') VALUES (NULL,'$_POST[prenom]','$_POST[nom]',CURRENT_TIMESTAMP)";

When you INSERT it should look like this:

$sql = mysql_query("INSERT INTO Humeur_log (logid, prenom, nom, datelog) VALUES ('NULL','$prenom','$nom','CURRENT_TIMESTAMP')");

Try this now.

commented: To Rectify what some retard did to LastMitch +0

Lines 24+27: You don't use a comma to concatenate a string.

Actually, you can in an echo.
echo is a language construct, and can take multiple arguments. If you want to get down to micro seconds, it is also slower to use concatenation in an echo instead of comma separated values..

@Will Gresham

echo is a language construct, and can take multiple arguments. If you want to get down to micro seconds, it is also slower to use concatenation in an echo instead of comma separated values...

Point noted and thanks for the correction :D

SOLVED: "\n" problem in textfile

Now, the problem is for adding the twice.

@adam.adamski.96155 Thanks a lot.. \n works.. :):)

@LastMitch I have amend your suggestion. But it seems i have made more erros. It is not working. I have correct that line in my code.

@Will Gresham
Please let me know why it is adding new row when i refresh the page.

Thank you all for your time.

Can you post all your latest code, and re-tell what you want to acheive?

@adam.adamski.96155

Yes, of course.

Here is my latest code:
There are three files: form.php, save.php and liste.php
Problem:
1. It adds row twice.
2. Unable to Dynamically sort column
3. Name is not remaiming unique

I would like to know how i can make code for limit of 24 hours with DATE. I would like to have person with same name should be able to register mood per day but not in the same day.

    <form style="" action="save.php" method="post">    


    **form.php**  

    <form style="" action="save.php" method="post">    
    <p align="center">  Prenom: <input type="text" name="prenom" /></p>
    <p align="center">  Nom: <input type="text" name="nom" /></p>
    <p align="center" >Humeur:
    <SELECT name="humeur">
    <OPTION VALUE="tres bonne">Tres bonne</OPTION>
    <OPTION VALUE="bonne">Bonne</OPTION>
    <OPTION VALUE="moyen">Moyen</OPTION>
    <OPTION VALUE="pas bonne">Pas bonne</OPTION>
    <OPTION VALUE="mauvais">Mauvais</OPTION>
    </SELECT>
    </p>
    <p align="center"><br> <input type="submit" value="Envoyer"/> </p>  
    </form>


    **  save.php**

    $prenom=$_POST['prenom'];
    $nom=$_POST['nom'];
    $humeur=$_POST['humeur'];
    $datelog=$_POST['datelog'];


    $query = "SELECT * FROM  `Humeur_log` WHERE  `prenom` =  '$prenom' AND  `datelog` =  '$datelog' LIMIT 0 , 30";
    $result = mysql_query($query);
    if (mysql_num_rows($result)>0)
    {
    echo "<script type='text/javascript'>\n";
    echo "alert('Aleady exists..!!.')\n";
    echo "</script>";
    }
    else
    {     

    $sql="INSERT INTO `Humeur_log` (`logid`, `prenom`, `nom`, `datelog`) VALUES (NULL,'".$prenom."','".$nom."',CURRENT_TIMESTAMP,)";
    $result = mysql_query($sql);

    if (!mysql_query($result,$con))
    {
    die('Error: ' . mysql_error() . '<br/><br/>' . $result);
    }

    $result=mysql_query($sql);
    echo "<script type='text/javascript'>\n";
    echo "alert('Registered...!')\n";
    echo "</script>";
    echo "<br />";
    echo "Bonjour ",$prenom;
    echo "<br />";
    echo "Votre humeur  ",$humeur;
    echo "<br />";
    }


    ** liste.php**    
    $logid=$_POST['logid'];
    $prenom=$_POST['prenom'];
    $nom=$_POST['nom'];
    $humeurid=$_POST['humeurid'];
    $datelog=$_POST['datelog'];
    $Humeur_log=$_POST['Humeur_log'];
    $Humeur_type=$_POST['Humeur_type'];*/

    $query = "SELECT * FROM  Humeur_log";
    $order = (isset($_POST['sortCostCode']) && strcasecmp($_POST['sortCostCode'], 'desc') == 0) ? 'DESC' : 'ASC';
    $query = 'SELECT * FROM Humeur_log ORDER BY logid ' . $order;


    //$query = "SELECT `humeur` FROM `Humeur_type` WHERE `humeurid`='$humeurid'";
    //$resulthumeur = mysql_query($queryhumeur);
    $result = mysql_query($query);

    ?>

    <table style='border-width: 4px;>
    <tr>
    <th><a href='?sortcostcode=" . ($order == 'DESC' ? 'ASC' : 'DESC' ) . "'>logid</a></th>
    <th>Prenom</th>
    <th>Nom</th>
    <th>Date</th>
    <th>Humeur</th>
    </tr>

    <?php
    while($rows=mysql_fetch_assoc($result))
    {
    echo "<tr>";
    echo "<td>" . $rows['logid'] . "</td>";
    echo "<td>" . $rows['prenom'] . "</td>";
    echo "<td>" . $rows['nom'] . "</td>";
    echo "<td>" . $rows['datelog'] . "</td>";
    echo "<td>" . $rows['humeur'] . "</td>";
    echo "</tr>";
    }  
    ?>
    </table>
    ?>

Pritesh, I replicated your pages and your database on my local machine.
form.php is all good.
save.php had a few problems on my machine:

//I wrapped the next part in an isset() to stop the undefined index error.
if(isset($_POST['prenom'])){
    $prenom=$_POST['prenom'];
    $nom=$_POST['nom'];
    $humeur=$_POST['humeur'];
}

As for the date comparison, I had problems with my machine caching the date and giving false information, so I changed the column type to int and stored a timestamp instead of a date.

$now = date("U"); //num seconds since jan1 1970
$one_day = ($now -(60*60*24));//minus 1 day (60secs * 60mins * 24hrs)
$query = "SELECT * FROM `Humeur_log` WHERE `nom`='$nom' AND `prenom`='$prenom' AND (`datelog` > $one_day)";

Now it will return all rows that were posted in the last 24hrs. There is certainly a better way to acheive this, but this is how I worked it out.

//The updated insert statement.
$sql="INSERT INTO `Humeur_log` (`prenom`, `nom`, `datelog`) VALUES ('$prenom','$nom', $now)";

I tested on name AND surname (prenom && nom) as it made more sense to me like that.
Do you not want to store the mood also in the database?

Questions:
Where is it writing twice?
Which column needs dynamically sorting and when?
Which name should be unique?

@adam.adamski.96155

Yes, i have problems in save.php file only.

I got message like this when i modify the code and put your code. Your logic for 24 hours with DATE seems good.

**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 '1' at line 1

1**

However, i have tried all sql quey in databse phpMyAdmin. It works fine.

In fact, Before i have written $_POST two times, it prints twice. But now, it is working. (Will Gresham)

Answers:
Sorry, earlier it was writing twice.
logid and date column should be worked dynamically sorting when i have displayed the data in table on liste.php file. User should be able to
Firstname and lastname should be unique.

I am sorry in advanced if i am taking your more time.

Here is my table structure:

`Humeur_log`

CREATE TABLE IF NOT EXISTS `Humeur_log` (
  `SOURCE` text COLLATE utf8_unicode_ci NOT NULL,
  `logid` int(11) NOT NULL AUTO_INCREMENT,
  `prenom` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `nom` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `datelog` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`logid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=231 ;

`Humeur_type`

CREATE TABLE IF NOT EXISTS `Humeur_type` (
  `humeurid` int(11) NOT NULL AUTO_INCREMENT,
  `humeur` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`humeurid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ;


INSERT INTO `Humeur_type` (`humeurid`, `humeur`) VALUES
(1, 'Good'),
(2, 'Romantic'),
(3, 'Bad')
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.