Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • how can i insert a value into foreign key in mysql table using php?

    • 0
    • 0
    • 0
    • 5
    • 0
    • 0
    • 0
    • 1.56k
    Answer it

    I am having a problem when I try to push value into a foreign key in MySQL table I don't know if it's correct but I have used the  GET method to pass the primary key through a link but it didn't work so how can I use the right way to do that 
     

    <?
    $sql = mysqli_query ($link,"SELECT * FROM `programming_language`") or die (mysqli_error($link));
        while ( $row = mysqli_fetch_assoc($sql)):
    
     language_id = $row['language_id'] ;
     language_name = $row['language_name'] ;
    
    endwhile ;
    
    ?>
    

    i need to insert the primary key form programming_language table into test tables 

     

    <?
    $sql = mysqli_query ($link,"INSERT INTO `test`( `test_name`, `language_id`) VALUES ('". $test_name."','".$language_id."') ") or die (mysqli_error($link)) ;
    
    ?>

     

 5 Answer(s)

  • Hello Nasyia,

    I have checked your code and I can see you are getting data from programming_language table then outside the while loop you are inserting the data. You need to put the insert query inside the while loop to store all the language id. If you put the insert query outside the loop then only last value will be inserted. If you are still facing problem or you are getting any specific error then send us the error which are you getting?

    Hope this helps!

    Deepak Verma Sr. Software Engineer

  • Hello Nasyia, In above code, i think the select statement returns more than 1 language_id but you have declared it as a variable first make it an array then try to insert this in test table. Please check it and inform me if you still face some issue.

  • Hello Nasyia,

    If you are adding data in test table then there should be a form to fill the data to insert. You need to contain all the language in a drop-down with their ids. After form submission you can get the form data and pass these data in query to insert.

    Hope this helps!

    Deepak Verma Sr. Software Engineer

  • Hello !! Thank you for your help , but these codes are written in different pages and values in programming languages are stored in the database already, but I need to insert the id of the programming languages whenever you want to add a new test so how can i insert the id i found method called the last id but its using when you adding new rows but my values are already stored i hope i made it clear for you

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: