0

I have a page which is dynamic and takes a URL variable then populates the page from a PHP database call based on the value of the URL variable e.g.

<a href="myPage?item_id=10">Show item</a>

Upon opening the page I grab the item_id from the URL and collect the data for printing e.g.:

$query = "select * from items where item_id = $_GET[item_id]";
$result = $mysqli->query($query);
$row = $result->fetch_array();
$title = $row['item_title'];
etc etc

My question is, can I grab a data variable from a link instead? e.g.

<a href="myPage" data-item_id="10">Show item</a>

The reason for asking is that I want to use a modal which of course cannnot read from a URL as it would be the parent URL.

Ideally I want to stick with PHP as the code is written, but if there's a simple jquery solution to bring the data in to populate the page then that would be ok too (I'd guess an ajax call)

StudioTime
  • 22,603
  • 38
  • 120
  • 207

2 Answers2

1

You can use ajax to read the data attributes.

http://api.jquery.com/data/

$('#yourId').data('item_id');

Please read about sql injection in your query

select * from items where item_id = $_GET[item_id]";

How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Oyeme
  • 11,088
  • 4
  • 42
  • 65
  • Hi, it's a simple example only, I'm all over the injection issue but thanks for pointing it out – StudioTime Mar 04 '14 at 10:34
  • Thats ok to pass the data to an element but it doesn't allow me to pass it into a PHP string as $_GET[] does – StudioTime Mar 04 '14 at 10:48
  • using ajax you can setup which method do you want to use GET or POST.https://api.jquery.com/jQuery.ajax/ by default method is GET – Oyeme Mar 04 '14 at 11:19
0

You may want to use Ajax :

<a href="myPage" id='clickMe' data-item_id="10">Show item</a>

$('#clickMe').click(function() {

    $.ajax({
        type: 'GET',
        url: 'myPage.php',
        data: 'item_id='+$(this).data('item-id'),
        success: function(data) {
            // Do something with the returned data from the server
        }
    });
});
BMN
  • 8,253
  • 14
  • 48
  • 80