0

By default, PHPMyAdmin has the datetime column formatted as YYYY-MM-DD, but I'm trying to reformat it into MM-DD-YYYY using an SQL statement on my PHP file. This is the code I used, but it's not working:

<?php $usertext = $_POST['textinput']; $insertsql = "INSERT INTO testtext (usertext) VALUES ('$usertext')"; if (isset($_POST['textinput'])) { require '../db.php'; mysqli_query($db, $insertsql); } $selectdate = "SELECT textdate, DATE_FORMAT(textdate,'%m/%d/%Y') AS newdate FROM testtext"; $dateresult = mysqli_query($db, $selectdate); while ($row = mysqli_fetch_assoc($dateresult)) { echo "{$row['textdate']}<br>"; } ?> 

This code is able to display rows from the 'textdate' column onto my test site just fine, but the DATE_FORMAT code was unable to reformat the date. Can you please help me fix this code? Thanks so much.

7
  • 1
    Your script is at risk of SQL Injection Attack Have a look at what happened to Little Bobby Tables Even if you are escaping inputs, its not safe! Use prepared parameterized statements. Commented Mar 20, 2018 at 20:36
  • update your question and add a proper data sample .. Commented Mar 20, 2018 at 20:37
  • What does $row['newdate'] look like? Commented Mar 20, 2018 at 20:37
  • @rickdenhaan $row['newdate'] doesn't show the date, just an empty string. $row['textdate'] does show the date though, but not in desired format. Commented Mar 20, 2018 at 20:47
  • @John Conde Thanks for the info and letting me know. I was just testing this script first since it's easier. I was going to work on security after. Commented Mar 20, 2018 at 20:49

1 Answer 1

2

You are calling your formatted date newdate but are referring to textdate in your code. You need to refer to that alias you assigned the results of DATE_FORMAT() to and not the original column identifier.

while ($row = mysqli_fetch_assoc($dateresult)) { echo "{$row['newdate']}<br>"; } 
Sign up to request clarification or add additional context in comments.

4 Comments

But when I change it to {$row['newdate']}, the date doesn't show up. I think it's because the table in my database is called 'textdate' and 'newdate' doesn't exist there.
Do var_dump($row); and see if the value exists in the results
@codo7081 nope, you are wrong. Newdate is a field alias. If nothing shows up there, then either the conversion went wrong annd it returned null, or some other error occured.
@John Conde hey it works now! It seems I was supposed to echo out newdate instead. Thanks so much for your help!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.