Only first word populating the value field on a submit button - php

I am doing a query and populating buttons with the results:
$query="select name from members where active=1 order by name";
If I do a simple:
while($row = $rs->fetch_assoc()) {
echo $row['name']."<br>;
}
I get a list:
Mary123
JOE
Robert Tables
However if I :
<table>
$column = 0;
while($row = $rs->fetch_assoc()) {
if ($column == 0) {
echo "<tr>";
}
echo "<td class='cellnopad'><input type='submit' class='submitbtn' name='name' value=".$row['name']."> </td>";
$column++;
if ($column >= 5) {echo "</tr>";
$row++;
$column=0;
}
}
echo "</table>";
My buttons look like
Mary123
JOE
Robert
As you can see the name Tables gets dropped from the name and only the value of Robert is shown.
I initially thought the name wasn't being displayed due to the size of the text versus button size, but I have proved that is not the case by removing the CSS and checking the $_POST value on individuals.php. Also,if I change the name in the database to Robert_Tables it works fine.
Is there something I am doing wrong? What do I need to change to get the value to show both words and the space?

Your problem relies on the fact that you forgot to quote the value parameter of the input with quotes ''. See here you have:
value=".$row['name'].">
when it should instead be:
value='".$row['name']."'>
And that is breaking your generated html markup, see simple snippet below on how the output is handled when you omit the quotes:
<input type='submit' class='submitbtn' name='name' value=asd asd>
<input type='submit' class='submitbtn' name='name' value="asd asd">

Related

Updating data in MySQL database based on checked dynamic checkboxes in the table

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.

Get the ID of the selected check box

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.

PHP & SQL - Update query fails to update value

I'm trying to create a very easy stock managing system. I'm able to show all the items in my table 'parts' and i'm showing the amount in a textbox. However, when i change the value from, for example, 0 to 5 in the textbox and i press my submit button, it doesn't update the stock.
Below is my code, i don't have alot of experience with update querys but i've read about it on php.net, obviously.
<?php
echo "<table width=\"800\" class=\"nieuws\">";
$db=mysqli_connect("localhost","root","","lichtwinkel");
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<form method='post' action=''>";
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal' value=$row[voorraad] /></td>";
echo "<td><input type='submit' id='update' name='update' value='Update' /></td>";
echo "</tr>";
}
echo "</table>";
if(isset($_POST['aantal']) && $_POST['update']) {
$y = $_POST['aantal'];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '$y' WHERE partnr = $row[0]");
}
echo "</form>"
?>
Simply said, what i'm trying to achieve is the following:
Whenever i change the value displayed in the texbox, and i press my submit button, i want it to update the value in the database.
Does anyone know what i'm doing wrong? Any ideas? Articles i should read?
All help would be appreciated.
Thank you.
As i see, you were doing it wrong at all.
First you can't use form tag within more then one td element.
You were didn't close the form tag, only at end. (So if it loops 6 times, you will have 6 forms open, but one ended!).
At update, you're selecting row[0] - it's outside of loop with rows?
Even if you update it, it will show wrong results again. Update should be above selects! So it picks up newly updated value.
What to do:
First make one form for all updates.
Use your submit button to have value DATABASE_ID.
Make the name of "aantal" to "aantalDATABASE_ID".
At submit check for $_POST['update'], and use it's value (DATABASE_ID) to get input $_POST["aantal".$_POST['update']].
Do update, you have all you need.
Example:
<?php
echo "<form method='post' action=''>";
echo "<table width=\"800\" class=\"nieuws\">"
$db=mysqli_connect("localhost","root","","lichtwinkel");
if(isset($_POST['update']) && !empty($_POST['update'])) {
$y = $_POST['aantal'.$_POST['update']];
$p=mysqli_query($db, "UPDATE parts SET voorraad = '".$y."' WHERE partnr = '".$_POST['update']."'");
}
$p=mysqli_query($db, "SELECT * FROM parts WHERE product LIKE 1");
echo "<tr><th></th><th>Onderdeel nummer</th><th>Eigenschappen</th><th>Prijs</th><th>Voorraad</th></tr>";
while ($row = mysqli_fetch_array($p)){
echo "<tr>";
echo "<td><img class='lamp' src='../css/images/".trim($row['partnr']).".png' alt='Geen afbeelding beschikbaar'></td>";
echo "<td>".$row['partnr']."</td>";
echo "<td>".$row['specs']."</td>";
echo "<td>€ ".$row['price']."</td>";
echo "<td><input type='text' id='aantal' name='aantal".$row[0]."' value='".$row[voorraad]."' /></td>";
echo "<td><input type='submit' id='update' name='update' value='".$row[0]."' /></td>";
echo "</tr>";
}
echo "</table>";
echo '</form>';
?>
After all, take care about SQL Injections. "aantal" value is user input. As the submit value can be changed.

inserting variables into php echo of a submit button

