【问题标题】:How to select a Month AND year from mysql database using ajax如何使用ajax从mysql数据库中选择月份和年份
【发布时间】:2013-09-12 11:01:11
【问题描述】:

我正在使用以下脚本检索特定月/年的所有发票。 php 从数据库中提取所有年份和日期,将它们组合在一起并将它们放入选择菜单中,结果类似于:

June - 2013
July - 2013
August - 2013
September - 2013

这是 selectsummary.php :

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Sales Summary</title>
      <script type="text/javascript" src="../js/jquery/jquery.js"></script>
    <script type="text/javascript" src="../js/jqueryui/js/jquery-ui.js"></script>
       <link href="../js/select2/select2.css" rel="stylesheet"/>
        <script type="text/javascript" src="../js/select2/select2.js"></script>
         <script type="text/javascript">
            $(document).ready(function() { $("select").select2(); });
        </script>

        <?php
    include '../connectmysqli.php';
    include '../menu.php';
         echo '<link rel="stylesheet" href="../css/template/template.css" />';
    $salesID = rand().rand();
    $today = date("Y-m-d");

    ?>
    <script type="text/javascript" charset="utf-8">
            $(document).ready(function(){
            $('#selectmonth').on('change', function (){

              // THIS IS WHERE I AM TRYING TO WORK OUT HOW TO RETRIEVE THE JSON AND THEN PLACE THE RESULTS INSIDE THE "summarycontent" DIV.     

                     $.getJSON('select.php', {monthyear: $(this).val()}, function(data){
                        var invoicerow = '';
                        for (var x = 0; x < data.length; x++) {
                            invoicerow += '<p>' + data[x]['invoiceID'] + '">' + data[x]['date'] + ' - ' + data[x]['grandtotal'] + ' - ' + data[x]['customerID'] + '</p>';
                        }
                        $('#summarycontent').html(invoicerow);
                      $("select").select2();
                    });

                    });     
                    });
            </script>
    </head>
    <body>
        <form method="post" action="addsalesubmit.php">
        <p>
          <select id="selectmonth">
            <option>Please Select A Monthly Summary To View</option>
            <?php

    $sql = <<<SQL
    SELECT YEAR(date) AS 'year', MONTHNAME(date) AS 'month'
    FROM `sales`
    GROUP BY YEAR(date), MONTHNAME(date) DESC
    SQL;

    if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']');}
    while($row = $result->fetch_assoc()){
    echo '<option value="'.$row['month'].'-'.$row['year'].'">'.$row['month'].' - '.$row['year'].'</option>';
    }
    echo '</select>';
            ?>
            <br />
            <br />
        </form>
    <div id="summarycontent"></div>

    </body>
    </html>

这是 ajax 用来查找结果并将其发送回主脚本的 select.php:

            <?php include '../connectmysqli.php'; ?>
    <?php
    $monthyear = strtotime($_GET['monthyear']);
    $sql = 'SELECT * FROM sales WHERE date = ' . (int)$monthyear;
    $result = $db->query($sql);

    $json = array();
    while ($row = $result->fetch_assoc()) {
      $json[] = array(
        'invoiceID' => $row['invoiceID'],
        'date' => $row['date'],
        'grandtotal' => $row['grandtotal'],
        'customerID' => $row['customerID']
      );
    }
    echo json_encode($json);

    ?>

我遇到的问题是我不确定如何将诸如“2013 年 7 月”之类的文本转换为 select.php 可以使用的内容。目前,如果我使用 chrome 开发人员工具查看发生了什么,我会得到以下信息:

select.php?monthyear=July-2013
/manda/salessummary

所以日期没问题,但我不知道如何在另一端使用它来选择那个月/年的日期,因为它的格式错误。

数据库如下:

     id invoiceID   salesID customerID  vehicleID   date    comments    subtotal    vat grandtotal  description1    qty1T   linetotal1T stock1T stock2T description2    qty2T   linetotal2T stock3T description3    qty3T   linetotal3T stock4T description4    qty4T   linetotal4T stock5T description5    qty5T   linetotal5T discount
    68  1     1512428605    82428579    134722464   2013-07-08      22.48   4.50    26.98   Bridestone Pt34 - 175/55/18/W/63 - (99 In Stock) -...   1   22.48   711022407                                                               

编辑>>>>

select.php 现在看起来像这样:

                    <?php include '../connectmysqli.php';

    $date_convert = date('Y-m-d', strtotime($_POST['monthyear']));

// 或者,使用 LIST,这将允许您稍后使用两个日期部分。

list($month, $year) = explode('-', $_POST['monthyear']);

