Mysql没有插入定义的值

时间:2011-05-15 23:04:26

标签: mysql session

session_start(); 
    if(!$_SESSION['user_id'])
    { 
    $_SESSION['user_id'] = rand(1, 1000000); 


    include 'database_connect.php';

mysql_query('INSERT INTO product_views (user_session_id) 
             VALUES 
           ('.$_SESSION['user_id'].')'); 

         } 

$productid = $_GET['name'];

   $query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].''; 
   $result = mysql_query($query); 

  while ($row = mysql_fetch_array($result))
{ 

mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE                  user_session_id="'.$_SESSION['user_id'].'"');


}

我的字段modelNumber设置为null,我通过上一个查询执行更新。 您认为由于默认值为null,因此不允许插入吗?

我的表结构:

CREATE TABLE `product_views` (
  `id` int(10) DEFAULT NULL,
  `user_session_id` int(11) DEFAULT NULL,
  `product_id` varchar(100) DEFAULT NULL,
  `view_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `modelNumber` varchar(...

1 个答案:

答案 0 :(得分:2)

我很困惑:

$query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].''; 
$result = mysql_query($query);

while ($row = mysql_fetch_array($result))
{ 
  mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE                  user_session_id="'.$_SESSION['user_id'].'"');    
}

如果您甚至没有使用$row

,为什么要循环浏览此结果集?

修改 :我认为这是您真正想要做的事情:

session_start(); 
if(!$_SESSION['user_id'])
{
  // Get the user ID
  $_SESSION['user_id'] = rand(1, 1000000); 
  require_once('database_connect.php');

  // Get the model number and escape it to prevent SQL injection
  $model_number = mysql_real_escape_string($_GET['name']);

  // Insert a row that associates the user_id with the model number
  mysql_query("INSERT INTO product_views (user_session_id,modelNumber) VALUES('{$_SESSION['user_id']}', '$model_number')"); 
}