首页 > 解决方案 > 单击链接/按钮PHP时如何执行sql查询

问题描述

我正在使用 WordPress 并有一个包含Name数据的表格Price

我想要一个链接,在名为“添加到我的投资组合”的第三列中,通过单击此链接NamePrice应将数据添加到表中user_portfolio

这是我创建表的函数:

function trendy2($Name, $Price, $user_id){
    echo "<tr>
    <td>$Name</td>
    <td>$Price</td>
    <td><a href=\"https://signal-invest.com/signals/macd/\">Add to portfolio</a></td></tr>";
}

$con = new mysqli(HOST,USER,PASS, DB,PORT);

下面是我用来调用 $results_query_uptrend 的 PHP 代码的一部分,我的 SQL 查询让我NamePrice.

对于 $results_query_uptrend 中的每一行,NamePrice函数中检索并添加到表中。

get_current_user_id()获取用于识别用户的 User_ID。

    <table >
         <tr>
            <th>NAME</th>
            <th>PRICE TODAY</th>
            <th>ADD TO PORTFOLIO</th>
         </tr>
         <?php
            foreach ($results_query_uptrend as $r){
                $name = $r["Name"];
                $price = $r['Price'];
                
                $sql = ("INSERT INTO user_portfolio (Name, Price, User_ID)
                VALUES ('$name','$price',get_current_user_id())");

                $sql_preped = $con->prepare($sql);

                echo trendy2($name, $price, $sql_preped);                                               
            }
        ?>
    </table>

我可以点击链接,但我的数据库没有更新。

编辑:玩弄并创建受此答案启发的不同解决方案。

创建了一个新文件 insert_to_db.php,其中包含 SQL 查询。


<?php
    if(isset($_POST['id'])){
        echo("You clicked button one!");
        $sql = ("INSERT INTO user_portfolio (Name, Price, User_ID)
                VALUES ('$name','$price',get_current_user_id())");
        $sql_preped = $con->prepare($sql);
        $sql_preped -> execute();
    }
    else {
    echo" dhur";
    }
?>

更新了 trendy2() 函数以在表格中添加一个按钮而不是超链接:

function trendy2($Name, $Price, $percent, $trend, $user_id){//used to create the winners and losers table
    $link = "https://signal-invest.com/tick/?ticker=";
    echo "<tr>
    <td><a href=\"$link$Name\" style='color:#616161;' >$Name</a></td>
    <td>$Price</td><td style='color: "; echo ($percent < 0 ? '#FF0000' : '#4ca64c'); echo ";'>$percent%</td><td>$trend</td><td><form method='POST' action='insert_to_db.php'>
        <input type='submit' name='id' value='$user_id'/>    </form></td></tr>";}
<table >
         <tr>
            <th>NAME</th>
            <th>PRICE TODAY</th>
            <th>ADD TO PORTFOLIO</th>
         </tr>
         <?php
            foreach ($results_query_uptrend as $r){
                $name = $r["Name"];
                $price = $r['Price'];
                echo trendy2($name, $price, $user_id);                                              
            }
        ?>
    </table>

这里的问题是,我可以点击按钮,但数据没有插入数据库

标签: phpmysql

解决方案


推荐阅读