Kevin G Kevin G - 4 months ago 9
PHP Question

Adding records to a database using a html form

Having trouble populating my database usning a html form. Once i run the code the webpage outputs "Completed successfully" but the record does not display. It seems like its entering null values for each of the fields because when i try to enter another record, i'm getting this error "connected successfully Error: Duplicate entry '0' for key 'PRIMARY'" How can i solve this?

<form action="addplayer.php"method "post"/>

<p> id: <input type="text" name="playerid"/></p>
<p> Name: <input type="text" name="name"/></p>
<p> Age: <input type="text" name="age"/></p>
<p> Position: <input type="text" name="position"/></p>
<p> Nationality: <input type="text" name="nationality"/></p>
<input type="submit" value="submit"/>


?php
require 'connection.php';


$id = filter_input(INPUT_POST, 'playerid');
$name = filter_input(INPUT_POST, 'name');
$age = filter_input(INPUT_POST, 'age');
$position = filter_input(INPUT_POST, 'position');
$nationality = filter_input(INPUT_POST, 'nationality');

$_id = mysql_real_escape_string( $id );
$_name = mysql_real_escape_string( $name );
$_age = mysql_real_escape_string( $age );
$_position = mysql_real_escape_string( $position );
$_nationality = mysql_real_escape_string( $nationality );
$sql = "INSERT INTO players ( playerid, name, age, position, nationality )
VALUES ( '$_id', '$_name', '$_age', '$_position', '$_nationality' )";

if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}

Answer

You need to add id to the input:

<p> id: <input type="text" name="playerid" id="playerid"/></p>

collect the data like this:

$playerID = mysql_real_escape_string($_POST['playerid'])

$sql = "INSERT INTO players
        SET
        playerID = '".$playerID."',
        ........";
Comments