$SQL = "SELECT * FROM sales WHERE date = :date"; $STH = $db->prepare($SQL); $STH->bindParam(':date', $date_convert);

    $json = array();
    while ($row = $result->fetch_assoc()) {
      $json[] = array(
        'invoiceID' => $row['invoiceID'],
        'date' => $row['date'],
        'grandtotal' => $row['grandtotal'],
        'customerID' => $row['customerID']
      );
    }
    echo json_encode($json);

    ?>

【问题讨论】:

  • 请看我的回答。

标签: php jquery mysql ajax json


【解决方案1】:

试试这个。

使用strtotime()

网址:select.php?monthyear=July-2013

$date = mysql_real_escape_string($_POST['monthyear']);

$mysql_date = date('Y-m-d', strtotime($_GET['monthyear']));

$sql = 'SELECT * FROM sales WHERE date = ' . $mysql_date;
  • P.S - 不要只是将参数连接到 sql 命令。我们已经不是 90 年代了。

更好的选择是使用bind_param()

$mysql_date = date('Y-m-d', strtotime($_GET['monthyear']));

$sql = 'SELECT * FROM sales WHERE date = ?';

$sql->bind_param("s", $mysql_date);

【讨论】:

  • 当我使用上述内容时,我得到:select.php?monthyear=August-2013 /manda/salessummary GET 500 Internal Server Error text/html jquery.js:8526 Script 226 B 4 B 966 ms 954控制台中的毫秒
  • 这是在 chrome 的开发者控制台中,我推测它来自 ajax,来自 php 选择文件
  • 我刚刚注意到 iv 使用了您的底层 PDO 方法,但我使用 mysqli 连接到数据库并在其他所有内容上使用 mysqli,因为我无法解决 PDO。
  • @IainSimpson 已更新。
  • 我得到的只是这个记录并且没有返回:select.php?monthyear=August-2013 /manda/salessummary
【解决方案2】:

转换数据

$date_convert = date('Y-m-d', strtotime($_POST['monthyear']));

// Or, use LIST which would allow you to use the two date parts later.

list($month, $year) = explode('-', $_POST['monthyear']);

获取结果

$SQL = "SELECT * FROM myTable WHERE date = :date";
$STH = $DBH->prepare($SQL);
$STH->bindParam(':date', $date_convert);

【讨论】:

  • 我完全迷失了 PDO 就像对我说西班牙语一样大声笑,我使用 mysqli
  • 谢谢!我在 Dreamweaver 中的这一行出现错误:$date_convert = date('Y-m-d', strtotime($_POST['monthyear']);
  • 应该是 $date_convert = date('Y-m-d', strtotime($_POST['monthyear']));
  • 在我得到的服务器上:[12-Sep-2013 06:33:42 America/Denver] PHP 通知:未定义索引:/home3/websit52/public_html/manda/salessummary/select 中的月份年份。第 3 行的 php [12-Sep-2013 06:33:42 America/Denver] PHP 通知:未定义的偏移量:第 7 行的 /home3/websit52/public_html/manda/salessummary/select.php 中的 1 [2013 年 9 月 12 日06:33:42 America/Denver] PHP 致命错误:在第 11 行的 /home3/websit52/public_html/manda/salessummary/select.php 中的非对象上调用成员函数 bindParam()
  • Iv 刚刚添加了上面的更新代码,现在得到:[12-Sep-2013 06:36:19 America/Denver] PHP Notice: Undefined index: monthyear in /home3/websit52/public_html/manda /salessummary/select.php 在第 3 行 [12-Sep-2013 06:36:19 America/Denver] PHP 通知:未定义的偏移量:1 in /home3/websit52/public_html/manda/salessummary/select.php 在第 7 行 [ 2013 年 9 月 12 日 06:36:19 America/Denver] PHP 致命错误:在第 11 行的 /home3/websit52/public_html/manda/salessummary/select.php 中的非对象上调用成员函数 bindParam() /跨度>
【解决方案3】:

玩了这么多,终于对 select.php 起作用了:

    <?php 
    error_reporting(E_ALL);
    ini_set('display_errors', '1');

            include '../connectmysqli.php';

            list($month, $year) = explode('-', $_GET['monthyear']);

             $date = date_parse($month);
      $month = $date['month'];


    $sql = "SELECT * FROM sales WHERE MONTH(date) = '$month' AND YEAR(date) = '$year'";
    $result = $db->query($sql);

    $json = array();
            while ($row = $result->fetch_assoc()) {
              $json[] = array(
                'invoiceID' => $row['invoiceID'],
                'date' => $row['date'],
                'grandtotal' => $row['grandtotal'],
                'customerID' => $row['customerID']
              );
            }
            echo json_encode($json);

            ?>

【讨论】:

    猜你喜欢
    • 2012-02-24
    • 1970-01-01
    • 2012-12-07
    • 2015-12-26
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2018-01-23
    相关资源
    最近更新 更多