简体   繁体   English

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

[英]insert with a select statement and php variables in 1 MySQL query

i have something like this to insert data from a form to my MySQL table. 我有类似的东西可以将数据从表单插入到我的MySQL表中。 is my use of select statements in the insert valid? 我在插入中使用select语句是否有效? please enlighten me. 请赐教。

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);  
    }
}

it says invalid query. 它说无效查询。 the columns in the insert statement is already in right order. insert语句中的列已经按正确的顺序排列。 can anyone help me? 谁能帮我?

You have to specify the columns that you are inserting into - 您必须指定要插入的列-

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)";

It looks like you have 6 columns. 看起来您有6列。

EDIT: This syntax may help to clear things up - 编辑:这种语法可能有助于清除问题-

$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 .= ")";

You're also using LIKE without giving it the chance to find other elements because you're not using wildcards. 由于没有使用通配符,因此您还在使用LIKE而没有机会找到其他元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM