2014-09-29 90 views
0

我有類似這樣的將表單中的數據插入到我的MySQL表中。我使用select語句插入有效嗎?請賜教。在一個MySQL查詢中插入一個select語句和php變量

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

它說無效的查詢。插入語句中的列已按正確順序排列。誰能幫我?

+1

您的查詢是對SQL注入攻擊開放的。看看http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php看看如何安全地做你的查詢。 – 2014-09-29 17:12:43

+0

我知道。即時通訊首先嚐試構建其功能。請堅持提問 – Gokigooooks 2014-09-29 17:18:39

回答

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不給它,因爲你不使用通配符查找其他元素的機會。

+0

我必須指定嗎?我插入的值與我創建表時的順序相同。 – Gokigooooks 2014-09-29 16:21:08

+0

是的,MySQL需要你指定。 – 2014-09-29 16:21:31

+0

添加了列說明,但無濟於事。我也試過把百分號放在'doctorName'這樣的'%$ docName%''仍然不起作用的地方。 – Gokigooooks 2014-09-29 16:25:10

相關問題