我在将数据插入表格时遇到问题。 我有以下表格:track(id,tracktitle),album(id,albumtitle),composer(id,composername),albumtrack(PRIMARY:trackid,albumid,composerid)。
我的PHP页面允许您添加曲目,然后选择与其相关的专辑和作曲家。它可以将曲目添加到曲目表中,但不会将其添加到专辑中。
我一直在四处寻找如何去做,而且我一点都不知所措。 任何人都可以告诉我应该如何正确地做到这一点? 感谢
if (isset($_POST['tracktitle'])):
// A new track has been entered
// using the form.
$cid= $_POST['cid'];
$tracktitle = $_POST['tracktitle'];
$albs = $_POST['albs'];
if ($cid == '') {
exit('<p>You must choose an composer for this track. Click "Back" and try again.</p>'); }
$sql = "INSERT INTO track, albumtrack SET
track.tracktitle='$tracktitle', albumtrack.albumid='$albs', albumtrack.composerid='$cid' " ;
if (@mysql_query($sql)) {
echo '<p>New track added</p>';
} else {
exit('<p>Error adding new track' . mysql_error() . '</p>');
}
$trackid = mysql_insert_id();
if (isset($_POST['albs'])) {
$albs = $_POST['albs'];
} else {
$albs = array();
}
$numAlbs = 0;
foreach ($albs as $albID) {
$sql = "INSERT IGNORE INTO albumtrack
SET albumtrack.trackid='$trackid', albumtrack.albumid='$albs', albumtrack.composerid='$cid'";
if ($ok) {
$numAlbs = $numAlbs + 1;
} else {
echo "<p>Error inserting track into album $albID: " .
mysql_error() . '</p>';
}
}
?>
<p>Track was added to <?php echo $numAlbs; ?> albums.</p>
<p><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Add another track</a></p>
<p><a href="tracks.php">Return to track search</a></p>
<?php
else: // Allow the user to enter a new track
$composers = @mysql_query('SELECT id, composername FROM composer');
if (!$composers) {
exit('<p>Unable to obtain composer list from the database.</p>');
}
$albs = @mysql_query('SELECT id, albumtitle FROM album');
if (!$albs) {
exit('<p>Unable to obtain album list from the database.</p>');
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Enter the new track:<br />
<textarea name="tracktitle" rows="1" cols="20">
</textarea></p>
<p>Composer:
<select name="cid" size="1">
<option selected value="">Select One</option>
<option value="">---------</option>
<?php
while ($composer= mysql_fetch_array($composers)) {
$cid = $composer['id'];
$cname = htmlspecialchars($composer['composername']);
echo "<option value='$cid'>$cname</option>\n";
}
?>
</select></p>
<p>Place in albums:<br />
<?php
while ($alb = mysql_fetch_array($albs)) {
$aid = $alb['id'];
$aname = htmlspecialchars($alb['albumtitle']);
echo "<label><input type='checkbox' name='albs[]' value='$aid' />$aname</label><br />\n";
}
?>
答案 0 :(得分:1)
您的插入句子错误:
试试这个:
$sql = "INSERT IGNORE INTO albumtrack (trackid, albumid, composerid) values " .
"($trackid, $albs, $cid)";
假设您的 ID 是数字。
当您注入从请求中获得的非清理值时,请注意SQL注入。
答案 1 :(得分:0)
除了Pablo更正的编写查询的方式。我还注意到你试图一次插入两个表:
$sql= "INSERT INTO track, albumtrack"
MySQL不允许一次插入两个表。