Avatar of Mike Moore
Mike Moore
 asked on

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.
DatabasesPHPMySQL Server

Avatar of undefined
Last Comment
Mike Moore

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Chris Stanyon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Mike Moore

ASKER
great thanks
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes