0

Well i built my website to write dates to database column in the following format: 2014/04/01

Now i've come to realize this is not helpful when i want to sort by date or manipulate date so i decided to change all date to to timestamps.

i applied the following fix :

    $sql = mysql_query("SELECT * FROM TABLE")or(die(mysql_Error()));
while($info = mysql_fetch_array($sql)){
        $newdate = strtotime($info['date']);
        mysql_query("UPDATE TABLE SET date = '$newdate' WHERE id = $info[id]")or(die(mysql_error()));
}

the problem is all the date columns are empty now, What am i doing wrong ?

9
  • Where are you actually changing the column datatype? Commented Aug 21, 2014 at 15:38
  • 1
    What's $info['date'] set to when it fails? Commented Aug 21, 2014 at 15:38
  • In the UPDATE statement im replacing the old date with the new timestamp. Commented Aug 21, 2014 at 15:38
  • Whats the data type of column date? Commented Aug 21, 2014 at 15:39
  • why dont use a date field date? Commented Aug 21, 2014 at 15:39

1 Answer 1

0

There's what looks like a syntax error on this line:

mysql_query("UPDATE TABLE SET date = '$newdate' WHERE id = $info[id]")
    or(die(mysql_error()));

Try changing it to:

mysql_query("UPDATE TABLE SET date = '$newdate' WHERE id = {$info['id']}")
    or (die(mysql_error()));

The reason is that when interpolating array indices into a string, you must surround them with {} or PHP will just try to convert $info to a string and insert [id] after it, which I'm guessing you didn't intend.

I would also suggest checking the return value for strtotime. If it can't parse a date it returns false which I'm guessing you don't want inserted back into your database.

Sign up to request clarification or add additional context in comments.

5 Comments

and think about using pdo or mysqli_* function instead of the deprecated mysql_query. and then you should use prepare statements to prevent from sql injections besides other nice improvments (e.g. speed - prepare once, update many)
@Rufinus I don't think prepared statements will do anything to improve security here. It seems he's running a one-off script to "fix" the data in the date column using PHP. Still, I agree, it's a good habit to get into.
@amphetamachine right. this is why i mentioned the speed gain. if he prepare the statement once and execute only with the different values.
@Rufinus Reusing prepared statements won't increase speed over straight querying; the same amount of SQL gets sent over the wire regardless.
@amphetamachine not really, you spare the mysql server to parse the same query over and over again. see stackoverflow.com/questions/11389449/…

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.