PDA

View Full Version : Script won't insert into db


Rollo Tamasi
07-05-06, 02:55 PM
This is an excerpt from a script i have which is causing me problems. The form field 'category' is not been inserted into the database for some reason and i can't figure out why

<?php

include 'db.php';

if (isset($_POST['submit'])) {

$sql = "INSERT INTO php_blog (category) VALUES ('$category')";

$result = mysql_query($sql) or print("Can't insert into table php_blog.<br />" . $sql . "<br />" . mysql_error());

if ($result != false) {
print "Your entry has successfully been entered into the database.";
}

// mysql_close();
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

<select name="select" id="category">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit" name="submit" id="submit" value="Submit">

</form>

nova912
07-05-06, 03:00 PM
Are you getting a die() error or a mysql_error() ?

Nico
07-05-06, 03:14 PM
The variable $category is nowhere set. You have a select with the id "category" and name "select". Which won't do anything, even if you have register globals on.

Change

<select name="select" id="category">


To

<select name="category" id="category">


And add


$category = $_POST['category'];


before creating the sql string.



Oh, and moving topic to database...

duesi
07-05-06, 03:20 PM
Maybe print out what $sql looks prior to the execution.


Something else:
You have absolutely no control over what the user submitted.
If I go there, and set $category to


whatever') ; DROP TABLE php_blog; --


You might loose your table.
(Notice that my -- comments out your closing bracket - therefore it is syntactically correct.)

That is one reason why I never put sql code directly into the code.
I would put all SQL stuff into a separate class, which makes sure that the user is not tampering with the query (checking for DELETE, UPDATE, INSERT, ; ...

Happy coding!