0

I have a question: I have 2 tables in my database:

articles:
id  useid  title
users
id  name  surname

My view:

 Author<select name="author" id="author">
                            <?php foreach ($users as $u): ?>
                                <option value="<?php $u['id'] ?>" <?php if($u['id']==$a['userid']): ?> selected="selected" <?php endif ?> style="width:300px"><?php echo $u['name'] ?> <?php echo $u['surname'] ?></option>
                            <?php endforeach; ?>
        </select>
        <p><b>Content:</b></p>
        <textarea name="content" id="content" style="width:605px; height: 300px;" rows="200"><?php echo $a['content']; ?></textarea>

My Controller:

$this->db->query("UPDATE articles SET title='$title',userid='$author' WHERE id=$aid" );

When I do this I got the error 1452: Cannot add or update a child row: a foreign key constraint fails (myblog.articles, CONSTRAINT articles_ibfk_1 FOREIGN KEY (userid) REFERENCES admindetails (id) ON DELETE CASCADE ON UPDATE CASCADE) Help me please guys....

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43
  • 2
    The error message seems to say *exactly* what the problem is: the updated `articles.userid` does not match any `admindetails.id` value .. the column/relation names seem "odd". (Also see http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – user2864740 Jun 02 '14 at 08:36
  • At the start of the question you say your table is called `users`, but your error message indicates `userid` references a table called `admindetails`. Are these two different tables? Is it possible that you have set up the foreign key referencing the wrong table? – GarethD Jun 02 '14 at 08:47

2 Answers2

2
<option value="<?php $u['id'] ?>" <?php if($u['id']==$a['userid']): ?> selected="selected" <?php endif ?> style="width:300px"><?php echo $u['name'] ?> <?php echo $u['surname'] ?></option>

where is your echo statement..

put <option value="<?php echo $u['id']; ?>" instead of ", Thats why the key is duplicating,every time it will take the same value which is NULL.. Just change it.

Vaisakh Pc
  • 714
  • 8
  • 21
0

In this case it means that your $author variable holds and id(if its a number) that doesn't exist in the admindetails table

Bartłomiej Wach
  • 1,968
  • 1
  • 11
  • 17