troubleshooting Question

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

Avatar of Mike Moore
Mike Moore asked on
DatabasesPHPMySQL Server
2 Comments1 Solution295 ViewsLast Modified:
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();
		}				
	}

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 -->

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);
        
        }
    }

any help is highly appreciated.

Thanks.
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros