How To Check If A User Purchased An Item On The Product Page

I want to show this message on the product page

{if ordered}You bought this item{/if} view order

make a request to db using two tables

- cscart_order_details (check product_id here)

- cscart_orders (check user_id here)

How?

{$previous_order = db_get_field("SELECT count(od.product_id) FROM ?:orders AS o LEFT JOIN ?:order_details AS od ON od.order_id=o.order_id AND od.product_id=?i WHERE o.user_id=?i", $product_id, $user_id}
{if $previous_order}you purchased this{/if}
I tried this it didn't work, how can i make it work and how can i get the url of the ordered item in the product page? thanks

So do you receive any error or empty result for this request? Please make sure that $product_id and $user_id variables are not empty

Yes, can you give me the snippet for the db query to check if the buyer has purchased it before and the link to the order? Thanks