Unable to insert data into phpMyAdmin via comments form

Hey guys, I am new to dev and would really appreciate some help as I am just towards the end of my project. I have created a simple comments form and just want to insert the comment_content data into the phpMyAdmin for since that is all that is required at this point. My issue is that I cannot get it to work. Here is the code as follows;

comments_form.php

<html>
  <head>
    <title>Comments form</title>
    <meta charset="UTF-8">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <link rel="stylesheet" href="../_css/style.css">
    <!--Fonts-->
    <link rel="stylesheet" type="text/css" href="../lou/_css/ss-pika.css" />
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <link href="../_css/styles.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
      
    <div class="container">   
      <h1>Comments</h1>
      <div id="unique-section" class="row">
        <div class="section">
            <form action="comments.php" method="post">
            <div class="form-group">
              <textarea name="comment_content" placeholder="Please add your comments here" style="height:200px; width:300px;font-size:12pt; align-vertical:" name="comment_content" class="form-control">
              </textarea> 
            </div>
            <div class="form-group">
              <input type="submit" name="comment_submit" class="btn btn-primary" />
            </div>
          </form>
        </div>
      </div>
    </div>
    <!-- Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous">
    </script>
    <script src="ajax.js">
    </script>
  </body>
</html>

comments.php

<?php
include_once ("dbconnection.php");
include ("comments_form.php");

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

        $comment_content = $_POST ["comment_content"];
        
        
        $comment_length = strlen($comment_content);
        
        if ($comment_length > 100){ 
            header("location: ../login/index.html?error=1");
        }else{
          
        $mysql_query =("INSERT INTO comments('comment_id', 'post_id', 'member_id', 'comment_content', 'comment_date', 'approved') 
                  VALUES ('','2','2','$comment_content','','0')");           
        header("location: ../login/index.html");
        
        }  
}
        
var_dump($_POST);       
        
?>

dbconnection.php

<?php
try {
    
  $con = new PDO ("mysql:host=localhost; dbname=test_blog", "root", "");

//echo "connected";
  $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  
  }  
  catch(PDOException $e)
  
  {
      echo "error" .$e->getMessage();
  }   

I have no errors and the database connection was tested successfully with another file where I could insert data.

Any help would be very much appreciated.

Thanks

You are mimxing PDO with the deprecated mysql-extension. Stick to PDO.

$stmt = $con->prepare('insert into foo(id, comment) values(?, ?)')
$stmt->execute([2, $content]);
1 Like

Thank you for your reply.

Thanks again for you help. I am now getting the following error. I am total beginner at this so apologies if I ask stupid questions.

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (pusheen_blog.comments, CONSTRAINT comments_ibfk_1 FOREIGN KEY (post_id) REFERENCES posts (post_id)) in C:\xampp\htdocs\pusheen_blog\comments\comments.php:21 Stack trace: #0 C:\xampp\htdocs\pusheen_blog\comments\comments.php(21): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\pusheen_blog\comments\comments.php on line 21

$stmt = $con->prepare('insert into foo(id, comment) values(?, ?)')
//May I ask why you entered the int 2
$stmt->execute([2, $content]);

I looked up the error which implies that I am attempting to add to a row that doesn’t exist which is the post_id but it does exist in the table.

The post was a contrived example to demonstrate the syntax, not to be used as is. Surely you don’t have a table named foo do you? :wink:

In other words, when you change the code from the obsolete mysql_ line, you can prepare the query using question mark place holders eg. ... VALUES (?,?,?,?,?,?)
Then in the array passed in the execute you can enter the appropriate values used in the query in the order that they will be used. If the datatype of the field is an int, no quotation marks are needed. If a string, use quotation marks. If they are variables, make sure they will be what you want them to be. PHP can do type juggling, but it is usually a poor idea to rely on it without being absolutely sure.

1 Like

Yes of course I know that it was an example so I didn’t just copy and paste it as it was and expected it to work. I edited it as suggested and then ended up with the other error

But thank you for explaining the int. It had totally slipped my mind as I have been trying to resolve several issues since 3am this morning and getting nowhere fast hahaha. I appreciate your feedback though. thanks you

So just to clarify this is what I did.

$stmt = $con->prepare(“insert into comments(comment_id, post_id, member_id, comment_content, comment_date, approved) values(‘’,‘’,‘’,‘$comment_content’,‘’,‘’)”);
$stmt->execute();

This is the error now:

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (pusheen_blog.comments, CONSTRAINT comments_ibfk_1 FOREIGN KEY (post_id) REFERENCES posts (post_id)) in C:\xampp\htdocs\pusheen_blog\comments\comments.php:21 Stack trace: #0 C:\xampp\htdocs\pusheen_blog\comments\comments.php(21): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\pusheen_blog\comments\comments.php on line 21

