[英]PHP, foreach weird behaviour
對不起,有限的標題。 放輕松吧,我對PHP不太了解。
在我的functions.php中,我具有以下2個函數來查看“接收者”或“發送者”是否已經存在。
function getSenderId($fromAddress){
global $database;
$check = $database->query("SELECT * FROM custMod_senders WHERE email = '$fromAddress'");
if($check->fetchRow() > 0){
$id = $check->fetchRow();
return $id['id'];
}else{
return 0;
}
}
function getReceiverId($toAddress){
global $database;
$check = $database->query("SELECT * FROM custMod_receivers WHERE email = '$toAddress'");
if($check->fetchRow() > 0){
$id = $check->fetchRow();
return $id['id'];
}else{
return 0;
}
}
現在在我的腳本中,我有以下內容。
$from = $_SESSION['fromAddress'];
$to = $_SESSION['addresses'];
$std = $_SESSION['possibleStd'];
if (!is_array($to)){
$to = array($to);
}
foreach($to as &$address) {
if(getReceiverID($address) == 0){
echo 'receiver not found';
$database->query("INSERT INTO custMod_receivers (email, possibleStd) VALUES ('$address', '$std')");
}
if(getSenderID($from) == 0){
echo 'sender not found';
$database->query("INSERT INTO custMod_senders (email) VALUES ('$from')");
}
$send_id = getSenderID($from);
$receive_id = getReceiverID($address);
$database->query("INSERT INTO custMod_lt_send_rec (send_id, receive_id) VALUES ('$send_id', '$receive_id')");
};
鑒於我的var,會話和表名都存在並且可用。。此循環或函數設置有什么問題?
問題出在foreach()中的最后一個查詢中。 鏈接表給出了各種瘋狂的結果。
編輯:問題是數據庫中的結果是重復的,不完整的或丟失的。 好像我的2個函數給出了錯誤的結果...
如果使用的是mysqli(應使用),則數據庫對象可以自動獲取ID。 它更快(查找次數減少了兩次)且即時。
$conn = new mysqli("localhost", "username", "password");
$conn->query("INSERT BLAH BLAH BLAH");
$id_of_new_row = $conn->insert_id;
您可能會看到(如注釋中所提到的)數據庫仍在寫入,並且由於並發性廢話,您看到緩存的響應(空)或其他一些不適當的值。 但是,當您僅可以使用發布的兩個函數來獲取要查找的ID時,再發送兩個查詢是沒有意義的,因此請將您的DB對象切換到該方法,讓我們知道它的運行方式!
;
最后不需要。 莫名其妙地搞亂了哪些價值觀?
編輯:
如果from不是數組,這將減少不必要的查詢數量。
$send_id = getSenderID($from);
if(getSenderID($from) == 0){
echo 'sender not found';
$database->query("INSERT INTO custMod_senders (email) VALUES ('$from')");
$send_id = $from;
}
foreach($to as $address){
$receive_id = getReceiverID($address);
if($receive_id == 0){
echo 'receiver not found';
$database->query("INSERT INTO custMod_receivers (email, possibleStd) VALUES ('$address', '$std')");
$receive_id = $address;
}
$database->query("INSERT INTO custMod_lt_send_rec (send_id, receive_id) VALUES ('$send_id', '$receive_id')");
}
確實看起來很奇怪的一件事是,您在沒有地址的情況下將$ address添加到數據庫,而在沒有from的情況下將$ from添加到數據庫。
您的詳細偽代碼結構,以幫助您了解:
if there is no receiver 1
then put the receiver intoto the database 2
if there is no sender 3
then put the sender into the database 4
anyway 5
put both in the database 6
因此,如果存在其中一個元素,它將在db中復制它(第6行); 如果未設置,則將空字符串放入db-因為第6行中的命令無論如何都會執行
那看起來不像是您可能想要做的事情嗎?
因此,這一系列條件條款應該是這樣的-如果我明白了你的話:
if ((getSenderID($from)) and (getReceiverID($address)) {
//code to put both into the db
}
elseif ((getSenderID($from)) {
//code to put the sender only
}
else {
//code to put the receiver only
}
另外,您可能希望查看一些有關條件語句的php手冊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.