What button is clicked in a dynamic number of buttons - php

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?

$('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.

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.

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);
});

Related

How to click all database buttons generated through php script using a singe button?

The problem i've run into is that i have multiple buttons generated through php from data mysql data base and i do not want to manually click them all(it can go over 150). How do i make a button in HTML or PHP to click them all? or How to select the ID of each button (not manually) to include it in the General button?
I have tried onclick="document.getElementByID('').click()" atribute on the button that i want to click them all but with no succes
This is the code that i have and the issue:
<?php
// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'testcases';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
//fetching data
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM test1 ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
echo "<table style=\"position:absolute; left:10px; top:80px;\" border ='1px'>";
while ($row = $result->fetch_object())
{
echo "<tbody>";
echo "<tr>";
echo "<td><textarea id=\"row->date\">". $row->date ." </textarea></td>";
echo "<td><textarea id=\"row->testcase\">". $row->testcase ."</textarea></td>";
echo "<td><textarea id=\"row->percentage\">". $row->percentage ." </textarea></td>";
echo "<td><a href='temp.php?id=" . $row->id . "'><button type=\"button\" class=\"btn\" name=\"id\" id=\"$row->id\" >COPY To Temp</button></a></td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
}
}
// close database connection
$mysqli->close();
?>
<button type="button" style="width:200px" class="pure-button fuller-button1 blue" onclick="document.getElementByClassName('btn').click();">Copy All</button>
The expected result would be to have a table with multiple rows and button generated through php and another button to click them all, but i got stuck at the part where i need to click all the buttons.
I don't know what you really wanna do, but first of all it's a really strange thing to put a button into a link: if you want a like you can add a span child styled like a button and if you really want a button just listen to click events on it.
Another thing would be that you could use form + checkboxes so that your button can make a single action by submitting form (and this single action/HTTP query will be exploded in N actions (loop) server-side)
If you really would like to do this like you do, using ID property is not wrong but it doesn't help readability nor CSS selection, I would use data-* attributes.
So, now you want a simple answer ;)
var elements = document.getElementsByClassName("btn");
for (var i=0; i<elements.length; i++) {
elements[i].click(); // or anything you want
}
If you wanna get id properties you can do:
var elements = document.getElementsByClassName("btn");
var ids = [];
for (var i=0; i<elements.length; i++) {
ids.push(elements[i].id);
}
If you plan to use jQuery:
var ids = [];
$(".btn").each(function() {
var $button = $(this);
ids.push($button.attr("id"));
});
try this:
<button type="button" onclick="copyBtn()">Copy</button>
and using jQuery
function copyBtn(){
var id = $(this).attr("id");
console.log(id);
//do some stuff
}

Get submit button value from multiple buttons php

I have a dynamic menu inside a form element code is here
<form method="GET" action="index.php">
<?php
display_menu(); // this function generates menu items
?>
</form>
after the menu is generated every menu item is a submit button of the above form I want to get input of a single element by name or id attribute of submit button, and load a post from database.
<form method="GET" action="index.php">
<input type="submit" name="page-1" id="page-1" value="page-1">
<input type="submit" name="page-2" id="page-2" value="page-2">
<input type="submit" name="page-3" id="page-3" value="page-3">
<input type="submit" name="page-4" id="page-4" value="page-4">
</form>
so when any input button is pressed the function display_post() is called. Code of the function is as follows:-
function display_post(){
$conn = mysqli_connect('localhost', 'root', '', 'posts') or die('cannot connect');
if($_SERVER['REQUEST_METHOD'] == 'GET' ){
$blog_post_id = $_GET["id"];
$sql = "SELECT * FROM blog_posts where id='blog_post_id' ";
$result = mysqli_query($conn, $sql) or die('cannot load');
while ($row = mysqli_fetch_assoc($result)){
if($row > 0){
echo '<div>'.$row['content'].'</div>';
}else echo 'no posts';
}
}
}
However, the display_post() method is called inside a content tag whereas the display_menu() is called inside another div.
So the problem is I'm unable to get the id of the to submit button any help will be appreciated thanks in advance.
When you click on the submit button you will get all inputs values of the form.
Do one thing put this statement print_r($_GET);exit; in display_post() as a first line and see what you get after clicking on submit button.
Note: 1. you want to get the value of clicked button then you should use javascript or jQuery and Ajax.
2. You can not get input fields value by fields ID.
ex. if we have field <input type="submit" name="page-1" id="page-1" value="page-1">
then we can get its value as:
echo $_GET['page-1'];
page-1 is the input field name.
You can make 5 different forms for each button and change the action to
action="index.php?id=1"
Then use $_GET['id']
Also change id='blog_post_id' " to id='$blog_post_id' "
If I am guessing right what is your difficulty then
$blog_post_id = $_GET['id'];
$sql = "SELECT * FROM blog_posts where id='".$blog_post_id."' ";//I modified this line
$result = mysqli_query($conn, $sql) or die('cannot load');

jquery inside a while statement

