Ryan Thomas King
Ryan Thomas King

Reputation: 33

PHP Form to Database

Hi I am trying to get a form to post to a database i can connect and the database and table are set up. but rather than post the contents of the fields in it posts the text firstname and secondname in to the columns.

below is my code:

mysql_select_db("company", $conn);

    $sqlCmd = sprintf("INSERT INTO names (firstname, secondname) VALUES ('%firstname','%secondname')", 
        mysql_real_escape_string($_POST["firstname"]),
        mysql_real_escape_string($_POST["secondname"]));

    //echo $sqlCmd;
    //die();    

    mysql_query($sqlCmd);

    mysql_close($conn);
}

?>



    <form method="post">
<input type="text" id="firstname" name="firstname"/>
<input type="text" id="secondname" name="secondname"/>
    <input name="submit" type="submit" value="Submit"/>
</form>

I need it to post the values from the fields. i am new to php and this is my first project, i would love some help.

just to add this is what i have managed after following a tutorial.

Thanks

Ryan

Upvotes: 1

Views: 385

Answers (2)

TheNiceGuy
TheNiceGuy

Reputation: 3730

Do not use php's mysql_ methods any more.

It is outdated: https://wiki.php.net/rfc/mysql_deprecation

Use mysqli_ or pdo instead

In your code you forgot the mysql_connect() anyways ;)

Upvotes: 1

Nick Dickinson-Wilde
Nick Dickinson-Wilde

Reputation: 1015

Just change your sprintf call to:

$sqlCmd = sprintf("INSERT INTO names (firstname, secondname) VALUES ('%s','%s')", 
    mysql_real_escape_string($_POST["firstname"]),
    mysql_real_escape_string($_POST["secondname"]));

Also consider using the newer mysqli function: http://www.php.net/manual/en/intro.mysqli.php

HTH; Pacific

Upvotes: 0

Related Questions