变量中的变量中的SQL代码

时间:2015-12-12 03:42:25

标签: php mysql

我一直在谷歌搜索几个小时,还没有找到我一直收到的错误的答案。我有以下代码:

$varFirstName = $_POST['FirstName'];
$varPast = $varFirstName.' Past';
$varPresent = $varFirstName.' Present';
$varPastandPresent = $varFirstName.' Past and Present';
$CharacterID = "SELECT CharacterID FROM CHARINFO WHERE FirstName='$varFirstName'";

$sql="INSERT INTO CHARACTER_RELATIONS (RelationshipWith, CharacterID)
VALUES('$varPast', '$CharacterID'),
('$varPresent', '$CharacterID'),
('$varPastandPresent', '$CharacterID')";

mysqli_query($con,$sql)
or  die('Error: ' . mysql_error());

每次运行时我都会收到“错误:”。如果我使$ CharacterID = 49;然后它工作正常,所以我觉得“SELECT CharacterID FROM CHARINFO WHERE FirstName ='$ varFirstName'”有问题,但我无法弄清楚是什么。建议?

1 个答案:

答案 0 :(得分:2)

$ CharacterID =" SELECT CHARID FROM CHARINFO WHERE firstName =' $ varFirstName'&#34 ;; //这会返回一个数组对象。所以你必须使用mysqli_fetch_array()检索每一行的值,如下所示     // print_r($ CharacterID); exit(); //检查数组值,同时你也执行了$ CharacterID。即mysqli_query($ con,$ CharacterID);

$varFirstName = $_POST['FirstName'];
$varPast = $varFirstName.' Past';
$varPresent = $varFirstName.' Present';
$varPastandPresent = $varFirstName.' Past and Present';
$Character= "SELECT CharacterID FROM CHARINFO WHERE FirstName='$varFirstName'";// this returns an array object
       $CharacterID= mysqli_query($con,$Character);
        while($row=mysqli_fetch_array($CharacterID)){
        $id=$row['CharacterID '];
        $sql="INSERT INTO CHARACTER_RELATIONS (RelationshipWith, CharacterID)
        VALUES('$varPast', '$id')";      
        mysqli_query($con,$sql)
        or  die('Error: ' . mysqli_error($con));  
}