我正在努力找出为什么这段代码不适合我。我有表格:albums (albumid, albumname)
,composers (composerid, composername)
和tracks (trackid, tracktitle, albumid, composerid)
。
当我使用表单添加曲目并将其链接到作曲家和相册时:
<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['composerid'];
$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['albumid'];
$aname = htmlspecialchars($alb['albumname']);
echo "<label><input type='checkbox' name='albs[]'
value='$aid' />$aname</label><br />\n";
} ?>
</p>
<input type="submit" value="SUBMIT" />
</form>
<?php endif; ?>
我收到此消息:
新曲目添加了 将曲目插入专辑2时出错:
曲目已添加到0张专辑中。
表单前面的php代码是:
if (isset($_POST['tracktitle'])):
// A new track has been entered
// using the form.
$tracktitle = mysql_real_escape_string($tracktitle);
$cid= $_POST['cid'];
$tracktitle = $_POST['tracktitle'];
$albs = $_POST['albs'];
if ($cid == '') {
exit('<p>You must choose an composer for this track. Click
“返回”并重试。
');}
$sql = "INSERT INTO tracks (tracktitle)
VALUES ('$tracktitle')" ;
if (@mysql_query($sql)) {
echo '<p>New track added</p>';
} else {
exit('<p>Error adding new track' . mysql_error() . '</p>
echo mysql_error() ');}
$trackid = mysql_insert_id();
if (isset($_POST['albs'])) {
$albs = $_POST['albs'];
} else {
$albs = array();
}
$numAlbs = 0;
foreach ($albs as $albID) {
$sql = "INSERT IGNORE INTO tracks (trackid, albumid,
composerid) VALUES " .
"($trackid, $albs, $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>
<?php
else: // Allow the user to enter a new track
$composers = @mysql_query('SELECT composerid, composername
FROM composers');
if (!$composers) {
exit('<p>Unable to obtain composer list from the database.</p>');
}
$albs = @mysql_query('SELECT albumid, albumname FROM albums');
if (!$albs) {
exit('<p>Unable to obtain album list from the database.</p>');}?>
我一直在寻找为什么会失败,我一直在打砖墙。我也知道,目前它不是很安全,这将是我接下来要解决的问题。我只想让实际的功能先工作。
答案 0 :(得分:2)
@paj:改变
if ($ok) {
到
if (mysql_query($sql)) {
-
我还建议您将SQL语句更新为
$sql = "INSERT INTO tracks (tracktitle) VALUES ('" . $tracktitle . "')";
$sql = "INSERT IGNORE INTO tracks (trackid, albumid, composerid) VALUES (" . $trackid . ", " . $albID . ", " . $cid . ")";
答案 1 :(得分:1)
我认为$ok
除if ($ok) {
外不存在
线。它需要先在某处定义,否则它将始终读为false,因为它不存在。
实际上你可以跳过不存在的$ ok,并像上面一样放入if (@mysql_query($sql)) {
。我不得不同意代码需要一些爱的评论,但是如果你想知道为什么它会崩溃,那么这就是原因。