2013-03-01 103 views
0

我嘗試使用php和html寫入mysql數據庫。提交表格後,我得到的錯誤SQL語法錯誤整數

MySQL error: 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 '', '1', '1362154007', '127.0.0.1'' at line 2

在提交的PHP文件中的代碼是

<?php 
require 'connection.php'; 
$ip = $_SERVER['REMOTE_ADDR']; 
$sql="INSERT INTO entries (summoner, role, level, time, ip) 
VALUES ('" . mysql_real_escape_string($_POST['summoner']) . "', " . mysql_real_escape_string($_POST['role']) . "', '" . intval($_POST['level']) . "', '" . time() . "', '" . $ip . "'"; 
if (!mysql_query($sql)) die("MySQL error: " . mysql_error()); 
echo "1 record added"; 
?> 

和代碼行二是

<?php 
$con = mysql_connect("localhost", "ratchet132", "password", "lookingforq") or die(mysql_error()); 
mysql_select_db("lookingforq", $con) or die(mysql_error()); 
header("Content-Type: text/html; charset=utf-8"); 
mysql_set_charset("utf8"); 
mb_internal_encoding("UTF-8"); 
?> 

誤差只有整數發生不是由html表單提交的(儘管級別是由它提交的,但似乎是由於與其他人相同的原因,而不是表單)。我想這可能是一個錯誤,我如何設置我的MYSQL表,但我無法弄清楚我做錯了什麼。任何幫助都是極好的。

+0

您在角色前沒有''''。 – str 2013-03-01 16:14:37

+0

[**請不要在新代碼中使用'mysql_ *'函數**](http://bit.ly/phpmsql)。他們不再被維護[並且被正式棄用](http://j.mp/XqV7Lp)。看到[**紅框**](http://j.mp/Te9zIL)?學習[*準備的語句*](http://j.mp/T9hLWi),並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [這篇文章](http://j.mp/QEx8IB)將幫助你決定哪個。 – Kermit 2013-03-01 16:21:49

回答

1

有你的整數值額外的單引號,

​​

我的建議是價值首先存儲在變量,所以很容易調試代碼,例如

$summoner = mysql_real_escape_string($_POST['summoner']); 
$role = mysql_real_escape_string($_POST['role']); 
$intV = intval($_POST['level']); 
$sTime = time(); 
$ip = $_SERVER['REMOTE_ADDR']; 
$sql="INSERT INTO entries (summoner, role, level, time, ip) 
     VALUES ('$summoner', $role, $intV, $sTime,'$ip')')"; 

使用PDOMySQLi擴展名,以便您可以參數化查詢。下面的鏈接談到了SQL Injection,但它也顯示了PDOMySQLi擴展的用法。

+0

現在我得到這個: 'MySQL錯誤:您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以在第2行'',1','1362154579','127.0.0.1'附近使用正確的語法。 – ratchet132 2013-03-01 16:17:04

+0

@ user2124235查看我的更新。 – 2013-03-01 16:19:44

+1

這裏只有***解決方案是使用綁定參數和準備語句。這是解決方案最接近的答案。 – Kermit 2013-03-01 16:22:32

0

你爲什麼用引號括int值?

'" . intval($_POST['level']) . "' 
0

你缺少一個'。嘗試:

$sql="INSERT INTO entries (summoner, role, level, time, ip) 
VALUES ('" . mysql_real_escape_string($_POST['summoner']) . "', '" . mysql_real_escape_string($_POST['role']) . "', '" . intval($_POST['level']) . "', " . time() . ", '" . $ip . "'"; 
+0

這讓我在某個地方! :D它解決了這個問題,但現在它說 'MySQL錯誤:你的SQL語法有錯誤;檢查與您的MySQL服務器版本相對應的手冊,在第2行''附近使用正確的語法。 我想有一個額外的逗號或導致它的東西?我找不到它,儘管 – ratchet132 2013-03-01 16:21:03

+0

從'time()'中刪除了''''。現在試試。沒有看到您的數據庫設置很難說。 – SeanWM 2013-03-01 16:31:23