What is preventing my MySQL foreign key from being created?

I have been experimenting with different methods to create a table that includes a foreign key and then insert it into phpMyAdmin. Unfortunately, the results are not meeting my expectations.

Here is what I have tried:

CREATE TABLE user (
    user_id BIGINT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    user_name VARCHAR(50) NOT NULL,
    user_password VARCHAR(50) NOT NULL);

The above code works perfectly fine. However, when I attempt to add a table with a foreign key like this, it does not allow me to create it:

CREATE TABLE article (
    article_id INT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    article_title VARCHAR(100) NOT NULL,
    article_content VARCHAR(1000) NOT NULL,
    user_id INT(10) NOT NULL,
    FOREIGN KEY (user_id) REFERENCES user (user_id));

This setup fails to add the table to the MySQL database and triggers the following error message:

Cannot add foreign key constraint

How can I resolve this issue?

Answer №1

After some exploration in the comments, we made an interesting discovery regarding the definition of a primary key:

user_id BIGINT(10) UNSIGNED

It turns out that a foreign key like the following won't function as expected because it must match in signedness (and possibly type):

user_id INT(10) NOT NULL

However, the following modification works perfectly:

user_id BIGINT(10) UNSIGNED NOT NULL

For a visual demonstration of this concept in action, check out this Fiddle.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Script for calculating in PHP

I've scoured the internet in search of a sample script that meets my specific needs, but unfortunately, I have come up empty-handed. Essentially, I am looking to retrieve a value from a div and then multiply that number based on user input. For instan ...

Upon successful completion of the Ajax call, refresh the page without causing any blinking

Hey there, I'm facing an issue with my website, I've implemented ajax to fetch data from my API, and upon successful retrieval, I need to reload the page to display the information, However, sometimes the page blinks before reloading, while oth ...

Utilize the power of MYSQL and PHP in conjunction with an HTML form to

Having trouble with a basic PHP/SQL search bar for my database. The search results are not showing up even though the search bar appears on the page. When I type something, it doesn't reflect in the URL. Below is the code snippet. I am connecting to t ...

Conceal the cancellation button on the 20th and the 3rd day of each month for Woocommerce Subscriptions

Currently, I am working on customizing Woocommerce Subscriptions for a specific product (ID:1812). In the code snippet below, I have successfully hidden the 'cancel' and 'reactivate' buttons for that product. However, my goal now is t ...

PHP: Checking for IP addresses in a text file

I'm working on a way to capture the IP address of a user and save it in a text file when they pay to access specific content. Once the IP is saved in the logFile.txt, I want to redirect the paying user to an exclusive content page. Additionally, I&apo ...

What is the best way to program a function that can extract random lines from a text file and save them in a variable?

Can someone enlighten me on how to create a function that reads from a txt file and saves random lines into a variable? This function needs to be executed multiple times within a foreach loop, and the language used is PHP. I'm still new to coding, so ...

Automatically load and instantiate all classes in PHP

My current setup involves using php spl_autoload_extensions to automatically load all classes. The question I have is whether it's possible to instantiate classes simultaneously, eliminating the need for manual instantiation afterwards. Below is my b ...

Error 4 encountered when attempting to upload files using Ajax to a PHP server

On my website, there is a form that looks like this: <form style="width:100%; clear:both; margin-top:50px; background:#fff; border:1px solid green" id="upload_form" enctype="multipart/form-data" class="form" action="" method="post"> <fieldse ...

Generating and Retrieving Dynamic URL with Jquery

My web page named single-colur.html has the ability to handle various query strings, such as: single-colour.html?id=1 single-colour.html?id=2 single-colour.html?id=3 single-colour.html?id=4 The parameter id in the URL corresponds to an entry in a table c ...

Unable to establish the default timezone in PHP

After updating the date.timezone setting in my php.ini file and restarting the php5-fpm process, I noticed that the phpinfo() script still displayed the incorrect timezone: America/New_York. date.timezone = "UTC" Despite confirming that the correct ini f ...

Obtain POST information through AJAX and jQuery

post.js $.post( "/scripts/update.php", {id: testId, age: testAge}, function(data) { $(".testDiv").html(data.testId); $(".testDiv2").html(data.testAge); } ); update.php $userId = $_POST["id"]; $userAge = $_POST["age]; // contact database ...

Performing a single AJAX call from a JavaScript loop is more efficient than iterating through multiple AJAX calls

I am working with a 2D array in JavaScript. Currently, I have a for loop where I make an AJAX call to update the database. I understand that this approach is not efficient, and I am seeking a way to update the database with just one AJAX call within the ...

CodeIgniter fails to recognize any controllers in the application

My experience with CodeIgniter 3 has been challenging. I created a simple controller but encountered a 404 error when trying to access it. Here is my controller code: <?php defined('BASEPATH') OR exit('No direct script access allowed&a ...

Using PHP to extract all occurrences of window.location from an HTML document using regex

Is there a way to extract all the window.location instances in PHP? I have a list of URLs that I am fetching using cURL, saving the HTML content as a string, and now I need to identify and display all the occurrences of window.location separately. I atte ...

using if-else statements within other if-else statements in PHP

My goal is to display a graphic change on a php page based on the outcome of a mySQL database query. <?php $find_howto=mysql_query("SELECT * FROM `answers` WHERE `username`='$username' AND `pagename`='_I1' ORDER BY `answer` DESC") o ...

Use PHP shopify_call to sync and adjust the inventory in your Shopify store

I am in the process of developing a PHP-based API for Shopify to facilitate updating the inventory_quantity of a product. Below is the JSON representation of my product: "variants": [ { "id": 1234567890123, "produc ...

Getting an Error in Symfony2 "Issue with spl_object_hash() function - parameter not matching"

Whenever I attempt to save my object and execute it, a noticeable error crops up: Warning: spl_object_hash() expects parameter 1 to be an object, but instead integer was provided. This results in a 500 Internal Server Error - ContextErrorException I un ...

The function fwrite() requires the first parameter to be a resource type, but a string was provided instead in the

I am currently using the latest version of PHP, but I have encountered a specific error that I can't seem to resolve. Warning: fwrite() is expecting parameter 1 to be a resource, but it's being given a string in c:\ and this error is occurr ...

Retrieving the previous value using JQuery's onChange event

Is there a way to retrieve the initial quantity value before it is changed with the onChange function in this code snippet? I'm encountering issues with the CSS while using this setup for an input box. You can view the problematic CSS here. Updating ...

PHP is experiencing a delay of an additional second in fetching each result set from Sphinx!

After working perfectly fine the night before, I encountered a strange issue today. The problem arose after reinstalling WAMP on my local dev server and attempting to retrieve results from Sphinx using the PHP API. For testing purposes, I executed a basic ...