在1个MySQL查询中插入一个select语句和php变量

时间:2014-09-29 16:05:39

标签: php mysql sql

我有类似的东西将表格中的数据插入我的MySQL表格。我在插入中使用select语句有效吗?请赐教。

if(isset($_POST['date']) && isset($_POST['docName']) && isset($_POST['docSpec']) && isset($_POST['time']) && isset($_POST['symptoms']) )
{   
    $nameOfUser = $_COOKIE['userlogin'];

    $docName = $_POST['docName'];

    $date = $_POST['date'];

    $symptoms = $_POST['symptoms'];

    $time = date('H:i:s',strtotime($_POST['time'])); 

    $id = mt_rand(1000,9999);  //generate random appointment id

    $insertQuery = "insert into appointment values
                ($id,(select doctorid from doctors where doctorName like '$docName' ),
                $date,$symptoms,
                (select patientid from patient where patientFName like '$nameOfUser'), $time)";

    if(mysqli_query($conn,$insertQuery)===true)
    {
        echo "<script>alert('success');</script>";
    }
    else
    {
        die('Invalid query: ' . mysql_error()); 
        $message .= 'Whole query: ' . $query;
        die($message);  
    }
}

它表示无效查询。 insert语句中的列已按正确顺序排列。有谁可以帮助我?

1 个答案:

答案 0 :(得分:0)

您必须指定要插入的列 -

insert into appointment (col1, col2, col3, ...) values
($id,(select doctorid from doctors where doctorName like '$docName' ), $date,$symptoms,(select patientid from patient where patientFName like '$nameOfUser'),$time)";

看起来你有6列。

编辑:这种语法可能有助于清理 -

$insertQuery = "INSERT INTO `appointment` (`col1`, `col2`, `col3`,`col4`,`col5`,`col6`) ";
$insertQuery .= "VALUES (";
$insertQuery .= "'" . $id . "'";
$insertQuery .= ", '" . "(SELECT `doctorid` FROM `doctors` WHERE `doctorName` LIKE '%" . $docName . "%')" . "'";
$insertQuery .= ", '" . $date . "'";
$insertQuery .= ", '" . $symptoms . "'";
$insertQuery .= ", '" . "(SELECT `patientid` FROM `patient` WHERE `patientName` LIKE '%" . $nameOfUser . "%')" . "'";
$insertQuery .= ", '" . $time . "'";
$insertQuery .= ")";

您还使用了LIKE而没有给它机会找到其他元素,因为您没有使用通配符。