We help IT Professionals succeed at work.

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

Mike Moore
Mike Moore asked
on
284 Views
Last Modified: 2018-03-27
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.
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Author

Commented:
great thanks

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions