dongyin0628
dongyin0628
2012-01-06 14:31

在SQL字符串中使用$变量?

已采纳

I would like to be able to select a category from a dropdown and depending on the category it will add it to whatever SQL table is it equal with.

<?php

$article = $_POST['article'];

$con = mysql_connect("******","******","*******");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("jstaltso_staltsoft", $con);

$sql="INSERT INTO $article (headline, content)
VALUES ('$_POST[headline]', '$_POST[content]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "Content Added!";
echo "<br/>";
echo "<a href='articles.php'><- Back</a>";

mysql_close($con)

?>

I want the variable $articles to be in the place of where you out the name of the table.

$sql="INSERT INTO $article (headline, content)
VALUES ('$_POST[headline]', '$_POST[content]')";

So whatever I choose in the dropdown, it will put it at $articles.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doukanzhuo4297 doukanzhuo4297 9年前

    Try:

    "INSERT INTO `{$article}` ...."
    

    Don't forget to sanitize your input! (mysql_real_escape_string, for starters)

    点赞 评论 复制链接分享
  • dongle7553 dongle7553 9年前

    I know this answer won't be too helpful for you right now, but sice there is just too much wrong with that code and that approach, here are a few tips:

    • Use PDO instead of PHP's MySQL functions. It'll seem daunting at first, especially if you haven't got any experience with object-oriented programming, but it's definately worth the effort.
    • Sanitize that $article value! if($article == 'foo' || $article == 'bar') {...}
    • The best ways to use variables in strings are: "This is a ".$adjective." string" and "This is a {$adjective} string"
    点赞 评论 复制链接分享
  • doujiabing1228 doujiabing1228 9年前

    You cannot use that type of variables, change last code to $sql="INSERT INTO $article (headline, content) VALUES ('" . $_POST['headline'] " . ', '" . $_POST['content'] . "')";

    点赞 评论 复制链接分享