I am trying to create a drop down menu that shows more information about each person displayed when the person is clicked on.
//Get users information
$sql = "SELECT user.uid, user.first, user.last, user.email, user.rating
FROM user
INNER JOIN team_members ON user.uid=team_members.uid
WHERE tid = '$tid'
ORDER BY user.last ASC";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
//name as button(displayed on page load)
echo "<button class='player' type='submit'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none'>
".$row["email"]." ".$row["rating"]."
</div>";
}
$(document).ready(function(){
$('button.player').click(function(){
$('div.player_info').toggle();
});
});
The issue I am having is that when clicked it displays all information in each loop. So if there are 5 people and you click one name, each person populates information. The information corresponds to each person but I only want to show the info of the person clicked.
I thought this would mean that I need to somehow uniquely identify each class but cant seem to figure it out and make it work. Or maybe there is a better way to run my loop to solve the problem. Any input is appreciated. Thank you.
You can use HTML data- attributes to correlate each button to a div. Then modify the JavaScript to use the embedded data.
In the below snippet, I added data-uid attributes to both the button and the div that are populated with the uid from the database.
When the button is clicked, the data-uid is read and used to select the div with corresponding data-uid.
Another small improvement that I made was to change the type attribute on the button to button. A value of submit means that the button should be used for submit a form which is not what you are doing here.
//Get users information
$sql = "SELECT user.uid, user.first, user.last, user.email, user.rating
FROM user
INNER JOIN team_members ON user.uid=team_members.uid
WHERE tid = '$tid'
ORDER BY user.last ASC";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
//name as button(displayed on page load)
echo "<button class='player' type='button' data-uid='".$row["uid"]."'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none' data-uid='".$row["uid"]."'>
".$row["email"]." ".$row["rating"]."
</div>";
}
$(document).ready(function(){
$('button.player').click(function(){
$('div.player_info[data-uid='+$(this).attr('data-uid')+']').toggle();
});
});
Wrap your .player and .player_info in a <div> and do some toggling with JQuery like so:
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='player-container'>
//name as button(displayed on page load)
echo "<button class='player' type='submit'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none'>
".$row["email"]." ".$row["rating"]."
</div>";
echo "</div>
}
$(document).ready(function(){
// hide all of the player_info containers
$(".player_info").hide();
$(".player-container").click(function() {
// this selects any child element of the clicked container with the
// classname .player_info and toggles it open or closed
$(this).children(".player_info").slideToggle();
});
});
You aren't specifying which player_info you want to toggle, $('div.player_info') will select all of them. A quick and dirty way to solve this would be to use select the next sibling with jQuery, relative to the button, like so:
$(document).ready(function(){
$('button.player').click(function(){
$(this).next().toggle();
});
});

displaying html form inputs that gets submitted to the browser?

I have a basic html form with textarea input and a submit button. I want to make it so that everything in the textarea gets submitted to the database and retrieved to be posted on the homepage of my website. An example would be the structure of stackoverflow, after posting this question it gets displayed on the homepage alongside other questions submitted in the past. I am using php and mysql. Please give me some direction and hopefully examples to how I can go about this. Thanks
<form action='index.php' method='post'>
<textarea name='data' rows='2' cols='20'></textarea>
<input type='submit' name='submit' value='store'/>
</form>
To Store In database:
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect('localhost','root','');
mysql_select_db('database_name',$con);
$data = $_POST['data'];
mysql_query("insert into table_name values ('$data')");
mysql_close($con)
{
?>
To Display in Home Page :
$con = mysql_connect('localhost','root','');
mysql_select_db('database_name',$con);
$q = mysql_query("select * from table_name");
while($r = mysql_fetch_array($q))
{
echo $r['data'];
}
Although this is the simplest and most oldest method but yet it can help you.
On The Form where textarea and submit button is present, just on click of submit, add the action where you can insert a query for inserting a record into the database.
And for your home page where you have to show the post . just add select query for posts And display all the posts according to your requirement.

wrap a mysql query in a php function and print results

I have the following query that I ran on my database to remove some data:
delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;
But I now need to make the a php function that runs when I press a button called clean
then print out all the subscriber data that was deleted.
Not quitesure where to start with this.
this is my html so far:
<form id="form1" name="form1" method="post" action="">
Clean subscribers:
<input type="submit" name="clean" id="clean" value="Clean" />
</form>
Any help or advice with this is very much appreciated.
C
You'll need the button to submit a form to a handler page, the handler page would then run the query, and collect+print the data.
If you don't want to refresh the page (or have your users diverted into another page), you'll want to use Ajax.
That's where you start.
Is abvious you made no effort! but I will answer you anyway.
<?php
$con = mysql_connect("serverUrl","login","password");
mysql_select_db("dbName", $con);
$result = mysql_query("SELECT * FROM subscriber, subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
while($row = mysql_fetch_array($result))
{
echo $row['subscriber.name']; //assuming you have a field {name} in your table
echo "<br />";
}
mysql_query("delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
?>
First you'll need to select the data you're about to delete.
Then you'll need to delete it and return the selected rows.
$rows = array();
mysql_connect(...);
$res = mysql_query(...select query here...);
while($row=mysql_fetch_assoc($res)) {
$rows[] = $row;
}
$res = mysql_query(...delete query here...);
return $rows;
You might not want to totally delete the subscriber. If I were you I would include a field named "deleted" or something along those lines, indicating whether or not the subscriber has been deleted. Then query according to whether or not that field is true or false.

Categories