I'm looking for a way to clean my DB with a button on a html-page (.php). I have a code that's working OK, but every time I go in to the page the function is cleaning my DB without me pushing the button.
Here is my code
<button id="checkoutbutton" onclick="cleanDb()">Clean DB</button>
<script>
function cleanDb()
{alert("<?php clean();?>")}
</script>
<?php
function clean()
{
$con=mysql_connect("localhost","rss","Habb0") or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db("kalender",$con) or die("Failed to connect to MySQL: " . mysql_error());
$sql='DELETE FROM `bilder` WHERE `stop` < now()';
mysql_query($sql);
echo "Databasen är rensad från gamla bilder";}
?>
Please help me!
PHP is parsed on the server side, JavaScript is parsed on the client side. Any PHP operation will run first, before any javascript (Not considering AJAX).
Use this code, but I am not using javascript. In your case you should consider AJAX. But 2nd option is as follow
<form action="" method="post">
<button id="checkoutbutton" onclick="cleanDb()" name="clebtn">Clean DB</button>
</form>
<?php
if(isset($_POST['clebtn']))
{
function clean()
{
// your code
}
}
?>
you must call ajax for it like this
<button id="checkoutbutton" onclick="cleanDb()">Clean DB</button>
<div id="result_content"></div>
<script>
function cleanDb()
{
if(window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
// do your task for result
}
}
var url="clean_db.php";
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
and a PHP File clean_db.php
<?php
clean();
echo "db has been cleaned";
function clean()
{
$con=mysql_connect("localhost","rss","Habb0") or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db("kalender",$con) or die("Failed to connect to MySQL: " . mysql_error());
$sql='DELETE FROM `bilder` WHERE `stop` < now()';
mysql_query($sql);
echo "Databasen är rensad från gamla bilder";}
?>