Looks like there is a foreign key constraint on post_id to some other table, so that value cannot be empty. It must be filled with an ID that actually exists in the other table.

1 Like

Thank you, that is something I didn’t realise. I will add a value and report back .

Much appreciated.

1 Like

Hey so I entered a value and don’t get any errors but still have an issue with no entry into the db

Can you post the entire code you have now?

The code now:

comments.php

<?php
include_once ("dbconnection.php");
include ("comments_form.php");

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

        $comment_content = $_POST ["comment_content"];
        
        
        $comment_length = strlen($comment_content);
        
        if ($comment_length > 100){ 
            header("location: ../login/index.html?error=1");
        }else
                   
        $stmt = $con->prepare("insert into comments(comment_id, post_id, member_id, comment_content, comment_date, approved) values('','1','19','$comment_content','','')");
        $stmt->execute();
          
                
        header("location: ../login/index.html");
        
        }  

        
var_dump($_POST);       
        
?>

comments_form.php

<html>
  <head>
    <title>Women Who Can - Comments form</title>
    <meta charset="UTF-8">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <link rel="stylesheet" href="../_css/style.css">
    <!--Fonts-->
    <link rel="stylesheet" type="text/css" href="../steph/_css/ss-pika.css" />
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <link href="../_css/styles.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
  
    <div class="container">   
      <h1>Comments</h1>
      <div id="unique-section" class="row">
        <div class="section">
            <form action="comments.php" method="post">
            <div class="form-group">
              <textarea name="comment_content" placeholder="Please add your comments here" style="height:200px; width:300px;font-size:12pt; align-vertical:" name="comment_content" class="form-control">
              </textarea> 
            </div>
            <div class="form-group">
              <input type="submit" name="comment_submit" class="btn btn-primary" />
            </div>
          </form>
        </div>
      </div>
    </div>
    <!-- Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous">
    </script>
    <script src="ajax.js">
    </script>
  </body>
</html>

dbconnection.php

<?php
try {
    
  $con = new PDO ("mysql:host=localhost; dbname=pusheen_blog", "root", "");

//echo "connected";
  $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  
  }  
  catch(PDOException $e)
  
  {
      echo "error" .$e->getMessage();
  }

@louisejean
<off-topic>
When you post code in the forum, you need to format it. To do so you can either select all the code and click the </> button, or type 3 backticks ``` on a separate line both before and after the code block.
</off-topic>

1 Like

Hi, thank you for enlightening me.

1 Like

There is { missing there, it should be } else {

Also, you should not put values in a prepare statement, that misses the entire point of a prepared statement.

even better, that entire file should be

<?php
include_once ('dbconnection.php');
include ('comments_form.php');

if (isset($_POST["comment_submit"])){
    $comment_content = $_POST['comment_content'];
        
    if (strlen($comment_content) > 100) { 
        header('location: ../login/index.html?error=1');
        exit;
    }

    $stmt = $con->prepare('INSERT INTO comments(comment_id, post_id, member_id, comment_content, comment_date, approved) VALUES (?, ?, ?, ?, ?, ?)');
    $stmt->execute(['', 1, 19, $comment_content, '', '']);

    header('location: ../login/index.html');
}

See how much more readable that is when you take care of proper indentation and alignment? :slight_smile:

Thank again for pointing out syntax errors:

This is what I have now. I entered values just for testing because those values cannot be null due to the foreign key constraints. This was something that I came up against earlier which spaceshiptrooper pointed out to me

<?php** **include_once ("dbconnection.php");** **include ("comments_form.php");** **if (isset($_POST ["comment_submit"])){** **$comment_content = $_POST ["comment_content"];** **$comment_length = strlen($comment_content);** **if ($comment_length > 100){ ** **header("location: ../login/index.html?error=1");** **} else {** **$stmt = $con->prepare("insert into comments(comment_id, post_id, member_id, comment_content, comment_date, approved) values('','1','19','$comment_content','','')");** **$stmt->execute();** **header("location: ../login/index.html");** **} ** **}** **var_dump($_POST); ** **?>

Have you tried my code?

If you mean the following then yes but the issue remains

<?php include_once ('dbconnection.php'); include ('comments_form.php'); if (isset($_POST["comment_submit"])){ $comment_content = $_POST['comment_content']; if (strlen($comment_content) > 100) { header('location: ../login/index.html?error=1'); exit; } $stmt = $con->prepare('INSERT INTO comments(comment_id, post_id, member_id, comment_content, comment_date, approved) VALUES (?, ?, ?, ?, ?, ?)'); $stmt->execute(['', 1, 19, $comment_content, '', '']); header('location: ../login/index.html'); }