简体   繁体   中英

How do I insert a related row into a mysql database?

I'm completely stumped. I have two tables set up in my database, one called subjects and one called pages. I gave the pages a subject_id in my database to connect them to subjects. I've dynamically displayed a nav containing the subjects and there child pages. I've also created a few php files that delete subjects, edit subjects, and edit pages. I've now added a link onto each subject so that when you click on the subject, it takes you to a page where, hopefully, I'll be able to add a new page under the chosen parent subject. It's also worth noting that i am sending the parent subject id in the link to add the page. Here's the fraction of code that i believe is somehow giving me problems:

if(empty($errors)){
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$content = mysql_prep($_POST['content']);

$subject = get_subject_by_id($id));//This fetches the subject id from the db

$query = "INSERT INTO
pages WHERE subject_id = $subject
(
menu_name, position, visible, content
) VALUES (
'{$menu_name}', {$position}, {$visible}, '{$content}'
)";
$result = mysql_query($query, $db_connect);      
if (mysql_affected_rows() == 1){

echo "<p>suceess</p>";
} else { ....

I know this is out of context but i thought someone might have some luck by spotting the problem. If anybody has ANY insight on this I would appreciate it.

You can't have a where clause in an insert statement.

Without the where clause the table will get the inserted row. If you are trying to update an existing row, which would justify a where clause, then you need to use an update statement.

the correct INSERT syntax is:

INSERT INTO pages (subject_id, menu_name, position, visible, content) VALUES (?,?,?,?,?)

of course, bind with the appropriate parameters and do not use string interpolation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM