PHP loop generated buttons - only last one works? - php

First time posting, and PHP is not my strongest area, so here goes...
My code below generates a list of buttons depending on how many values are found in my DB Table, then the second piece of code is supposed to trigger when the buttons are clicked. Everything is working except that the second piece of code only works for the last button generated. Any ideas?
<?php
$username = $_SESSION['sess_user'];
$con=mysql_connect('localhost','root','root') or die(mysql_error());
mysql_select_db('user_registration') or die("cannot select DB");
$loop = mysql_query("SELECT * FROM `vaults` WHERE username = '$username' ORDER BY vaultname asc") or die ('Error Getting User Data! <br />' .mysql_error());
$chk = mysql_num_rows($loop);
$myvalue = '';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
}
?>
<?php
if(isset($_POST[$myvalue])){
echo '<script type="text/javascript">window.onload = function() { document.getElementById("instructions").innerHTML = " HELLO WORLD! "; }</script>';}
?>
Thank you all for your replies, I appreciate it. I understand what everyone is saying, but the ID I reference in my getELementByID() is a separate DIV from the buttons, I want to change the content of the single DIV with the ID "instructions", when any of the buttons are clicked, but it only works for the last button created by the loop. Is that still due to the way I have my buttons ID'd?
For example say the above loop creates three buttons, I want each button to change the contents of the following DIV with "Hello Word".
<div id=instructions>
replace this text
</div>
I am guessing I have to store each of the $myvalues created by the loop into an array, so that each value can be assigned separately to each button, I just have no idea how to do that.

You're duplicating IDs in this line:
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
and IDs must be unique. Try classes instead. Ex:
var elems = document.getElementsByClassName("text-center");
for (var i = 0; i < elems.length; i++) {
console.log('x')
elems[i].addEventListener('click', function () {
alert('hello');
}, false);
}

You're assigning multiple inputs to the same id, assign them to a class instead since id's have to be unique.
You're also making a form for every button, which seems kind of pointless to me, try this instead:
echo '<form method="post">';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<input class="text-center vaultSelecter" type="submit" name=' . $myvalue . ' value=' . $myvalue . '>';
}
echo '</form>';
The id called vaultSelector is now a class, so can be accessed via getElementByClassName()

Instead of this:
name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"
Maybe try
name="' . $myvalue . '" value=' . $myvalue . ' id="' . $myvalue . '"
In my opinion it is best to uniquely identify any elements that will be used as a programming element.
Just another piece of unsoliciated opinion. If you can put everything in one form it may make things easier. So when the button submits set a hidden field and continue with the form submit.

Related

How does this code to create an array in HTML accessed by PHP?

I was going through Head First PHP and came by this piece of code.
<?php
$dbc = mysqli_connect('localhost', 'root', 'atlantis2016', 'elvis_store')
or die('Error connecting to MySQL server.');
if(isset($_POST['submit']))
{
foreach ($_POST['todelete'] as $delete_id)
{
$query = "DELETE FROM email_list WHERE id = $delete_id";
mysqli_query($dbc, $query);
}
echo 'Customer removed. <br />';
}
$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result))
{
echo '<input type="checkbox" value="' . $row['id'] . '" name="todelete[]" />';
echo $row['first_name'];
echo ' ' . $row['last_name'];
echo ' ' . $row['email'];
echo '<br />';
}
mysqli_close($dbc);
?>
I fully understand how we go through all the ids present in the array todelete by using the foreach loop.
What I don't get is how the array itself is created? Are there even arrays in HTML? IF not, how are we creating a PHP array using pure HTML in the following line?
echo '<input type="checkbox" value="' . $row['id'] . '" name="todelete[]" />';
Additionally, what I also find mysterious is how only those id's for which the checkboxes have been ticked end up in the array todelete while the others are ignored?
Basically, explain the origin and functioning of the todelete array for me, please.
By defining the input name as todelete[], we are saying that this input variable todelete will send any selected checkboxes upon form submission to a PHP script by POST or GET.
The PHP script defined in the parent form 'action' attribute will be able to access values under $_REQUEST['todelete'] which will be an array structure.
This syntax is useful if we want to send multiple values associated to a variable name.
See also: HTML input arrays
The top rated answer at this link describes the inner workings of the array beautifully. It cleared up almost all of my doubts.

Store values of dynamically generated radio buttons in mysql

