2010-10-04 97 views
2

我有一个好奇的问题,我希望是我忽略的一些愚蠢的东西。“字段列表”中的未知列'Bob'... php或mysql问题

我收到的时候有一个MySQL表丢失列,或拼写错误的PHP变量,通常会出现的错误:“在‘字段列表’未知列‘鲍勃’” ......

除了“ Bob'不是列的名称,它是我试图分配给该行的VALUE。为什么PHP会混淆两者?

这里是我的PHP函数,我认为这是错误的位置:

function recordGuest($id,$fname,$lname,$dinner){ 
    $conn = connect("wedding"); 
    $guest_query = "INSERT INTO guest (fname,lname,person_id) 
        VALUES (".$fname.",".$lname.",".$id.");"; 
    mysql_query($guest_query,$conn) or die(mysql_error()); 

    $guest_id_query = "SELECT id FROM guest WHERE person_id = ".$id.";"; 
    $guest_id_result = mysql_query($guest_id_query,$conn) or die(mysql_error()); 
    $guest_id = ""; 
    while($row = mysql_fetch_array($guest_id_result)){ 
     $guest_id = $row["id"]; 
    } 

    $guest_dinner_query = " INSERT INTO guest_dinner (dinner_id,guest_id) 
          VALUES (".$dinner.",".$guest_id.");"; 
    mysql_query($guest_dinner_query,$conn) or die(mysql_error()); 
} 

这里是PHP代码处理表单并执行上述功能:

<?php 
include("functions.php"); 

$code = $_POST["code"]; 
$type = $_POST["type"]; 
$people = getPeople($code); 
$ids = $people["ids"]; 
$email= ""; 

for($i = 0; $i < count($ids); $i++){ 
    $response = $_POST["response_".$i]; 
    $dinner = $_POST["dinner_".$i]; 
    recordResponse($ids[$i],$response); 
    if($dinner != "null"){ 
     recordDinner($ids[$i],$dinner); 
    } 
    if($type == 3){ 
     $guest_responses = $_POST["guest_response_".$i]; 
     $guest_fname = $_POST["guest_fname_".$i]; 
     $guest_lname = $_POST["guest_lname_".$i]; 
     $guest_dinner_response = $_POST["guest_dinner_response_".$i]; 
     if($guest_dinner_response != "null"){ 
      recordGuest($ids[$i],$guest_fname,$guest_lname,$guest_dinner_response); 
     } 
    } 
} 
?> 

继承人什么我的“客人”MySQL表看起来像:

guest 
    id int auto inc (primary key) 
    fname varchar 
    lname varchar 
    person_id int 

任何帮助,将不胜感激。

+2

FYI偷了:你的代码很容易受到SQL注入 – mikerobi 2010-10-04 00:31:57

+1

你尝试打印到生成的SQL? – mikerobi 2010-10-04 00:32:16

+0

嗯,修复漏洞最快的方法是使用mysql_real_escape_string()吗?这只适用于数据库中的字符串条目吗? – 2010-10-04 00:58:39

回答

2

字符串括起来在单引号试图插入字符串之前,即“鲍勃”值

+0

啊!谢谢,我看不到它。 – 2010-10-04 00:51:50

1

是,尝试在事务所引号括起来像这样:

VALUES ('".$fname."','".$lname etc 

但更好的是你永远不应该插入在数据库中这样的东西,它打开SQL注入和其他不好的东西的风险

除非你使用一些严厉的PHP版本,你可以使用PDO和使用语句。就像这个例子我从灵活php.net

<?php 
/* Execute a prepared statement by binding PHP variables */ 
$calories = 150; 
$colour = 'red'; 
$sth = $dbh->prepare('SELECT name, colour, calories 
    FROM fruit 
    WHERE calories < :calories AND colour = :colour'); 
$sth->bindParam(':calories', $calories, PDO::PARAM_INT); 
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12); 
$sth->execute(); 
?> 
相关问题