1

Have the following code that's executed when a script is ran. (I've just changed the login for display purposes).

<?php

    $conn = mysql_connect("localhost", "root", "pw123");



    mysql_select_db("test_db", $conn);


    $sql = "INSERT INTO test_table (fname)
    VALUES ('$fname')"; 

    mysql_query($sql);

    mysql_close($conn);


?>

I've edited the code down slightly so it doesn't show every value I'm trying to enter, but essentially, everything is entering as a blank value, or in the case of numerical inputs is defaulting to 0. I can't seem to figure out why this is. The variables are definitely not blank before hand as I've got them out putting on the web page to test as such.

For reference I assign $fname a value when the input box is changed using :

   fname = $("#fname").val();
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    please start using `mysqli_*` procedural or OOP or `PDO` as `mysql_*` is depracted and will be removed – SuperDJ Jul 12 '15 at 19:12
  • 1
    Is this a new project or you are debbuging some old code? if it's a new code i suggest you restart by using prepared statement. See https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – Louis Loudog Trottier Jul 12 '15 at 19:13
  • Where do you assign the value for `$fname`? – kittykittybangbang Jul 12 '15 at 19:13
  • How do you assign $fname a value? – M H Jul 12 '15 at 19:13
  • I have a change function that includes the following : fname = $("#fname").val(); Cheers for comments about changing code, will alter that, in mean time i can't figure out the issue described above... – David Shepherd Jul 12 '15 at 19:14
  • you will need to get the value of the fname. perhapse using `$_POST` e.g. `$fname = $_POST['fname'];` – Jaylen Jul 12 '15 at 19:19
  • Implementing your suggestion Mike still yields the same result. – David Shepherd Jul 12 '15 at 19:25
  • Hi David. We try not to edit questions to put [solved] in the title, or answers as an addendum. I've added an answer below for you instead - in future it is encouraged that you do the same yourself, and you may 'tick' that answer to show it is solved. Thanks! – halfer Jul 12 '15 at 22:17
  • 1
    Cheers man, appreciated. – David Shepherd Jul 12 '15 at 22:25

2 Answers2

0

$fname is empty in your script and you need declarate the variable before:

$fname = 'David';
$sql = "INSERT INTO test_table (fname) VALUES ('$fname')"; 

:)

Nomad Webcode
  • 816
  • 5
  • 9
0

(Posted on behalf of OP):

Solved this myself anyway, instead of executing the MySQL statements in the initial page that user enters data, I moved it to the secondary web page, which opens once a user has submitted their information.

halfer
  • 19,824
  • 17
  • 99
  • 186