請參閱下面的代碼,它檢查數據是否存在於表中,如果不存在,則插入它或者更新表。檢查插入或更新表
正如你可以看到它看起來有點混亂 - 有無論如何改善代碼邏輯或更小的東西?我有幾張桌子需要做同樣的事情。
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQL = "SELECT * FROM phone_affiliate WHERE affiliate_id = 1 AND affiliate_phone_id = '$dataPhoneID'";
$q = mysql_query($SQL);
if (mysql_num_rows($q) == 0) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
if (mysql_query($SQLInsert)) {
$phone_id = mysql_insert_id();
$SQLInsert = "INSERT INTO phone_affiliate (phone_id, affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUE('$phone_id', '1', '$dataPhoneID', '$stock')";
mysql_query($SQLInsert) or die(mysql_error());
}
} else {
$row = mysql_fetch_assoc($q);
$phone_id = $row['phone_id'];
$SQLUpdate = "UPDATE phone_affiliate set stock = '$stock' WHERE affiliate_id = 1 AND phone_id = $phone_id";
mysql_query($SQLUpdate) or die(mysql_error());
}
// Similar code block above for other tables.
}
}
注意:我知道PDO,但我沒有時間在現有系統上替換它。
'mysql_escape_string'?至少使用'mysql_real_escape_string'(本身已被棄用....)使用PDO或mysqli,沒有其他選擇。而且,依靠已棄用的功能意味着,後來頭痛。 – itachi