NizeGuy NizeGuy - 1 year ago 82
SQL Question

Use a $variable inside a SQL string?

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.


$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>";



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.

Answer Source


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download