2015-11-09 80 views
1

這是我的代碼,但我得到一個SQL語法錯誤;PHP中的CONCAT SQL查詢

$insert = "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '".$area1."')"; 
$insert .= "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '".$area2."')"; 
$insert .= "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '".$area3."')"; 
$insert .= "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '".$area4."')"; 
$insert .= "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '".$area5."')"; 

執行此查詢的正確方法是什麼?

回答

3

插入多個元組時,這是所使用的符號。

$insert = "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '".$area1."')"; 
$insert .= ", (NULL, '".$area2."')"; 
$insert .= ", (NULL, '".$area3."')"; 
$insert .= ", (NULL, '".$area4."')"; 
$insert .= ", (NULL, '".$area5."')"; 
$insert .= ";"; 

提供多個INSERT子句建議單獨查詢;這可能是可以接受的,這取決於MySQL庫,但是每個都需要被;終止。

這就是說,你真的應該使用參數化查詢。當prepare d時,它們的速度通常與此相當(在一些較大的散裝插入物之外)。

+0

工作一種享受,將授予矮子! –

0

您只需指定列名一次,然後用逗號分隔值。例如

INSERT INTO學生(姓名,年齡) VALUES ( '約翰福音',10), ( '鮑勃',10), ( '傑里米',10);

因此,只需替換 「INSERT IGNORE INTO locations(location_id,location_name)VALUES」除第一個用逗號「;」之外的所有語句,並且還在末尾插入分號。

0

使用此SQL語法(使用;):

$insert = "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '$area1');"; 
$insert .= "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '$area2');"; 
$insert .= "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '$area3');"; 
$insert .= "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '$area4');"; 

或者

$insert = "INSERT IGNORE INTO locations (location_id, location_name) VALUES (NULL, '$area1')"; 
$insert .= ", (NULL, '$area2')"; 
$insert .= ", (NULL, '$area3')"; 
$insert .= ", (NULL, '$area4');";