我正在建立一个会员网站,当用户点击提交按钮或图像时我需要保持跟踪,即当这样的事情发生时,应该在数据库中输入一个条目。但令人沮丧的是双重条目,即当我从new.php重定向到bhejo.php时,会生成一个条目,当我单击提交并将页面重定向到亚马逊时,会生成另一个条目。请帮助。抓住。
<?php require_once("navig.php");
if(isset($_SESSION['user_id'])) { ?>
<?php
$cool=$_SESSION['user_id'];
echo '<a href="http://www.amazon.in/?tag=rewardadda-21¶m=$cool"><img src=images/a.png></a>';
?>
<script>
$("#a").click(function() {
alert("Entry added");
<?php
require_once('connect.php');
$dbb = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die('Error communicating to MySQL server.');
$cool_id=$_SESSION['user_id'];
$querye = "INSERT INTO orderdata(user_id, store_used) ".
"VALUES ('$cool_id', 'amazon')";
mysqli_query ($dbb, $querye);
mysqli_close($dbb);
?>
});
</script>
<?php
}
else {
?>
<div id="damn">
You need to be logged in to view this. Redirecting you to Log In page in 5 seconds (<a href="logsign.php">click here if it doesn't redirect automatically</a>).</div>
<script>
setTimeout(function () {
window.location.href= "logsign.php"; // the redirect goes here
},5000);
</script>
<?php
}
require_once('footer.php');
?>
答案 0 :(得分:2)
PHP是一种服务器端语言,您不能简单地将其附加到Javascript(客户端语言)。当有人请求页面时,服务器首先处理PHP代码,然后发送HTML文档。您获得双重条目的原因是因为在页面加载时,PHP代码已经被执行。因此,点击“提交”即可。类型按钮很可能只刷新页面。使用经典表单操作属性,或使用ajax
<script>
$("#a").click(function() { <-- JAVASCRIPT
alert("Entry added"); //These two languages are executed at seperate times
<?php <--PHP
require_once('connect.php');
$dbb = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die('Error communicating to MySQL server.');
$cool_id=$_SESSION['user_id'];
$querye = "INSERT INTO orderdata(user_id, store_used) ".
"VALUES ('$cool_id', 'amazon')";
mysqli_query ($dbb, $querye);
mysqli_close($dbb);
?>
});
</script>
解决方法 最简单的方法是使用&#34; action =&#34;表单属性。因此,在表单提交时,您可以指定要执行的脚本:
<form action='script.php'>
<input type='submit' ...>//<-- script.php will execute when you click that button
</form>
另一种方法是使用AJAX :( jQuery更可取)
$.ajax({
url:"script.php",
type: "POST",
data:{name:value, name:value},
success: function (){},
...
})
AJAX DOC:http://api.jquery.com/jquery.ajax/