我尝试使用$ _GET变量制作SQL语句
这是我的handler.php:
if(array_key_exists("task", $_GET)){
$task = $_GET['task'];
}
if(array_key_exists("id", $_GET)){
$id_event = $_GET['id'];
}
if($task == "write"){
postMessage();
} else {
getMessages();
}
function getMessages(){
global $pdo;
global $id_event;
$resultats = $pdo->prepare("SELECT * FROM messages WHERE id_messages_evenement = :id ORDER BY date DESC LIMIT 10");
$resultats->execute([
"id" => $id_event
]);
$messages = $resultats->fetchAll();
echo json_encode($messages);
}
还有我的表格:
<form action="../src/App/handler.php?task=write&id=13" method="POST">
<input type="hidden" name ="auteur" id="auteur" value="<?php echo $id_membre ?>">
<input type="hidden" name ="id_event" id="id_event" value="<?php echo $id_event ?>">
<input type="text" id="message" name="message">
<button type="submit">Envoyer</button>
</form>
但是SQL语句不起作用。
如果我尝试使用$id_event = 13;
而不是
if(array_key_exists("id", $_GET)){
$id_event = $_GET['id'];
}
该语句有效,所以您认为我的问题来自$ _GET ['id']。
例如,每当有人发布带有表单的消息时,例如,调用id为13的“ ../ src / App / handler.php?task = write&id = [...]”,那么我想做
SELECT * FROM messages WHERE id_messages_evenement = 13 ORDER BY date DESC LIMIT 10
编辑:这是我使用AJAX的chat.js:
function getMessages(){
const requeteAjax = new XMLHttpRequest();
requeteAjax.open("GET", "../src/App/handler.php");
requeteAjax.onload = function(){
const resultat = JSON.parse(requeteAjax.responseText);
console.log(resultat);
const html = resultat.reverse().map(function(mess){
return `
<div class="message">
<span class="date">${mess.date.substring(11, 16)}</span>
<span class="author">${mess.id_auteur}</span> :
<span class="content">${mess.message}</span>
</div>
`;
}).join('');
const messages = document.querySelector('.messages');
messages.innerHTML = html;
messages.scrollTop = messages.scrollHeight;
}
requeteAjax.send();
}
function postMessage(event){
event.preventDefault();
const auteur = document.querySelector('#auteur');
const id_event = document.querySelector('#id_event');
const message = document.querySelector('#message');
const data = new FormData();
data.append('message', message.value);
data.append('auteur', auteur.value);
data.append('id_event', id_event.value);
const requeteAjax = new XMLHttpRequest();
requeteAjax.open('POST', '../src/App/handler.php?task=write');
requeteAjax.onload = function(){
content.value = '';
content.focus();
getMessages();
}
requeteAjax.send(data);
}
document.querySelector('form').addEventListener('submit', postMessage);
const interval = window.setInterval(getMessages, 1000);
getMessages();