0

我现在正在学习 PHP 和 MySQL。我正在尝试一个简单的页面,我可以在其中提交一条短消息,并从服务器检索一条消息(对于这种特殊情况只是一个随机数)。

<?php

$success = false;

require_once '../../../phpIncludes/mysqlIncludes.php';
require_once '../../../phpIncludes/iphandler.php';
$creds = new MySQLLoginCredentials;
$con = $creds->ConnectToDB();

mysql_select_db("testDB", $con);

$userMsg = trim($_POST['msg']);
//The simple version for 128 Characters from the beginning of the string
$userMsg = substr($userMsg,0,128);
$userMsg = filter_var($userMsg, FILTER_SANITIZE_STRING,!FILTER_FLAG_STRIP_LOW);

$ip = encode_ip( $_SERVER['REMOTE_ADDR'] );

$time = time();

$returnMsg = "". rand() . "";

$userAgent = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
//Trim to 256 since that is largest db can hold
$userAgent = substr($userAgent,0,256);
$userAgent = filter_var($userAgent, FILTER_SANITIZE_STRING);

//Debug 
echo "Time : " . $time . "<br>"
. " IP: " . $ip . " | " . decode_ip($ip) . "<br>"
. " UserAgent: " . $userAgent . "<br>"
. " Msg: " . $userMsg . "<br>"
. " Return: " . $returnMsg . "<br>";

$sql = "INSERT INTO TestMessageTbl (TimeStamp, IPAddress, ClientInfo, IncMsg, OutMsg)
VALUES ('" . $time . "', " . $ip . ", " . $userAgent . ", " . $userMsg . ", " . $returnMsg .")";

$success = mysql_query($sql, $con);

if($success == false)
{
    echo "Error: " . mysql_error();
}

echo $returnMsg;

mysql_close($con);
?>

输出是:

<i>Time : 1356919336
IP: * | *
UserAgent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko)     Chrome/23.0.1271.97 Safari/537.11
Msg: 
Return: 743166102
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 '(Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.' at line 2743166102</i>

该表如下所示:

UID bigint(20) unsigned, AUTO_INCREMENT
TimeStamp bigint(20) unsigned
IPAddress varchar(32) utf8_general_ci
ClientInfo varchar(256) utf8_general_ci
IncMsg varchar(128) utf8_general_ci
OutMsg varchar(128) utf8_general_ci

我从mysql手动转录,以防有错别字......

让我立即感到奇怪的是错误的非常大的行号。那是怎么回事?

PS 我知道就目前而言,$msg 将是空白的

4

1 回答 1

2

用简单的报价包装你的所有价值观

$sql = "INSERT INTO TestMessageTbl (TimeStamp, IPAddress, ClientInfo, IncMsg, OutMsg)
VALUES ('" . $time . "', '" . $ip . "', '" . $userAgent . "', '" . $userMsg . "', '" . $returnMsg ."')";
于 2012-12-31T02:21:35.367 回答