简体   繁体   中英

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

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. Please can someone check out the code for my addtrack page and tell me what is wrong?

 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. But one hurdle at a time....

Thanks

Your INSERT syntax is incorrect. You are trying to INSERT using an UPDATE syntax.

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:

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(). I honestly didn't know PHP had those already.

The problems are in your queries. Try using mysql_error function to get extra information on what you are doing wrong.

As an example your INSERT statement is malformed.

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.

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'; drop database YourDataBaseName; you should try to imagine what happens..

This is known as SQL-injection. 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.

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. This will probably help you more than any random guesses we can make here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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