I am creating radio buttons dynamically. I need to write the posted data into a MySQL table. The radio buttons names will change as will the qty of buttons.
For example, if four radio buttons are created, the name of each is a variable, $proposed_id (a number), and the values are yes or no.
I wish to have have all of the posted data in one table field. I tried using an array ("props_yes[]") but of course each new one overwrites the previous button.
Thanks for any help.
$sql = "SELECT * FROM table WHERE ballot_name = '$ballot_id' ";
$sql_result = mysql_query($sql,$link);
while ($row = mysql_fetch_array($sql_result))
{
$proposed_id = $row['submission_id'];
echo '<input name="' . $proposed_id . '" id="' . $proposed_id . '_yes"type="radio" value="Yes" required > ';
echo '<label for="' . $proposed_id . '_yes">' . 'YES' . '</label> ';
echo '<input name="' . $proposed_id . '" id="' . $proposed_id . '_no" type="radio" value="No" required > ';
echo '<label for="' . $proposed_id . '_no">' . 'NO' . '</label><br>';
}
While I agree with #trincot that, in general, it is bad practice to store multiple, different kinds of values in a single DB field, there are times that it is called for or even necessary, as for example, when your database uses the EAV pattern as do some popular systems like Wordpress. If this is the primary data that is being stored in your database, you might want to consider a NoSQL database for this project.
That being said, here is how you might handle storing and retrieving your data. First, I would add some key word to the name field of your radio inputs, e.g. name="ballot_'.$proposed_id.'" so that you don't end up with a bunch of fields with numbers as names, and so that you have some way to filter the results on the server side. On the server side then you could do something like (assuming the form was submitted using POST):
// create an associative array of values from your radio buttons
$ballot_values = array();
foreach ($_POST as $index => $value) {
if (false !== strpos($index, 'ballot_')) {
$id = substr($index, 7); // get the numeric part of the name
$ballot_values[$id] = $value;
}
}
Once you do this, $ballot_values will contain an associative array of IDs and yes/no values. In order to save this in a single database field, you need to serialize the array, i.e.
$serialized_ballot_values = serialize($ballot_values);
This will store the array as a single string that you can then store in your DB field. When you retrieve the value from the database, you'll have to unserialize it before you can use it.
Again, if you can avoid doing this, I would. Unfortunately, though, we don't always have control over the structure of the DB so it could be that you have no choice.
Use an array with keys in your radio button names. PHP will interpret the submitted values into an array.
$sql = "SELECT * FROM table WHERE ballot_name = '$ballot_id' ";
$sql_result = mysql_query($sql,$link);
while ($row = mysql_fetch_array($sql_result))
{
$proposed_id = $row['submission_id'];
echo '<input name="props_yes[' . $proposed_id . ']" id="' . $proposed_id . '_yes"type="radio" value="Yes" required > ';
echo '<label for="' . $proposed_id . '_yes">' . 'YES' . '</label> ';
echo '<input name="props_yes[' . $proposed_id . ']" id="' . $proposed_id . '_no" type="radio" value="No" required > ';
echo '<label for="' . $proposed_id . '_no">' . 'NO' . '</label><br>';
}
After the post, the value of $_POST['props_yes'] will contain an array of chosen answers. The keys in the array will be from the $proposed_id

Display checkbox values in HTML after select, submit and email results from process.php

