0

I would like to add data to a database when user clicks button in table.

I am creating a portfolio for stocks in Wordpress and a user should be able to add stocks to their portfolio.

This is my insert_to_db.php file where the query is. get_current_user_id() gets the User_ID which is used to identify the user.


global $wpdb;

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

Below is my function that insert data to a front-end table, including the button user presses to add Name and Price to a database

function trendy2($Name, $Price, $user_id){
    $link = "https://signal-invest.com/tick/?ticker=";
    echo "<tr>
    <td>$Name</td>
    <td>$Price</td>
    <td><form method='POST' action='insert_to_db.php'>
        <input type='submit' name='id' value='$user_id'/>$user_id
    </form>
    </td></tr>";}

Html:

<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>

Right now, when button is clicked I get redirected to front-page and data is not added to MySQL Database.

d00me
  • 19
  • 3
  • What is `$con`? What is `get_current_user_id()`? If it's not a user-defined function of your database, you're doing something very wrong. You need to properly prepare your statement with placeholders to avoid serious security risks, and probably fix the problem you're having. – miken32 May 14 '21 at 22:08
  • You are also not checking for any errors or even if your database operations are successful. How can you know what is wrong if you aren't looking? – miken32 May 14 '21 at 22:08
  • Added both $con and the get_current_user_id(), sorry about that. – d00me May 14 '21 at 22:10
  • Setting aside the fact that Wordpress [already provides you](https://stackoverflow.com/questions/52165241/how-am-i-supposed-to-use-prepared-statements-in-wordpress-with-variables-in-a-qu) with database access, you can't just put a PHP function into a string and expect it to work. More importantly, you can't put ***any*** PHP code into a query and expect it to be safe. Your SQL should look like `INSERT INTO user_portfolio (Name, Price, User_ID) VALUES (?, ?, ?)` with the three values bound to the statement. The linked duplicate contains many examples of how to do this. – miken32 May 14 '21 at 22:20
  • Thanks for the advice. – d00me May 14 '21 at 22:27

0 Answers0