E
E
elisey4742015-10-09 10:36:24
PHP
elisey474, 2015-10-09 10:36:24

What is wrong with the php code?

This crap first gives out 4, then 3 and that's it.

$f = fopen("db.txt", "r"); 	
$c = $f + 1;
fclose($f);
$f = fopen("db.txt", "w"); 	
fwrite($f, $c); 	
fclose($f);
echo $c;

Where is the mistake?

Answer the question

In order to leave comments, you need to log in

6 answer(s)
N
neol, 2015-10-09
@elisey474

If I understood correctly what you wanted to write, then:

<?php
$fd = fopen("db.txt", "r");
$data = fgets($fd);
fclose($fd);
$data = $data + 1;
$fd = fopen("db.txt", "w");
fwrite($fd, $data);
fclose($fd);
echo $data;

You missed fgets.
And remember that for the meaningless names of variables in a decent society they can even heat up with a candelabra.

S
Sergey Zhukov, 2015-10-09
@Adobe

I hope not offtopic, but I'll leave it here:
Once
php.net/manual/ru/function.file-get-contents.php
and two
php.net/manual/ru/function.file-put-contents.php

S
Shirshov Alexander, 2015-10-09
@Keanor

fopen returns a resource type, why are you trying to do arithmetic with it?

M
Maxim Malypko, 2015-10-09
@maximmalypko

You can also use fread to read the contents of a file. fopen - opens, and fread or fgets fetches the contents. With variable names +1

B
bO_oblik, 2015-10-09
@bO_oblik

How did you get into the past? lol :)

D
Dmitry, 2015-10-09
@mytmid

maybe something like that?

file_put_contents( 'db.txt' , $data = (int)file_get_contents('db.txt') + 1 );
echo $data;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question