我試圖編寫if
代碼,但無法弄清楚。PHP檢查是否存在值
在我的數據庫表中我有主鍵id
。 在表中我有objekt_nr
& element_nr
。 現在,在我致電INSTERT
之前,我需要檢查objekt_nr
和element_nr
是否已經存在。 If
objekt_nr
存在element_nr
。然後UPDATE
而不是INSTERT
。只有id可以是唯一的。表中的
例如:
ID ...... objekt_nr ...... element_nr
1 ....... 1 .......... ..... 1
2 ....... 1 ............... 2
3 ....... 1 .. ............. 3
4 ....... 2 ............... 1
5 ....... 2 ............... 2
PHP:這裏
if(isset($_POST["Import"])){
echo '<a href=".php">Fortsätt...</a><br />';
echo $path=$_FILES["file"]["tmp_name"];
//Load file into PHPExcel
$objPHPExcel = PHPExcel_IOFactory::load($path);
//Loop threw file to get data
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = 'J'; //$worksheet->getHighestColumn(''); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
//Echo file info
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
//Loop threw colum, rows and cells
for ($row = 2; $row <= $highestRow; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getCalculatedValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val . '<br></td>';
}
echo '</tr>';
}
echo '</table>';
}
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getCalculatedValue();
}
// Prepare Query
$query = "INSERT INTO phpexcel(
objekt_nr,
objekt_rev,
element_nr,
element_hojd,
element_typ,
element_langd,
element_oppningar,
element_vikt,
element_ritare,
element_status)
VALUES (
:objekt_nr,
:objekt_rev,
:element_nr,
:element_hojd,
:element_typ,
:element_langd,
:element_oppningar,
:element_vikt,
:element_ritare,
:element_status
)";
// Security measures
$query_params = array(
':objekt_nr' => $val[0],
':objekt_rev' => $val[1],
':element_nr' => $val[2],
':element_hojd' => $val[3],
':element_typ' => $val[4],
':element_langd' => $val[5],
':element_oppningar' => $val[6],
':element_vikt' => $val[7],
':element_ritare' => $val[8],
':element_status' => $val[9]
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
//echo $query."\n";
}
}
'INSERT INTO ... ON DUPLICATE KEY UPDATE'?假設'objeckt_nr'是關鍵。 http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html – 2014-10-28 09:13:28
@ʰᵈˑ絕對是最簡單的解決方案,但值得指出的是它是一個MySQL擴展(非標準的sql) – 2014-10-28 09:16:00
@TimSeguine這可能與MySQL - 我不確定你在說什麼。 – 2014-10-28 09:17:00