ledar
ledar

Reputation: 5

PHP MySQL Query Insert consistent error

//--------------------------------------------------------------------------
// php script for adding data from mysql database
//--------------------------------------------------------------------------

$ip = $_GET['ip']; //for debugging sake, will be POST from Ajax
$key = substr(md5(microtime()),rand(0,26),5); //random referral ID - will implement exist analysis
echo $ip; //debugging
$dbhost = 'localhost';
$dbuser = user;
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("database", $conn);
$tbl_name = "refs";
$sql="INSERT INTO $tbl_name(ip, key)VALUES('frfr', 'grgr')";

if (!mysql_query($sql,$con)) {
    die('Error: ' . mysql_error());
}
echo "1 record added";

I'm not sure if it's my Digital Ocean server or what, but the only syntax my PhpMyAdmin will accept as a query is as INSERT INTOrefs(ip,key) VALUES ("insert","432") with the double quoted values. I cannot seem to get this implemented in the PHP without getting a flat out error or an Unknown column in 'field list' error.

Similar questions suggest junk non-printable characters from copy-paste, however I've retyped my code within the editor. Thanks for all the help

I'm creating a basic referral system by the way, storing requested IP's in 'refs' table with a key, or id.

Upvotes: 0

Views: 480

Answers (1)

Rahul
Rahul

Reputation: 77876

key is a reserve word and thus needs to be escaped using backtique. Along with that you have spacing issue as well. Your query should looks like below

INSERT INTO refs(ip,`key`) VALUES ('insert','432')

Never use a reserve word as column or table name. if in doubt, then escape all the columns present in query.

Start referring MySQL Documentation for more inforamtion. It's way easier than posting it as question in stackoverflow.

Upvotes: 3

Related Questions