Database issue (SQLSTATE[23000]: Integrity constraint violation: 1452)

Hi guys

I am getting this error when trying to insert into my database :

Warning: PDOStatement::execute(): SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`cobox`.`posts`, CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`)) in /Applications/MAMP/htdocs/cobox/application/model/PostsModel.php on line 69

any suggestions???

Users Table

Screen-Shot-2017-11-28-at-21.54.56.png
Posts Table

Screen-Shot-2017-11-28-at-21.55.06.png
Relationship

Screen-Shot-2017-11-28-at-21.55.21.png
I am using an MVC structure here is the code I am using :

Model

public function addPost($firstName, $lastName, $email, $password)
	{
		try
		{	
			
			$password = sha1($password);
			$stmt = $this->db->prepare("INSERT INTO users(firstname, lastname, email, password) 
		                                               VALUES(:firstName, :lastName, :email, :password)");
												  
			$stmt->execute(array(':firstName'=>$firstName,
								 ':lastName'=>$lastName,
								 ':email'=>$email,
								 ':password'=>$password));							  
				
		} catch(PDOException $e) {
			echo $e->getMessage();
		}				
	}









	// new post
    public function newPost($post_name, $post_description, $post_text, $user_id)
	{
		try
		{	
			$stmt = $this->db->prepare("INSERT INTO posts(post_name, description, post_text, user_id) 
		                                               VALUES(:post_name, :description, :post_text, :user_id)");
												  
			$stmt->execute(array(':post_name'=>$post_name,
								 ':description'=>$post_description,
								 ':post_text'=>$post_text,
								 ':user_id'=>$user_id));							  
				
		} catch(PDOException $e) {
			echo $e->getMessage();
		}				
	}

Open in new window


View

<div class="container">

<div class="forms">
    
    <h3 style="margin-bottom: 30px;">Add New Post</h3>

            <?php
                if(isset($errors))
                    {
                        echo "<div class='alert error'>";

                        foreach($errors as $error)
                        {
                            ?>
                            <div>
                                <?php echo $error; ?>
                            </div>
                            <?php
                        }
                         echo " </div>";

                    } 
            ?>


    <form action="<?php echo URL?>posts/newPost" method="POST">
        <input type="text" name="post_name" placeholder="Enter post name" value="<?php if(isset($errors)){echo $_POST['post_name'];}?>" required/>
        <input type="text" name="description" placeholder="Enter description" value="<?php if(isset($errors)){echo $_POST['description'];}?>" required/>
        <input type="text" name="post_text" placeholder="Enter post text" value="<?php if(isset($errors)){echo $_POST['post_text'];}?>" required/>
        <input type="hidden" name="user_id" value="<?php if(isset($errors)){echo $_POST['user_id']; } ?>" />
        <input type="submit" name="submit" value="Add Post">
        &nbsp; &nbsp;  &nbsp; &nbsp;  &nbsp; &nbsp; 
        <a class="button" href="<?php echo URL?>profile">Cancel </a>
    </form>
</div>

</div> <!--End of container -->

Open in new window


Controller

public function add($status = '')
    {
          $pageTitle = 'Add post';
        // load views

        require APP . 'view/_templates/header1.php';

        if($this->is_loggedin()){

         $id = $_SESSION['user_session']['user_id'];
         $profileDetails = $this->model->getPost($id);

         require APP . 'view/Posts/add.php';
         require APP . 'view/_templates/footer.php';

        } else{
            $this->redirect('user');	
           
        }
   }
    
    // the add form sends the data to here
    public function newPost()
    {
        if (isset($_POST['submit'])) {

            $id = isset($_SESSION['user_session']['user_id']);
            
            $post_name = $_POST['post_name'];
            $post_description = $_POST['description'];
            $post_text = $_POST['post_text'];
            $user_id = $id;

            $this->model->newPost($post_name, $post_description, $post_text, $user_id);
        
        }
    }

Open in new window


any help is highly appreciated.

Thanks.
Mike MooreAsked:
Who is Participating?
 
Chris StanyonCommented:
Take a look at your View:

<input type="hidden" name="user_id" value="<?php if(isset($errors)){echo $_POST['user_id']; } ?>" />

This will only ever echo out the POST['user_id'] if you have errors. No errors = no value!

Then take a look at the Controller/newPost method:

$id = isset($_SESSION['user_session']['user_id']);

This basically sets the $id variable to either TRUE or FALSE, depending on whether or not a SESSION variable is set, so when you call this:

$user_id = $id;
$this->model->newPost($post_name, $post_description, $post_text, $user_id);

You only ever pass in TRUE of FALSE (0 or 1) which is probably where your Exception is coming from
0
 
Mike MooreAuthor Commented:
great thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.