jjzjj

php - 当 MySQL 记录更改时,如何更新页面上显示的值?

coder 2023-10-12 原文

我正在尝试创建一个非常简单的拍卖页面,感谢这个社区,我离它越来越近了。

该页面非常简单,发生的事情是有人可以输入他们的名字和出价,然后出价,然后页面会为他们刷新新出价(前提是它高于当前出价)。不幸的是,这只会刷新出价者的页面。

我希望页面为当前正在查看它的每个人更新,这样他们就可以确保出价高于当前出价。

我在网上看过但找不到太多帮助我的东西,我看到这是通过称为轮询的东西完成的,或者 AJAX 和 jQuery - 但是我不确定它们是否相同。

这是我的 HTML 代码片段,这段代码检索拍卖:

<div class="auction-main">
<h1 class="auction-title">Bathroom Accessories</h1>

<?php
$con=mysqli_connect("xxxx","xxxx","xxxx","xxxx");

if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");


while($row = mysqli_fetch_array($result))
  {
    echo "<form name='auction' id='auction" . $row['ID'] . "'>
            <input type='hidden' name='id' value='" . $row['ID'] . "' />
            <div class='auction-thumb'>
                <div class='auction-name'>" . $row['Item'] . "</div>";
            echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
            echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
            echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
            echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
            echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
    echo "</div></form>";
  }
echo "</table>";

mysqli_close($con);

?>

这是我的 jQuery 代码片段,此代码发布到 PHP 页面以实际进行出价:

<script>
    $(document).ready(function(){
        $('form[name="auction"]').submit(function(){
            var id = $(this).find('input[name="id"]').val();
            var bidname = $(this).find('input[name="bidname"]').val();
            var bid = $(this).find('input[name="bid"]').val();
            var currentbid = $('#'+id).text();
            var itemdesc = $(this).find('.auction-name').text();

            if (bidname == '')
            {
                alert("No name!")
                return false;   
            }

            if (bid > currentbid)
            {
                alert("Bid is greater than current bid");   
            }
            else
            {
                alert("Bid is too low!");
                return false;   
            }

            $.ajax({
            type: "POST",
            url: "auction-handler.php",
            data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
            success: function(data){
                window.location.reload();
                bidname = '';
                bid = '';
                currentbid = '';
            }
        });
        return false;

        }); 
    });
</script>

最后,这是我的 PHP 代码片段。此代码将出价发布到 MySQL 数据库:

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);

$con=mysqli_connect("lena","Admin","1tadm1nI","auction");

if (mysqli_connect_errno())
    {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$itemdesc = $_POST['itemdesc'];

$query = "UPDATE auction SET CurrentBid = '$bid', Bidder = '$bidname' WHERE ID = '$id'";

$query2 = "INSERT INTO auction_log (Item, Bid, Bidder) VALUES ('$itemdesc','$bid','$bidname')";



mysqli_query($con, $query) or die(mysqli_error());

mysqli_query($con, $query2) or die(mysqli_error());

mysqli_close($con);
?>

所以我在此处显示的代码仅设置出价等。我想要实现的是能够向当前页面上的每个人显示这些新出价。目前它们出现的唯一方式是有人在出价后进入页面,或者用户手动刷新页面。

我希望能够几乎将 MySQL 数据库上的任何更新“推送”到网页。

如果有人能给我建议或代码片段来告诉我如何实现这一点,我将不胜感激。

感谢您的阅读,如果您需要更多信息,请告诉我。

最佳答案

What you are looking for is called Realtime.

您可以使用不同的方法来实现这一点。现在使用 Ajax,您可以在某个时间间隔内向服务器发送一些请求,并检查是否发生了什么,如果发生了什么,您可以更新它以查看。它叫做pooling .

有关更多信息,您可以看到这个很棒的答案 https://stackoverflow.com/a/12855533/3143384 .

希望这会节省您的时间。

关于php - 当 MySQL 记录更改时,如何更新页面上显示的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39450881/

有关php - 当 MySQL 记录更改时,如何更新页面上显示的值?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby-on-rails - Ruby on Rails 迁移,将表更改为 MyISAM - 2

    如何正确创建Rails迁移,以便将表更改为MySQL中的MyISAM?目前是InnoDB。运行原始执行语句会更改表,但它不会更新db/schema.rb,因此当在测试环境中重新创建表时,它会返回到InnoDB并且我的全文搜索失败。我如何着手更改/添加迁移,以便将现有表修改为MyISAM并更新schema.rb,以便我的数据库和相应的测试数据库得到相应更新? 最佳答案 我没有找到执行此操作的好方法。您可以像有人建议的那样更改您的schema.rb,然后运行:rakedb:schema:load,但是,这将覆盖您的数据。我的做法是(假设

  4. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  6. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  7. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  10. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

随机推荐