在我的PHP查询中收到错误

时间:2011-01-06 12:42:03

标签: php mysql

我在php查询中收到错误消息。

显示错误: 您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第2行“1294251744”,“127.0.0.1”,“/ register”附近使用正确的语法

我的代码:

<?php 
require_once("includes/database.php"); 

//Set timeout to 5 minutes
$timeoutseconds  =  300 ;

//get the time 
$timestamp  =  time();
//Delete all users that are no online after the time out allowed
$timeout  =  $timestamp - $timeoutseconds ;

// stores users IP addresss 
$user_ip = $_SERVER['REMOTE_ADDR'];
// Automatically collects the hostname or domain  like example.com) 
$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path   = rtrim(dirname($_SERVER['PHP_SELF']), '/');

//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
            VALUES (''$timestamp','$user_ip','$path')";

    $result = mysql_query($sql, $conndb) or die(mysql_error());


//delete values when they leave
mysql_query("DELETE FROM totalonline WHERE timestamp < $timeout");

//grab the results
$sql = "SELECT DISTINCT ip FROM totalonline WHERE file='$path' ";

    $result = mysql_query($sql, $conndb) or die(mysql_error());

//number of rows = the number of people online 
    $user = mysql_num_rows($result);


//spit out the results 

if( $user  ==  1 ) { 
echo "$user User online"; 
} else { 
echo "$user User online"; 
} 

?>

2 个答案:

答案 0 :(得分:3)

改变这个:

//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
            VALUES (''$timestamp','$user_ip','$path')";

到此:

//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
            VALUES ('$timestamp','$user_ip','$path')";

你有两个单引号而不是一个。


此外,接近结束时,您可能想要更改此内容:

if( $user  ==  1 ) { 
echo "$user User online"; 
} else { 
echo "$user User online"; 
}

到此:

if( $user  ==  1 ) { 
echo "$user User online"; 
} else { 
echo "$user User offline"; 
} 

答案 1 :(得分:1)

你在值字段中有两个')

//insert the values
$sql = "INSERT INTO totalonline(timestamp, ip, file)
            VALUES (''$timestamp','$user_ip','$path')";

在$ timestamp之前。

最好做

//insert the values
$sql = 'INSERT INTO totalonline(timestamp, ip, file)
            VALUES ('.$timestamp.',"'.$user_ip."',"'.$path.'")';

因为这样你可以确保db理解ip和path是字符串。