简体   繁体   English

如何为此SQL查询更正我的PHP代码?

[英]How can I correct my PHP code for this SQL query?

I've been messing with this for a while and I'm nearly there. 我已经弄了好一阵子,我快到了。 Just need to get past this wall I've hit. 只需要穿过我碰到的那堵墙。

I have the following tables: 我有以下表格:

tracks (trackid, tracktitle, albumid, composerid)
albums (albumid, albumname)
composers (composerid, composername)

I can insert a new record via PhpMyAdmin SQL tab with 我可以通过PhpMyAdmin的“ SQL”选项卡使用

INSERT INTO tracks (tracktitle, albumid, composerid) VALUES ('New Song', 1, 1);

and it works fine. 而且效果很好。

My PHP form though isn't doing the same thing and I must have overlooked something. 我的PHP表单虽然没有做相同的事情,但我一定忽略了一些事情。 Please can someone check out the code for my addtrack page and tell me what is wrong? 有人可以检出我的addtrack页面的代码,然后告诉我哪里出了问题吗?

 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 tracks SET
  tracks.tracktitle='$tracktitle'" ;
  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 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>

 <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 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>');
 }
 ?>

 <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";
    }
   ?>

Once I have this sorted, I can move on to expanding it and also sorting out the security issues. 排序后,我可以继续扩展它,并解决安全问题。 Someone on here recommended I look into PDO's which are a new thing to me. 有人建议我研究PDO对我来说是新事物。 But one hurdle at a time.... 但是一次一个障碍。

Thanks 谢谢

Your INSERT syntax is incorrect. 您的INSERT语法不正确。 You are trying to INSERT using an UPDATE syntax. 您正在尝试使用UPDATE语法插入。

You are trying: 你在尝试:

INSERT INTO table_name SET field_name = '$value', another_field_name = '$another_value'

But you should be doing: 但是您应该这样做:

INSERT INTO table_name (
    field_name,
    another_field_name
)
VALUES (
    '$value',
    '$another_value'
)

Also, you really should be using addslahes(), like this: 另外,您实际上应该使用addslahes(),如下所示:

INSERT INTO table_name (
    field_name,
    another_field_name
)
VALUES (
    '".addslashes($value)."',
    '".addslashes($another_value)."'
)

Otherwise your code is easier to hack than a boiled potato. 否则,您的代码比煮土豆更容易被黑。 :) :)

EDIT: Chad Birch (below) suggests rather using parameterized values, which admittedly is better than addslashes(). 编辑:查德·伯奇(Chad Birch)(下)建议使用参数化值,这显然比addlashes()更好。 I honestly didn't know PHP had those already. 老实说,我不知道PHP已经有了。

The problems are in your queries. 问题出在您的查询中。 Try using mysql_error function to get extra information on what you are doing wrong. 尝试使用mysql_error函数获取有关您做错了什么的更多信息。

As an example your INSERT statement is malformed. 例如,您的INSERT语句格式不正确。

You have: 你有:

$sql="INSERT INTO tracks SET tracks.tracktitle='$tracktitle'"

It should be something like: 应该是这样的:

$sql="INSERT INTO tracks (tracktitle) VALUES ('$tracktitle')";

My previous answer was wrong (and is deleted). 我之前的回答是错误的(已删除)。 I've learned now that your Insert syntax is indeed valid. 现在我了解到您的插入语法确实有效。

But what you don't do, is escape the value you put in the query. 但是,您不执行的操作是转义您在查询中输入的值。 If $tracktitle contains any invalid characters, like a single quote, it could break your query. 如果$ tracktitle包含任何无效字符(如单引号),则可能会中断查询。

You should add this line before building your insert query: 您应该在构建插入查询之前添加以下行:

$tracktitle = mysql_real_escape_string($tracktitle);

You current code is very dangarous. 您当前的代码非常琐。 If I was to insert a song, and in the song name I would type YourF...ed, oh by the way'; 如果要插入一首歌曲,并且要在歌曲名称中输入YourF ... ed,哦,顺便说一句。 drop database YourDataBaseName; 删除数据库YourDataBaseName; you should try to imagine what happens.. 您应该尝试想象会发生什么。

This is known as SQL-injection. 这称为SQL注入。 Because you don't correctly escape the value, someone else can close the statment en start a new statement by just inserting it into a html form field. 因为您没有正确地转义该值,所以其他人可以通过将陈述插入到html表单字段中来关闭该陈述。

I don't know if this is the reason that your query doesn't work right now (it only breaks if you type an invalid character), but it is a serious problem at the moment. 我不知道这是否是您的查询现在不起作用的原因(仅当您键入无效字符时它才会中断),但是目前这是一个严重的问题。

To find out your exact error, you should display the results of mysql_error() when mysql_query() returns false. 为了找出确切的错误,当mysql_query()返回false时,应该显示mysql_error()的结果。 This will probably help you more than any random guesses we can make here. 这可能比我们在这里所做的任何随机猜测都对您有更大的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM