Zatarra97
Zatarra97

Reputation: 31

What button is clicked in a dynamic number of buttons

I have a database that contains an autoincrement id, the location and the date's trip. With this code I can show on display the result of my query.

$mysqli = new mysqli("localhost", "root", "password", "trip");
$result = $mysqli->query("SELECT * FROM news WHERE location = '$location'");

echo "<br/><h3>"."Result, I found " .$result->num_rows. " results.". "</h3><br/>";


while($row = $result->fetch_assoc()) {
    echo "<tr><td>".$row["location"]."</td><td>".$row["date"]."</td><td>".' <button type="submit" value="reserve"/>'. "</td></tr>";
}

How can I know which button the user click to reserve his trip?

Upvotes: 0

Views: 70

Answers (3)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

You don't need jQuery, or JavaScript at all, unless you want to submit the form with AJAX, which you haven't mentioned. You just need to fix your HTML.

<button> is not an empty element; it needs a closing tag. The text on the button goes between the tags. Give the button a name and assign the row id as its value.

$button = "<button type='submit' name='id' value='$row[id]'>Reserve</button>";

Then you can get the id of the clicked button from $_POST['id'] in the PHP script that handles the form submit.


Also, with this code

$result = $mysqli->query("SELECT * FROM news WHERE location = '$location'");

there is no way SQL injection is not a problem, regardless of what you've done on the client side. Client side validation is trivial to bypass. You need to use a prepared statement.

Upvotes: 1

Balvinder Singh
Balvinder Singh

Reputation: 320

To get particular row information use data attribute in your button and then get that information

$mysqli = new mysqli("localhost", "root", "password", "trip");
$result = $mysqli->query("SELECT * FROM news WHERE location = '$location'");

echo "<br/><h3>"."Result, I found " .$result->num_rows. " results.". "</h3><br/>";


while($row = $result->fetch_assoc()) {
    echo "<tr><td>".$row["location"]."</td><td>".$row["date"]."</td><td><button type='button' data-bind='".$row["location"]." - ".$row["date"]."' value='reserve'/></td></tr>";

}

Use Jquery to get that information

$('button').on('click',function(){
  var info=$(this).attr('data-bind');
    alert(info); 

});

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

$('button').on('click',function(){
    alert($(this).val()); // do anything what you want

});

Sample snippet:-

$('button').on('click',function(){
    alert($(this).val()); // do anything what you want
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>pahse 7, mohali</td>
    <td>04/06/2019</td>
    <td><button value="Click Me!">Click Me</button></td>
  </tr>

Note:- instead of submit button use input type="button", as submit button used to submit form normally.

Upvotes: 2

Related Questions