Почему в этом случае база данных mysql не обновляется? - PullRequest
0 голосов
/ 27 июля 2011

У меня есть PHP-скрипт:

require_once('global.php'); //connects to db and various functions used
//select the user's information
$statement = $db->prepare("SELECT * FROM user WHERE id=1");
$statement->execute();
$result = $statement->fetchObject();
//get the chat
$string = $result->chats;

$from = $_REQUEST['from'];
$msg = $_REQUEST['msg'];
$sent = $_REQUEST['sent'];

//see what we should do with the recieved data
if($string == "") {
    //there isnt any chats right now, we must add the first ever contact
    $string = "<ResultSet><chats><chat><messages><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$from}</contact></chat></chats></ResultSet>";
    //send the data back to the user's row in the database
    $statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
    $statement->execute();
} else if($from == $result->name) {
    //the user is sending a message to a contact. we now need to get the "to" value.
    $to = trim(str_replace("_", " ", $_REQUEST['to']));
    //add the sms to the contact's chat
    $string = str_replace("</sms></messages><contact>{$to}</contact>", "</sms><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$to}</contact>", $string);
    //send the data back to the user's row in the database
    $statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
    $statement->execute();
} else if(strstr($string, "<contact>".$from."</contact>")) {
    //The contact that sent the message already exists in this user's row, add the message to the contact's chat
    $string = str_replace("</sms></messages><contact>{$from}</contact>", "</sms><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$from}</contact>", $string);
    //send the data back to the user's row in the database
    $statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
    $statement->execute();
} else {
    //Person who sent the message doesnt exist in the chats, add him.
    $string = str_replace("</chats>", "<chat><messages><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$from}</contact></chat></chats>", $string);
    //send the data back to the user's row in the database
    $statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
    $statement->execute();
}

Проблема в этом, если код:

else if($from == $result->name) {
//the user is sending a message to a contact. we now need to get the "to" value.
$to = trim(str_replace("_", " ", $_REQUEST['to']));
//add the sms to the contact's chat
$string = str_replace("</sms></messages><contact>{$to}</contact>", "</sms><sms><from>{$from}</from><msg>{$msg}</msg><sent>{$sent}</sent></sms></messages><contact>{$to}</contact>", $string);
//send the data back to the user's row in the database
$statement = $db->prepare("UPDATE user SET chats='{$string}' WHERE id=1");
$statement->execute();
}

Я уверен, что код выполняется через это, у меня есть echo'd и подтвердил. Когда я использую $ string = str_replace (), я печатал $ string, и он действительно заменил. Но когда я отправляю данные в строку в базе данных, ничего не происходит, когда я обновляю свою базу данных. Почему это не работает для этого, а работает для остальной части оператора if (и if перед ним)?

Это не имеет смысла для меня. Код, который я старался изо всех сил, чтобы прокомментировать его, если вам нужно что-то объяснить, просто спросите.

Ответы [ 2 ]

1 голос
/ 27 июля 2011

В случае, если $ db - это не экземпляр MySQLi или PDO, а оболочка db, посмотрите на класс, для которого создается экземпляр $ db, и убедитесь, что он не запускает транзакцию. Если инициирована транзакция, вам нужно будет зафиксировать транзакцию, чтобы изменения в базе данных были применены / сохранены.

0 голосов
/ 31 июля 2011

Я не уверен, почему, но мне пришлось изменить свой код так, чтобы я отправлял переменные в функцию execute вместо запроса. В запросе я бы поставил "?" где я хочу переменные, и в функции execute () я бы поместил массив, как

$statement->execute(array($string, 1));

Это, похоже, решило мою проблему.

...