【问题标题】:How to fetch results from MySQL database using AJAX on button click如何在单击按钮时使用 AJAX 从 MySQL 数据库中获取结果
【发布时间】:2020-07-06 09:05:00
【问题描述】:

我是 PHP 和 ajax 的新手,所以请放轻松。我正在尝试使用 AJAX 获取 MySQL 结果。从我在互联网上发现的研究中,我已经做到了这一点。如果这可能有帮助,我正在 WordPress 中执行此操作。我收到此错误 -

Uncaught Error: Call to a member function get_results() on null in script.php:13 Stack trace: #0 {main} thrown in script.php on line 13

test.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<button type="button">Click</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<p></p>
<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery("button").click(function(){

            $.ajax({
                type: 'POST',
                url: 'script.php',
                success: function(data) {
                    
                    jQuery("p").html(data);

                }
            });
   });
});
</script>
</body>
</html>

脚本.php

 <?php 
 echo' <table border="1">
<th colspan="5" style="text-align:center;"> <h2 class="tomorrow">GRADES</h2> </th>
<tr>
 <th>Day</th>
 <th>Comp</th>
 <th>Exam Type</th>
 <th>Grade</th>
<th>Previous Score</th>
</tr>'?>
  <?php
    global $wpdb;
    $result = $wpdb->get_results ( "SELECT * FROM wp_mytab
WHERE date=DATE(NOW())
UNION ALL
SELECT * FROM wp_mytabb
WHERE date=DATE(NOW())

ORDER BY date, comp ASC;" );
    foreach ( $result as $print )   {
    ?>
    <tr>
<td><?php echo $print->day;?></td>
<td><?php echo $print->comp;?></td>
<td><?php echo $print->examtype;?></td>
<td><?php echo $print->grade;?></td>
<td><?php echo $print->previouscore;?></td>
    </tr>
        <?php }
  ?>    
</table>

 ?>

这里有什么问题?

【问题讨论】:

  • 我不是 wordpress 人,但 $spdb 是什么。从它的外观来看,您将直接进入 script.php 页面,没有任何变量 inits。这就是为什么 $wpdb 为空,它在任何地方都没有得到任何值。我想它应该通过一些 WP init func
  • 你是说这些$connection = mysqli_connect("localhost","root",""); $db = mysqli_select_db($connection,'wp_mytab'); 吗?
  • 再说一次,我不是 WP 专家。但基本上,是的,您需要初始化 DB 连接(通过 PDO),然后才能使用 DB 连接从 DB 中获取内容。请注意,在这种情况下,这不是最好的方法。因为您使用的是 WP,所以我不必有一些适当的顺序来初始化您需要的所有东西。在这篇文章中添加 wordpress 标签以获得更好的答案
  • 您的script.php 文件在哪里?这是在您的 Wordpress 的 ROOT 文件夹中,所有文件夹(如 wp-content 或 wp-admin` 都在其中吗?告诉我。
  • test.phpscript.php 都在根文件夹中。

标签: javascript php html jquery wordpress


【解决方案1】:

您不能在单独的 PHP 文件中在 wordpress 代码结构之外使用 $wpdb

为此,您应该包含一些 wordpress 库

在你的 php 代码的开头添加这个。

$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-includes/wp-db.php';

确保您的 $path 正确

【讨论】:

    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 2015-09-09
    相关资源
    最近更新 更多