我有一个button
属性onclick
来启动 javascipt 函数,并且我的 javascript ajax 脚本有xmlhttp
对象。它正在与dbaction.php
当我单击按钮时,脚本和 mysql 一切正常,但问题在于行。It is inserting TWO same row for each click until it rowCount>0
当第一次单击 echo prints "0"
forrowCount()
后,如果我现在再次单击 echo prints "2"
forrowCount()
问题出在哪里?
<body>
<script type="text/javascript">
function loadName() {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
document.getElementById("sample_div").innerHTML = xmlhttp.responseText;
$("#my_button").attr("value", "Sent");
$("#my_button").attr("style", "color:red;");
}
};
xmlhttp.open("GET", "dbaction.php?sender_id=5&receiver_id=6", true);
xmlhttp.send();
}
</script>
<input type="submit" id="buton" onclick="loadName();" value="Submit"/>
<div id="sample_div" style="background-color: khaki; width:50%; margin: 0 auto;">
</div>
</body>
dbaction.php
<?php
//Database connection using PHP PDO(php database objects)
try {
$db = new PDO("mysql:dbname=member;host=localhost", "root", "", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch ( PDOException $e ) {
echo $e->getMessage();
}
$sql= "SELECT * FROM friendship WHERE sender_id=".$_GET["sender_id"]." AND receiver_id=".$_GET["sender_id"]."";
$rs=$db->prepare($sql);
$rs->execute();
$rs->fetch();
$count = $rs->rowCount();
if ($count>0){
echo "You already sent request...";
echo $count;
}
else {
$query = $db->query("INSERT INTO friendship (sender_id, receiver_id, is_approved) VALUES (".$_GET["sender_id"].",".$_GET["receiver_id"].",0)" );
$query->execute();
echo "Request sent";
echo $count;
}