编辑:我尝试了来自 PhpMyAdmin 的 INSERT INTO。我注意到如果我只是做 GenreName 而没有输入 ID,AutoIncrement 会给我一个行 ID 2147483647 : INSERT INTO Genres( GenreName ) VALUES ('testFromPhpmyAdmin')
我之前在直接在 MySQL 数据库中工作时遇到过这样的错误,但是我从过去的错误中尝试的所有方法都不起作用。我已经用尽了尽可能多的 StackOverflow 帖子,但没有一个解决方案最终奏效。我确实检查了两个表中的 ID 是否可用。此外,当我的页面只是有一个带有 AlbumID 和 AlbumName 文本输入的表单时,它起作用了,但我想摆脱 AlbumID 的文本条目,因为它在 MySQL DB 中自动递增,因此用户不必键入/猜测新的ID。
错误:SQL 错误:Errno:1452 错误:无法添加或更新子行:外键约束失败 ( andrew79_601
. Albums
, CONSTRAINT Albums_ibfk_2
FOREIGN KEY ( ArtistID
) REFERENCES Artists
( ArtistID
))
当我在我的 addalbum.php 页面上时会发生这种情况。这是我正在使用的代码: addalbum.php
<?php
//Get All genre
include 'dbconnect.php';
$sql_genre = "SELECT GenreID FROM Genres";
$genre_data = $mysqli->query($sql_genre);
// Get all artists
$sql_artist = "SELECT ArtistID FROM Artists";
$artists_data = $mysqli->query($sql_artist);
?>
<form action="addalbumssrv.php" method="post">
<!-- AlbumID:<input type="text" name="AlbumID" id="AlbumID"/></br> -->
Album Name:<input type="text" name="AlbumName" id="AlbumName"/></br>
<div>
<div class="dev-left">Genre ID: </div>
<div class="dev-left">
<?php if ($genre_data->num_rows > 0) { ?>
<select name="genre" style="width: 150px;">
<option value="">------Select-------</option>
<?php while ($row = $genre_data->fetch_assoc()) {
?>
<option value="<?php echo $row['ID']; ?>">
<?php echo $row['GenreID']; ?>
</option>
<?php }
?>
</select>
<?php
} else {
echo 'No Genre ID Found';
}
?>
</div>
</div>
<!--Artist drop down-->
<div>
<div class="dev-left">Artist ID: </div>
<div class="dev-left">
<?php if ($artists_data->num_rows > 0) { ?>
<select name="artist" style="width: 150px;">
<option value="">------Select-------</option>
<?php while ($row = $artists_data->fetch_assoc()) {
?>
<option value="<?php echo $row['ID']; ?>">
<?php echo $row['ArtistID']; ?>
</option>
<?php }
?>
</select>
<?php
} else {
echo 'No Artist ID Found';
}
?>
</div>
</div>
<input type="submit"/>
</form>
addalbumssrv.php:
<?php
//include 'dbconnect.php';
$link = new mysqli('127.0.0.1', 'andrew79_601', 'csis601', 'andrew79_601');
if ($link->connect_errno) {
echo "Error: Failed to make a MySQL connection, here is why: </br>";
echo "Errno: " . $link->connect_errno . "</br>";
echo "Error: " . $link->connect_error . "</br>";
exit;
}
// Escape user inputs for security
$AlbumID = mysqli_real_escape_string($link, $_REQUEST['AlbumID']);
$AlbumName = mysqli_real_escape_string($link, $_REQUEST['AlbumName']);
// attempt insert query execution
//$sql = "INSERT INTO Albums (AlbumID, AlbumName) VALUES ('$AlbumID', '$AlbumName')";
$sql = "INSERT INTO Albums (AlbumName) VALUES ('$AlbumName')";
if (!$result = $link->query($sql)) {
echo "Error: SQL Error: </br>";
echo "Errno: " . $link->errno . "</br>";
echo "Error: " . $link->error . "</br>";
exit;
}
?>
<script>
window.location='albums.php';
</script>
表结构:http: //imgur.com/xziavSk