-2
<?php

if (isset($_GET['firstname'])){
    $fname = $_GET['firstname'];
}

mysql_query("UPDATE student SET firstname = $fname WHERE studentID = $id");

?>

I have a form that will update my database. At the bottom of the form there is a update button. When I use this code it does not work.

I can put in a "tom in where it says $fname in my mysql_query and it will update.

I can also echo out the $fname variable and it will echo out what is in the form correctly.

But I cannot get the database to take the $fname.

Any suggestions would be great, thanks.

Riley Bracken
  • 5,959
  • 2
  • 16
  • 17
  • 1
    Are you setting the $id anywhere on the page before updating the database? – sbeliv01 Nov 30 '12 at 15:04
  • Don't use `mysql_*`, as it is deprecated. Use prepared queries to separate the data from your query. As it stands right now, you are **wide open** to SQL injection and **will be hacked** if you haven't been already. Consider prepared queries with PDO or similar. Finally, never do an UPDATE with the GET verb. Any crawler will hit this and update your database. At least use POST. – Brad Nov 30 '12 at 15:04
  • Relevant: http://thedailywtf.com/Articles/The_Spider_of_Doom.aspx – Marc B Nov 30 '12 at 15:11
  • NO BOBBY TABLES... NOOOOOO! http://xkcd.com/327/ – feathj Nov 30 '12 at 15:21

2 Answers2

2

You forgot the quotes around the name:

mysql_query("UPDATE student SET firstname = '$fname' WHERE studentID = $id");

BTW your code is vurnerable to SQL injections. Please fix that problem. See best-way-to-prevent-sql-injection-in-php

Community
  • 1
  • 1
juergen d
  • 201,996
  • 37
  • 293
  • 362
  • I had '$fname' in there before and forgot to put it back in when I posted, but even when I do that it does not work. I will have to look into the injections, I'm 4 months into coding with PHP and MYSQL. – Riley Bracken Nov 30 '12 at 15:10
  • @user1770189: sql injection prevention is a day 0 thing in ANY language. it's not something you leave until later. – Marc B Nov 30 '12 at 15:12
  • Try using PDO or MSQLI. Probably the problem will be solved then too. – juergen d Nov 30 '12 at 15:12
1

You are missing single quotes around $fname and $id(if its a string),

mysql_query("UPDATE student SET firstname = '$fname' WHERE studentID = '$id'");

Note: Mysql_* extensions are deprecated, and are open to SQL injection. So, avoid using them. Use PDO or Mysqli_* instead.

Teena Thomas
  • 5,139
  • 1
  • 13
  • 17