dongwei1954 2017-11-05 19:04
浏览 79
已采纳

将数据从一个PHP页面传递到另一个PHP页面[重复]

I have a program that I'm making that takes a database gets the top 5 rows from that database and presents it to a user when a button is clicked on the website I have made. I was able to get the database data to print on the page where the button was clicked, but I want it to be printed to another page that I have created. Here is my code so far for the main page with the buttons and the PHP code to get the database information(the file is called file1.php):

<html>
    <head>

        <title>Testing SQL DB</title>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


    <script type = "text/javascript">
        function myAjax () {
            $.ajax( { type : 'POST',
              data : { },
              url  : 'query.php',              // <=== CALL THE PHP FUNCTION HERE.
              success: function ( data ) {
                document.getElementById("dbResult").innerHTML = data;   // Get the element with id="demo"
              },
              error: function ( xhr ) {
                alert( "error" );
              }
            });
        }
    </script>
    </head>
    <style>
        h1
        {
            text-align: center;
            font-size: 45px;
        }

        .radio-input
        {
            font-size: 35px;
        }
        .radio
        {
            font-size: 45px;
            display: block;
            vertical-align: top;
            margin-right: 3%;
            margin-bottom: 30%;
            text-align: center;
        }
        .buttons 
        {
            text-align: center;
        }
        .jumbotron {
            position: relative;
            background: #dca7ea url("dogGif.gif") center center;  
            width: 50%;
            display: block;
            margin-left: auto;
            margin-right: auto;
            height: 50%;
            background-repeat: no-repeat;
            overflow: hidden;
        }
        .jumbotron2 
        {
              min-height: 50%;  /* Fallback for browsers do NOT support vh unit */
              min-height: 40vh; /* These two lines are counted as one :-)       */
              background-color: #fb6f74;
              display: flex;
              align-items: center;
        }
        #dbResult
        {
            text-align: center;

        }
    </style>

    <body style = "background-color: #dca7ea;">
        <h1>Pet Name generator! The perfect name for your pet.</h1>
        <div class="jumbotron">
            <div class="container">
           </div> 
        </div>

        <div class="jumbotron2">
            <div class="container">
                  <div class="radio">
                      <label><input type="radio" name="girl">Girl</label>
                      <label><input type="radio" name="boy">Boy</label>
                      <button type="button" class="btn btn-default">Normal names</button>
                      <button type="button" class="btn btn-default">Specialty names</button> 
                      <a href="file2.php" target="_blank"><button id="submit_btn" onclick="myAjax()" type="button" class="btn btn-default">Random name</button></a> 
                      <p method="post" action="file2.php" id="dbResult" name="databaseNames">No results </p>
                  </div>

            </div>
        </div>
    </body>
</html>

My query.php file is as follows:

<?php 
    $db = mysqli_connect('localhost','root','','names_tbl');
    if($db->connect_errno > 0){
        die('Unable to connect to database [' . $db->connect_error . ']');
    }

    $query = "SELECT * FROM names_tbl.general_names LIMIT 5;";
    $result = mysqli_query($db, $query);
    while($row = mysqli_fetch_assoc($result))
    {
        echo "<u>".$row['Name']."</u>";            
    }
?>

Finally, my file I want the data to be transferred on is giving an error saying "Undefined index: dbNames" in file2.php(this is the line in which it's giving me the error in my second file)

          <?php
             echo("Names: " . $_POST['dbNames'] . "<br/>
");
          ?>

No SO posts have been able to help me, so any help on this would be greatly appreciated.

</div>
  • 写回答

1条回答 默认 最新

  • dqce48404 2017-11-06 23:44
    关注

    First of all, you should not embed an ajax request to a function. It strips off a large portion of flexibility of something called "events".

    You want to request data when the user clicks on the button:

    <script type = "text/javascript">
        $(function() {
          $('#normalnames').click(function(){
            $.ajax( { 
              type : 'POST',
              data : { type: 'normalnames' },
              url  : 'query.php',
              success: function ( data ) {
                $('#dbResult').html(data);
              },
              error: function ( xhr ) {
                alert( "error" );
              }
            });
          });
    
          $('#specialnames').click(function(){
            //etc
          });
        });
    </script>
    
    <button id="normalnames" type="button" class="btn btn-default">Normal names</button>
    <button id="specialnames" type="button" class="btn btn-default">Normal names</button>
    

    And on the PHP side of things:

    <?php
      if(isset($_POST['type'])){
        if($_POST['type'] == 'normalnames'){
          // make normal names query
        } elseif($_POST['type'] == 'specialnames'){
          // make special names query
        } else {
          die('incorrect request');
        }
      } else {
        die('unknown request');
      }
    ?>
    

    Now you want to enlist data in the dbresponse div:

    while($row = mysqli_fetch_assoc($result)){
        $data[] = "<li>".$row['Name']."</li>";            
    }
    
    echo '<ul>' . implode($data) . '</ul>';
    

    That would be the gist of it, perhaps its better to work with returning with json (echo json_encode($data) without the html tags) as javascript can traverse though it and append it to the list.

    To use that data on another page, use sessions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题