I have a checklist that's broken down into days, stage, timeShow, and bandName. I am displaying the options from a database with this script and I'm trying to display the results (and eventually email them) to the user on the 'process' page. How do I carry over the $result_x to the following page?
Here's an example of one of the 'blocks' for Saturday, Stage 1 and the value of the selection is the 'ID' of the row.
UPDATE- Part one is solved. Now looking to get the results sent to an email address input by the user.
FORM SOLUTION- 'Selection.php'
$sql_Sat1 = "SELECT * FROM bandSched WHERE day='saturday' AND stage='stage 1'";
mysql_query($sql_Sat1);
$result_Sat1 = mysql_query($sql_Sat1);
while($row = mysql_fetch_array($result_Sat1))
{
echo "<ul><li>";
echo'<input type="checkbox" name="id[]" value="'.$row['id'].' " id="bandSched_' . $row['id'] . '" />';
echo '<label for="bandSched_' . $row['id'] . '">' . $row['timeShow']." ".$row['bandName'] . '</label>';
echo "</li></ul>";
}
SOLUTION- 'process.php'
if ( ! empty($_POST['id']))
{ foreach($_POST['id'] as $key => $id) { $_POST['id'][$key] = mysql_real_escape_string($_POST['id'][$key]); }
$in = implode(', ', $_POST['id']);
$sql_Sat2 = "SELECT * FROM bandSched WHERE id IN ($in) ORDER BY FIELD(id, $in)";
$result = mysql_query($sql_Sat2) or die('MySQL Error ' . mysql_errno() . ': ' . mysql_error());
}
if ( ! isset($result))
{
echo 'You did not select anything';
}
else
{
while ($row=mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>". $row['timeShow'] ."</td><td>" . $row['bandName'] . "</td>";
echo "</tr>";
}
}
Unless you have the attribute checked="checked" in your <input type="checkbox" />, the value will not be sent with the form data.
Try this:
echo '<input type="checkbox" value="' . $row['id'] .'"name="selected" checked="checked" />';
Does this solve the problem?
Carrying data from page to page can either be done with Sessions, Cookies, or posting hidden form elements containing the data.
Sessions provide you the data, but you still need to make a valid query. The only thing that sessions do are store data on the server. They do not keep any of the program execution, variables, etc.
Your error message is telling you that mysql_fetch_array was not supplied a MYSQL result resource (and it wasn't you supplied it an integer of the id value). The query will not be remembered across the session.
Also, mysql_* is deprecated, use PDO or mysqli.

PHP returned code not showing up, but it used to

I run a website for my church. In a database on the server, we store all of the newest sermons' information so that when a user clicks a button on the first page, the newest sermons will show up in a div. For a long time, everything was working just great, but now, the returned code just doesn't show up.
The weird thing is, if I open the page in Google Chrome and hit "Inspect Element" over the div, the returned code just appears. It looks perfect... After I have done that, clicking on the button will again load the info from the database and it will show up; if I refresh the page, however, the returned stuff goes away again until I inspect the element.
Try it for yourself here. Click the orange button labeled "New Message."
NOTE:
The div that pops up is id navNew
The background transparent div that pops up is id navBackground
Within the div id navNew, I have a p id navNewBody that holds the information returned by the get PHP page below.
My code for the PHP getter page:
<?php
$link = mysql_connect('domain', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db(flf);
$r = mysql_query("SELECT * FROM new");
$first = mysql_num_rows($r);
$last = $first - 20;
echo '<p class="NavHead">New Sermons<br/><table width="90%" border="0" cellpadding="0" cellspacing="0">';
$ind = 0;
while($first > $last){
$me=mysql_fetch_array(mysql_query("SELECT * FROM new WHERE id='" . $first . "'"));
$name = $me["name"];
$row = 21-$ind;
echo '<tr id="row' . $row . '" class="navClosed" onclick="expand(' . "'" . 'row' . $row . "'" . ',' . $row . ')"><td colspan="4"> ' . $name . '</td></tr><tr id="row' . $row . 'e" style="visibility: hidden" class="navOpenClosed" onclick="dismiss(' . "'" . 'row' . $row . "'" . ')"></tr>';
$first = $first - 1;
$ind = $ind + 1;
}
echo "</table></p>";
?>
And here is the code I use to access the page (yes I imported jQuery):
function retNew(){
document.getElementById("navNewBody").innerHTML = '<span class="NavHead"><p align="center">Loading...Please Wait...<br/><br/><br/><img src="Sermons/Style/Loading.gif" /></p></span>';
document.getElementById("navNew").style.visibility = "visible";
$("#navNewBody").load("retNew.php");
}
What's wrong? It just doesn't make sense to me. I set the z-index to 10,000,000 and nothing happened. Any ideas? Thanks in advance.
I think you visibility is messing with the content. Try to use this load.
function retNew(){
$('#navNewBody').html('<div class="NavHead"><p align="center">Text</p></div>')
.load('retNew.php');
$('#navNew').fadeIn();
}
As of the close button, in your case it should be something like that:
<div id="navNew">
<a class="LargeNameU" onclick="offNavNew();return false;"
style='position:fixed; z-index: 1000; right:0px;top:0px'>
<img src="Sermons/Style/x.png" border='0'>
</a>
<p align="center" style="z-index:10000000" id="navNewBody">
and so on. Your .navNew already has a fixed position.
The visibility property has some very weird problems. I would recommend using display instead. The only difference between the two is that display removes the element entirely when it's set to none, while visibility just essentially makes the element invisible (but still leaves a space in the page where the element was).

Dynamicly creating and checking checkboxes in php

I am trying to dynamically create php check-boxes linked to an MSSQL-Database. The idea is to List every item in the table, with a check box. From there the user will be able to check the check-boxes and click submit to change the value in 1 field of the Database to "A". I have the database linked to the php and It outputs the check-checkboxes and table values, however I do not know from there how to dynamically check the check-boxes to see if they are checked, or to use it from there.
This is roughly the approach you want to take to dynamically create checkboxes. There are of course prettier ways to accomplish this (i.e. Smarty templates).
<html>
...
<form method="post" action="submit.php">
<?php
// connect to DB here
$result = mysql_query("SELECT l.id, l.name, u.checked FROM List l LEFT JOIN UserAnswers u ON l.id = u.list_id WHERE u.user_id = 5");
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="cb_' . $row['id'] . '" ' .
'id="cb_' . $row['id'] . '" ';
if($row['checked'])
echo 'checked';
echo " />\n"
echo '<label for="cb_' . $row['id'] . '">' . $row['name'] . "</label><br />\n";
}
?>
<input type="submit" value="Submit" />
</form>
...
</html>
submit.php is a bit trickier. When a checkbox is checked, it will set a post item. However if it's unchecked, you won't get ANYTHING back, so you need to check your database for all the items you'll be expecting.
<?php
// connect to DB here
$result = mysql_query("SELECT id, name, checked FROM things");
$answers = Array();
while ($row = mysql_fetch_assoc($result))
{
$checked = isset($_POST['cb_' + $row['id']]);
$answers[$row['id']] = $checked;
}
// update your database here using $answers
foreach ($answers as $id => $checked)
{
$query = "REPLACE INTO UserAnswers SET user_id=5, list_id=" . $id . ", checked=";
if($checked)
$query .= "1";
else
$query .= "0";
mysql_query($query);
}
This is all off the top of my head, there are better ways to do most of this. It's just a general direction. I make no guarantees about any of this. Oh and it looks quite vulnerable to SQL injection, watch out for that.

Categories