在加载页面上执行查询

execute query onload page

本文关键字:执行 查询 加载      更新时间:2023-09-26

我想在onload期间执行查询。我该怎么做?这是我的代码。这是我要执行的查询。

<?php
    mysql_query("UPDATE `requests` SET `stat_id`= 3 WHERE `proj_id`='".$_GET['projid']."' and DATE(`req_date`)='".$_GET['date']."'");   
?>

和javascript

<script type="text/javascript">
$(document).ready(function(){
    $('input#approve').click(function(){
        var date = $(this).parent().attr('id');
        var projid = $(this).parent().attr('class');
        window.location.href="index.php?page=requests&date="+date+"&projid="+projid+"";
    });
});
</script>

当单击approve按钮时,页面会刷新,但查询没有执行。

您可以在index.php中使用以下代码来更新表

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET stat_id=3 WHERE proj_id='".$_POST['projid']."' and DATE(`req_date`)=DATE('".$_POST['date']."')");
mysql_close($con);
?> 

检查w3Schools

然后使用ajax调用这个页面

$.ajax({
  type: "POST",
  url: "Index.php",
  data: { projid: projid , date: date }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

jQuery ajax reference

你也可以使用ajax将此写入Java脚本

var date = $(this).parent().attr('id');
var projid = $(this).parent().attr('class');
$.ajax({
    type: "POST",
    url: "index.php",
    data: "{stat_id: 3,proj_id:projid,Date:date}",
    success: function(result) {
        alert(result);
    }

结果将是布尔值或0/1的形式

$(document).ready(function(){
    $('input#approve').click(function(){
        var elem = $(this).parent(),
            date = elem.attr('id'),
            projid = elem.attr('class');
        $.get("index.php", { page: 'requests', date: date, projid: projid }, function() {   
            console.log('updated!')
        })
    });
});

您的mysql_query将返回一个值,您可以使用它来查看问题是否在查询中以及它是否正在执行。

<?php
  //Output GET Params
  echo $_GET['date'] . " " . $_GET['projid'];
 //Escape Slashes in Date http://php.net/manual/en/function.addslashes.php
  $date = addslashes($_GET['date']);
  $result = mysql_query("UPDATE `requests` SET `stat_id`= 3 WHERE `proj_id`='".$_GET['projid']."' and DATE(`req_date`)='".$date."'");  
  //Check to see if an error has occurred. If so output.
  if (!$result) {
     die('Invalid query: ' . mysql_error());
  }
?>

Javascript:(硬编码值)

<script type="text/javascript">
$(document).ready(function(){
$('input#approve').click(function(){
   //Hard code for now to ensure you have accurate data
    var date = "12/12/12";
    var projid = 15;
    window.location.href="index.php?page=requests&date="+date+"&projid="+projid+"";
});
});