Hi I'm looking to insert a varible into a submit buttons name when I echo it via a loop so that each button has a unique name
$x=0;
$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 5; ";
$result = mysqli_query($link,$sql);
echo ("<table>");
echo ("<tr>");
echo ("<th>Name</th>");
echo ("<th>Level</th>");
echo ("<th>Stats</th>");
echo ("<th>Win Chance</th>");
echo ("<th>Action</th>");
echo ("</tr>");
while($row = mysqli_fetch_assoc($result)){
if($row['username'] !== $_SESSION['username']){//add so it dosent put duplicates
echo("<tr>");
echo("<th>".$row['username']." </th>");
echo("<th>Level: ".$row['Level']." </th>");
echo("<th>Player Stats:".$row['Attack']."/".$row['Defence']." </th>");
echo("<th>Win Chance: ");
echo(CalculateWinChance($link,$row['Defence']));
echo("<input type='hidden' name='".$x."hidden1' value='".$row['Defence']."' />");
echo("<input type='hidden' name='".$x."hidden2' value='".$row['username']."' />");
echo("<th><input type='submit' name = 'Attack_Btn".$x."' onclick = 'BattlePlayers()' value ='Attack'></th>");
echo("</tr>");
$x=$x+1;
}
}
echo ("</table>");
I tried the above code but it does not change the name attribute? What am I doing wrong here?
you can put that as an answer can ill accept it :) – GregHBushnell
Posting from comments:
"$ is not empty its prining as expected 01234" - The leading zero is treated as an octal, that's why it's failing. . – Fred -ii
thank you very much that solved it :) what is an octal ? – GregHBushnell
References:
http://php.net/manual/en/language.types.integer.php
https://en.wikipedia.org/wiki/Octal
Footnote:
echo is a language construct and not a "function" per se. So, you can safely omit all of the (), since that's just more code than needed really.
Reference:
http://php.net/manual/en/function.echo.php

Checkbox looping in php while posting to database

I am building at the moment an achievement system that works on the foundation of checkboxes (since its not post related) However, I bumped into a problem, and I cant seem to wrap my head arround it, since I am not that handy with loops and Arrays.
Okay, So I made group of checkboxes, that are posted on this page and filled appropiately, as see the code below that helps me fill that part of the page.
function MakeProfessionlist(){
$result = LoadListProffesion();
$i = 0;
echo '<table class="Overview">';
while($row = mysqli_fetch_array($result)){
$i++;
if(($i % 2) == 0){
echo "<td class='small'><td><input id='achievementHidden' type='hidden' value='0' name='IsChecked[]'>";
echo "<input type='checkbox' id='achievement' name='IsChecked[]' value = '1'>";
echo "<input name='AchievementId[]' type='hidden' value='".$row['AchievementId']."'></td>";
echo "<td class='big'>".$row["AchievementName"]."</td></tr>";
}else{
echo "<tr><td class='small'><input id='achievementHidden' type='hidden' value='0' name='IsChecked[]'>";
echo "<input type='checkbox'id='achievement' name='IsChecked[]' value = '1'>" ;
echo "<input name='AchievementId[]' type='hidden' value='".$row['AchievementId']."'></td>";
echo "<td class='big'>".$row["AchievementName"]."</td>";
}
}
echo '</table>';
}
As you see, i try to shoot through 2 variables, namely the AchievementId, and the IsChecked value (can be either 0 or 1)The problem occurs when I am going to save this information. I set up a table within the database that acts as mediator (The Achievement_User, with just 3 entries, which are UserId, AchievementId and the IsChecked Value)
My start was that I shoot through all the achievements that come through here with the AchievementId's that are posted together with the checkbox through the code down below.
if(isset($_POST['AchievementSaveData']))
{
// print_r($_POST);
$checkbox = isset($_POST['IsChecked']) ? $_POST['IsChecked'] : array();
$Achievement = isset($_POST['AchievementId']) ? $_POST['AchievementId'] : array();
foreach (array_combine($checkbox, $Achievement) as $IsChecked => $AchievementId){
$sql="SELECT * FROM Achievement_User WHERE UserId='".$UserId."' AND AchievementId ='".$AchievementId."'" ;
$result=mysqli_query($sql);
$count=mysqli_num_rows($result);
if ($count==1){
echo 'Update datarow with UserID '.$UserId.', AchievementId '. $AchievementId.' and with a value of '.$IsChecked;' <br>';
}
else{
echo 'Create datarow with UserID '.$UserId.', AchievementId '. $AchievementId.' and with a value of '.$IsChecked.' <br>';
}
}
}
Now the problem lies in the fact that when I check a checkbox, appearantly the Array gets increased. Instead of the 40 entrees it makes (which is how many AchievementId's are posted, and when checked everything off is the default) it creates an extra array space for each checked value, which makes my comparison useless, cause i get an error then that the arrays can be combined.
Is there any way I can work arround it what would make my array of AchievementId's match up with my IsChecked Value?
Edit: Next to that, the whole foreach loop doesn't seem to work anymore when I tried to merge the arrays (even if they match in values). So my thought here is maybe is there a way I can post the array from IsChecked with already the value of the AchievementId attached to it. If that is so, how could I work this out?
why don't you just give the checkbox the value of the achievement and get rid of the hidden input
<input type='checkbox' id='achievement' name='IsChecked[]' value = '<?php echo $row['AchievementId'];?>'>
then in the php
foreach ($IsChecked as $AchievementId){

Categories