I am currently building a web application. In my application, a load some data from mysql and I display them as a table in my website. Additionally I add another column that consists of different checkboxes. My source code of displaying the table is called by a function that is located in another page. The source code odf the function is the following :
function user_clients_table() {
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table border=2>
<tr>
<th>ID</th>
<th>Name</th>
<th>SurName</th>
<th>Receive Message</th>
</tr>";
while($record = mysql_fetch_array($clients)){
echo "<form action=pushnotification.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<input type=checkbox name=checkbox[] value=".$record['ID']." />". "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysql_close();
}
The function works fine, after i call the function my webpage looks like this:
I want next to display the client number whose check box has been checked after i click the button send. For example if i checked only the first check box and submit it, i want to echo the client id that matches thsi checkbox, in this case i will echo '2'. My approach to this is the following:
if(isset($_POST['send'])){
if(!empty($_POST['checkbox'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['checkbox']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
foreach($_POST['checkbox'] as $selected) {
echo "<p>".$selected ."</p>";
}
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
}
else{
echo "<b>Please Select Atleast One Option.</b>";
}
}
It works but only for the first checkbox, if I select the other checkboxes without the first one I doesn't display anything.
Can someone please help me?
Thanks in Regards
Each checkbox is in it's own form, so when you are submitting you are submitting the first form (the first checkbox), and that is why you are getting the current action. Put the form tags outside the loop
Related
I'm sorry about my question, but I'm starting with PHP and I want to ask you for a help with my problem.
In my web application I work with a table, which has a dynamic count of rows based on the number of rows in a source table in MySQL database. In the application should be a checkbox in each row of the table. After clicking on the submitt button there should be update of records in the source table and it should be update just of these records where the checkboxes were checked.
The table in the application looks simillar like in the picture.
The primary key in the source table is in the column NUMBER. As a first try I simulated that after clicking on submitt button there will be shown the msgbox with the values from the column NUMBER for the rows, where the checkboxes were checked.
<html>
<head>
<title>APLICATIONa</title>
<script type="text/javascript">
function GetSelected() {
//Reference the Table.
var grid = document.getElementById("Table");
//Reference the CheckBoxes in Table.
var checkBoxes = grid.getElementsByTagName("INPUT");
var message = "\n";
//Loop through the CheckBoxes.
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
message += " " + row.cells[1].innerHTML;
message += "\n";
}
}
//Display selected Row data in Alert Box.
alert(message);
}
</script>
</head>
<body>
<?php
$values = mysql_query("SELECT * FROM table_03_2020");
echo "<br><form action='main.php' method='POST'>";
echo "<input type='submit' name='button' value='Get Selected' class='btn btn-primary' onclick='GetSelected()' />";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
echo "<td><input type='checkbox' name='cbox[]' ></td>";
echo "<td><font color='red'>".$zaznam["number"]."</font></td>";
echo "<td>".$zaznam["name"]."</td>";
echo "</tr>";
endwhile;
echo "</table><br>";
echo "</form>";
?>
</body>
</html>
The msgbox is just an illustration. Instead of msgbox, I need that after clicking on the submit button, there should be an update for these records in the source table, where the checkboxes were selected (so of these records, which are now shown in the msgbox). So I need something like:
"UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
There'll be also a second submit button and after clicking on it, there should be another different update. So after clicking on the second button, I need something like:
"UPDATE table_03_2020 SET column1 = 'ab' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
I'm sorry if my question is not so clear, but I'd really appreciate any help.
Thank you very much.
Add key values with the number to the cbox form variable:
echo "<td><input type='checkbox' name='cbox[" .$zaznam["number"]. "]' ></td>";
Then use the following PHP to get the number list.
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
The addslashes function is for SQL Injection protection.
This will create a list with comma separated numbers.
Than, you can insert it in the the SQL query.
UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('. $checked_list .')
If you assign a value to the checkboxes, like this:
<input type='checkbox' name='cbox[]' value='{$zaznam["number"]}' >
When the form is submitted the cbox variable will contain an array of these numbers, which means that you can process them like this:
<?php
include 'db.php'; #your database connection!!!
$sql='update table_03_2020 set `column1`="XY" where `column2` in ( ? )';
$stmt=$db->prepare( $sql );
$ids=implode(',',$_POST['cbox']);
$stmt->bind_param('s',$ids);
$stmt->execute();
?>
Note that the above has not been tested so there might be errors but I hope it'll give the idea.
Thank you, I tried to improve the part of the code to:
echo "<input type='submit' name='buttonupdate' value='Get Selected' >";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
if ($_POST["buttonupdate"]) {
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
}
echo "<td><input type='checkbox' name='cbox[" .$zaznam["cflot"]. "]' ></td>";
It didn't work, there was no update. Did I edited the code incorrectly?
Actually I forgot to mention the second button, so I edited my first post. Would it be possible to distinguish between the first and the second button? Thank you very much for any help.
I am currently working on a php and MySQL application. In my application I load a table from MySQL and I display it in my Website. The table consists of the columns (ID,Name,SurName). When I load the table I also create another column which consists of different checkboxes. My source code for the creation of the table is the following:
function user_clients_table() {
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table border=2>
<tr>
<th>Client</th>
<th>Name</th>
<th>SurName</th>
<th>Receive Message</th>
</tr>";
while($record = mysql_fetch_array($clients)){
echo "<form action=pushnotification.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<input type=checkbox name= checkbox[".$record['ID']."] "."</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysql_close();
}
The table looks Lke that in the Website:
What i want to do is to echo the client id from the first column of the table if the checkbox of the client isset after i click the send button on the website. For example if the top checkbox isset i want to echo "1" , if the checkbox in the third row is checked i want to echo "3".
I ve done this so far:
if (isset($_POST['checkbox']))
{
foreach ($_POST['checkbox'] as $key => $value)
{
$receivemsg = $key;
}
echo '<span style="color:#AFA;text-align:center;">'.$receivemsg.'</span>';
}
But it works only for the first checkbox the other ones are not working.
Can someone please help me to do this?
Thanks in Regards
(In HTML, you put the attributes in "", like type="checkbox". Use '' for your tags, so you can use "" for the attributes. You are also missing a " />" at the end of your input tag.)
With the isset you actually check only the first one. Remove it, with foreach, you don't need it anyway, as it loops through the checked checkboxes (if you send them from HTML as an array). If none of the checkboxes are selected, the loop will run 0 times anyway.
foreach ($_POST['checkbox'] as $key => $value)
{
$receivemsg = $key;
}
If you write it this way, it will only save the very last checked checkbox. Maybe you want
foreach ($_POST['checkbox'] as $key => $value)
{
$receivemsg[] = $key;
}
And of course, injection, mysqli, and others what has been mentioned in the comments.
(Personally I find it kind of strange that if checkboxes are sent as an array, isset doesn't work on them anymore. Or to be more precise, it works on them as elements of the array.)
As #Johannes said, you also declare a form for each checkbox.
I am attempting to create an order form on our website but I have hit a dead end and am not sure where to go next.
I have a php file that queries a database and returns a list of item numbers and the quantity we have in stock. For each item number that shows up in the table there is an input box next to it. At the moment these input boxes all have the same Id.
My guess would be that first I need to have it so they don't all have the same ID?
Here is the form in action: http://synergysystems.com.au/soh/testmysql.php
From there, the user will fill out the form and click a submit button. This will then need to get the values from the input boxes (if greater than or equal to 1) and the corresponding item number and create a CSV file. The CSV file would just be 1st column - item number 2nd column - quantity.
I have attempted to do this with code I have found on the internet but just cant get my head around how I would go through each input box and get the values as well as the item number.
I think I may be going about it the wrong way.
Here is my current php to create the form:
<?php
echo "<div id=header>";
echo "<h1>Synergy Order Form</h1>";
echo "<p>Stock is updated every hour during business hours</p>";
echo "</div>";
echo "<br />";
echo "<link rel='stylesheet' href='table.css' type='text/css'>";
$conn = mysql_connect('localhost', '*****', '*****');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('****',$conn);
/* select only items with stock on hand */
$result = mysql_query("SELECT * FROM TABLE_SOH where (((TABLE_SOH.ITM_ONHAND) >0))",$conn);
echo "<table border='0'>
<tr>
<th>Item</th>
<th>Description</th>
<th>On Hand</th>
<th>Order Quantity</>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ITM_NO'] . "</td>";
echo "<td>" . $row['ITM_DES'] . "</td>";
echo "<td align=right>" . $row['ITM_ONHAND'] . "</td>";
echo "<td>". ("<input type ='text' name ='Item'.$i >") . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($conn);
?>
<html>
<body>
<form action="submit_order.php">
<input type="submit" name="select" value="select"/>
</form>
I don't have anything in the submit_order.php file as I have gutted it out of frustration trying to get something to work.
Even if someone could point me in the right direction.
Thank you,
Matt
If all you need to do is get all the data in all the input fields, you can just loop through $_POST in submit_order.php and toss them into the CSV.
// unset the stuff you dont want
unset($_POST['submit']);
// open a file
$fp = fopen('file.csv', 'w');
// put the items in the file
foreach($_POST as $key => $val)
if($key > 1)
fputcsv($fp, array($key, $val));
// Close the file
fclose($fp);
I am making a website for a mock book database using MSSQL where users can search for different books and select particular books that they might like to add to a list of favorites under their account name. The problem I am having is that I have no idea how to differentiate which book selection they want to add to their favorites because I can't figure out how to set the ISBN of the book, which uniquely identifies it, to a php session variable. If anyone can shed some light on this I would appreciate it, have been trying to figure it out all day.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
//Search to run if searching for book title
if(isset($_GET['searchBook'])){
$searchBook = $_GET['searchBook'];
$query = "SELECT BOOK.ISBN, Title, Author, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Title LIKE '%$searchBook%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Search to run is searching for a book author
if(isset($_GET['searchAuthor'])){
$searchAuthor = $_GET['searchAuthor'];
$query = "SELECT BOOK.ISBN, Title, Author, Genre, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Author LIKE '%$searchAuthor%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Store query result
$query_result = mssql_query($query, $connection)
or die( "ERROR: Query is wrong");
//Set up table to display search results
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><input name=\"".$line['index']."\" type=\"submit\" value=\"Add To Favorites\"></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
Not sure if this is relevant but the following code is my best attempt at getting the value of ISBN that corresponds to the row of the button being clicked, which doesn't exactly work like I had hope.
//Get the ISBN
$data = mssql_fetch_assoc($query_result);
$ISBN = $data['ISBN'];
echo $ISBN;
Here is the code for my addFavorite.php which is where the form action is set to. This is the file that needs to know what user is adding a book as a favorite AND what book they are adding to that list.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
$User = $_SESSION['userID'];
//Set up query
$query = "INSERT INTO FAVORITES VALUES(\"$User\",\"**I NEED A SESSION VARIABLE OR SOMETHING TO GO HERE\")";
//Store query result
$query_result = mssql_query($query, $connection)
//or die( "ERROR: Query is wrong");
Any help would be much appreciated. I know it's alot of information and if there is anything that doesn't make sense or I have forgotten to provide please let me know. Thanks.
EDIT
I have tried using the BUTTON instead of using INPUT but the value of the button is not setting to anything for some reason.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records **PROBLEM IN HERE since $line['ISBN'] returns nothing**
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line['ISBN']."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
EDIT 2
Finally got it working, thanks to everyone for helping! Partial code that was problematic posted below in working condition.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line[0]."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
Use a BUTTON-element instead of the INPUT-element. That way, you can use the 'value'-attribute of this element to pass the correct value.
echo "<td><button name=\"$line['index']\" value=\"$line['ISBN']\" type=\"submit\">Add to favorites</button></td>";
Although I would suggest using AJAX instead of the above approach for this: use the onclick event from a button to execute javascript that calls a seperate php-file and passes the correct ISBN-number. This is then added to the database and your original page should be refreshed or part of the page reloaded.
I have a dropdown box which is populated through MySQL:
echo "<form>";<br>
echo "Please Select Your Event<br />";
echo "<select>";
$results = mysql_query($query)
or die(mysql_error());
while ($row = mysql_fetch_array($results)) {
echo "<option>";
echo $row['eventname'];
echo "</option>";
}
echo "</select>";
echo "<input type='submit' value='Go'>";
echo "</form>";
How do i make it that if one clicks submit it will display a value from a MySQL db
Thanks for the help
Just change your query like SELECT result FROM somedb WHERE eventname = '".$eventname."'
Then you just do: (remember to check before while has user already requested info)
The value was: <?php print $row["result"]; ?>
Remember to check $_POST["eventname"] with htmlspecialchars before inserting it to query.
1) Give a name to your <select>, i.e. <select name='event'>.
2) Redirect your form to the display page (and set method POST): <form method='POST' action='display.php'>
3) just display the selected value: <?php echo $_POST['event']; ?>
If you want to use the same page, give a name to your submit button and then do this:
<?php
if (isset($_POST['submit']))
echo $_POST['event'];
?>
Hope it helps.