Kevin G
Kevin G

Reputation: 119

Adding records into a database from an html form

I am trying to add records into a database from a simple html form that I have created. I keep on getting this error:

connected succesfullyError: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1

the connection is successful but something is wrong with the sql statement and I haven't been able to spot the error.

This is the form

 <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"/>

This is the connection

     <?php

define('DB_NAME', 'syokimaufc');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

if (!$link) {
    die ('could not connect: '. mysql_error());
}
$db_selected= mysql_select_db(DB_NAME, $link);
if (!$db_selected){
    die('can\'t use' . DB_NAME .': ' . mysql_error());
}
echo 'connected successfully';

implementation

<?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');

$sql = "INSERT INTO players (playerid,Name,Age,Position,Nationslity) VALUES ('$id','$name','$age','$position',$nationality)";

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

Upvotes: 2

Views: 50

Answers (1)

Ben Shoval
Ben Shoval

Reputation: 1752

Change:

$sql = "INSERT INTO players (playerid,Name,Age,Position,Nationslity) VALUES ('$id','$name','$age','$position',$nationality)";

To:

$sql = "INSERT INTO players (playerid,Name,Age,Position,Nationality) VALUES ('$id','$name','$age','$position','$nationality')";

UPDATE As Jeff Puckett II correctly pointed out in the comment section below, I gave my initial answer hastily and should have mentioned that you're opening yourself up to SQL injection and other nasty problems by not sanitizing your data.

To do things more safely, change:

$sql = "INSERT INTO players (playerid,Name,Age,Position,Nationslity) VALUES ('$id','$name','$age','$position',$nationality)";

To:

$_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' )";

Upvotes: 1

Related Questions