Jump to content

Getting the error Undefined index but the column exists


Recommended Posts

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. 


$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 } ?>

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.

Link to comment
Share on other sites

I changed the code so that it is using prepared statements but I just get new errors now. I altered the table so that the date_col column has the data type of varchar. I get the following warning:

mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement

if(isset($_REQUEST["submit"]) ) {
$date = new DateTime('', new DateTimeZone('America/New_York'));
$name = mysqli_real_escape_string($connection, $_REQUEST["name"]);
$date_col = $date->format('M d, Y H:i');
$website = $_REQUEST["website"];
$comment = mysqli_real_escape_string($connection, $_REQUEST["comment"]);
$sql = "INSERT INTO comment_table (name,date_col,website,comment) VALUES ('$name', '$date_col','$website','$comment')";  
if($stmt = mysqli_prepare($connection, $sql)){
    // Bind variables to the prepared statement as parameters
    // Attempt to execute the prepared statement
        echo "Records inserted successfully.";
    } else{
        echo "ERROR: Could not execute query: $sql. " . mysqli_error($connection);
} else{
    echo "ERROR: Could not prepare query: $sql. " . mysqli_error($connection);
// Close statement
// Close connection


Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...