• PHP Help
  • Getting the error Undefined index but the column exists?.

Hello,

I added a column to my database with SQL as follows:

ALTER TABLE comment_table ADD date_col Datetime NOT NULL;

I try to insert into the database with the following PHP but nothing gets inserted.

if(isset($_POST["submit"]))
{

$date_col = "test";//this will be DateTime later
$name = $_POST["name"];

mysqli_query($connection, "INSERT INTO comment_table (name, date_col) VALUES ('$name', '$date_col')");
}

$comsql = "SELECT * FROM comment_table";
$comres = mysqli_query($connection, $comsql);
while($comr = mysqli_fetch_assoc($comres)){
?>
<div class="row">
<p>Name: <strong><?php echo $comr['name']; ?></strong>This is the code that is being pointed to as undefined index. <?php echo $comr['date_col']; ?> </p>
<?php } ?>
</div>
The data I'm using for the date_col column is varchar and it should be Datetime but I don't know if that's the reason for the error. I would like to set $date_col equal to a Datetime expression for testing purposes but the formatting I chose wasn't working either.

    You're already jamming undiluted user-supplied material into your query (A Very Bad Thing) and you'll need to convert your DateTime into a textual representation the database will recognise anyway. So that's not it. More likely to be the problem is the fact that MySQL wouldn't recognise "test" as any sort of date or time and would complain about that if you're trying to insert it into a MySQL datetime field. If you're storing your dates in something other than a date type field then that's yet another problem.

    If you're having errors, have you considered using mysqli_error to see what error the database is reporting?

    If the index that should be there isn't there, have you tried looking at $comr to see what is there?

    What other debugging steps have you taken?

      Write a Reply...