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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike MooreAuthor Commented:
great thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Databases

From novice to tech pro — start learning today.