Jump to content

Cannot add or update a child row: a foreign key constraint fails


Recommended Posts

Hello,

 

I have created two tables, one called 'posts' and the other 'selected_pic'.

The idea is to have a table of posts that gets stored with an ID that references the image in the 'selected_pic' table. From what i have gathered, using Foreign keys is probably the best way y do this? If theres something easier, then please let me know.

 

However when i try to make a post on the web page "Cannot add or update a child row: a foreign key constraint fails " comes up and thus fails to insert into the table.

 

This is what i have set up so far..

 

 

TABLE : selected-pic

 

'pic_id' - int(11) - NOT_NULL - auto_increment

'username' - varchar(32) - NOT_NULL

'imagelocationpic' - varchar(100) - NOT_NULL

 

Primary Key - 'pic_id'

 

 

Table : posts

 

'posts_id' - int(11) - NOT_NULL - auto_increment

'pic_id' - int(11) - NOT_NULL

'username' - varchar(11) - NOT_NULL

'text' - varchar(100) - NOT_NULL

'date' - date - NOT_NULL

'time' - int(11) - NOT_NULL

'up' - int(11) - NOT_NULL

'down' - int(11) - NOT_NULL

'profile_pic' - varchar(100) - NOT_NULL

 

Primary Key - 'posts_id'

Index key - 'pic_id'

 

*Here i have set the 'pic_id' from the 'posts' table to reference the 'pic_id' in the 'selected_pic' table.

 

 

 

PHP & Mysql code on page.

 

<?php 

$id=$_SESSION['username']; 
$time=time(); 
$date=date("Y-m-d"); 

if($_POST['post']) 

{ 

//get the data 
$text=$_POST['text']; 
$image=$_POST['profile_pic']; 

//check for existance 
if ($text) 

{ 

//insert data	
include ("connect2.php"); 

$time=time(); 

$insert=mysql_query("INSERT INTO posts VALUES('', '', '$id','$text','$date', '$time','','','$image')") or die(mysql_error());	
echo ""; 

} 
else echo "Please fill out the text field"; 

} 
echo" 
<br>"; 
?> 

Thanks in advance!

 

Dave

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.