Have radio buttons for each row of a query result - php

I am having issues with creating radio buttons for each query result. For each line returned I want to have an extra column that consists of 2 radio buttons. the user should only be able to select 1 of these 2 buttons. Right now I have the column of radio buttons but the user can only select 1 of each radio button, not 1 for each result of the query. I hope that makes sense.
Should I be even using radio buttons? Or should I use check boxes?
<!DOCTYPE html>
<html>
<head>
<title>games</title>
</head>
<body>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
<select name="weekNo">
<option value="1">week 1</option>
<option value="2">week 2</option>
<option value="3">week 3</option>
<option value="4">week 4</option>
<option value="5">week 5</option>
<option value="6">week 6</option>
<option value="7">week 7</option>
<option value="8">week 8</option>
<option value="9">week 9</option>
<option value="10">week 10</option>
<option value="11">week 11</option>
<option value="12">week 12</option>
<option value="13">week 13</option>
<option value="14">week 14</option>
</select>
<input type="submit" name="submit" value="Get Games" />
</form>
<br>
<hr>
<?php
$conn =
or die('Could not connect: ' . pg_last_error());
if(isset($_POST['submit'])) //submit button pressed
{
$query=NULL; //prevent compile error
$weekNum = $_POST['weekNo'];
$query = "SELECT a.game_no AS game_number, a.home AS home_team,
homeTeam.wins AS home_wins, homeTeam.losses AS home_losses,
a.away AS away_team, awayTeam.wins AS away_wins,
awayTeam.losses AS away_losses, a.spread AS spread
FROM weekly_stats AS a
INNER JOIN team AS homeTeam ON a.home = homeTeam.name
INNER JOIN team AS awayTeam ON a.away = awayTeam.name
WHERE a.week_no = $weekNum";
$result = pg_query($query) or die ('Query failed: ' .pg_last_error());
$query2 = "SELECT week_no, game_no FROM weekly_stats";
$result2 = pg_query($query2) or die ('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<br>There are " . pg_num_rows($result) . " records found.\n<p></p>\n";
echo "<table border=1>\n\t<tr>\n";
for($i=0; $i<pg_num_fields($result); $i++)
{
echo "\t\t<th>" . pg_field_name($result, $i) . "</th>\n";
}
echo "\t\t<th>Picks</th>\n";
echo "\t</tr>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo "\t<tr>\n";
foreach ($line as $col_value)
{
echo "\t\t<td>$col_value</td>\n";
}
echo "<td><input type=\"radio\" name=\"picks\" value=\"home\">Home
<input type=\"radio\" name=\"picks\" value=\"away\">Away</td>";
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
}
// Closing connection
pg_close($conn);
?>
</body>
</html>

The input name is the same on all of your radio buttons so the web browser is assuming they all answer the same question (Home or Away for ALL records) rather than a set of questions (Home or Away for EACH record). You need to differentiate the names for each pair of radio buttons for each row.
$row=0;
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo "\t<tr>\n";
foreach ($line as $col_value)
{
echo "\t\t<td>$col_value</td>\n";
}
echo "<td>"
."<label>Home <input type='radio' name='picks[$row]' value='home'></label>"
."<label>Away <input type='radio' name='picks[$row]' value='away'></label>"
."</td>";
echo "\t</tr>\n";
$row++;
}
On the server side it will interpret the submission as an array. The $row variable above could be a unique index or ID for each row rather than simply a counter as I demonstrated.

Radio buttons with the same names cannot be selected simultaneously. Radio buttons for each query should have unique names but names for two buttons of the same query should have the same name.
The code should be modified to:-
echo "<td><input type=\"radio\" name=\"picks[$row_number]\" value=\"home\">Home
<input type=\"radio\" name=\"picks[$row_number]\" value=\"away\">Away</td>";

Related

Dropdown and MySQl

I have a dropdown I dynamically populated from mysql
When I save the information it to mysql, it do not save the value of the dropdown list.
How do I set the selected value for the dynamic dropdown
Here is the code use to fill the dropdown.
How do I set the selected value on change in php
echo "<option value=\"" . utf8_encode($row['school_name']) . "\">" . utf8_encode($row['school_name']) . "</option>";
im have problems setting the correct format using this example
<option value="My School"<?php if ($row[school_name] == 'My School') echo ' selected="selected"'; ?>>My School</option>
Where My School should be the value populated from database
Ok
<select id="school_name" "name="school_name" style="width:200px;" name="school_name">
<option selected="">Select Province School</option>
</select>
i then fill the dropdownlist with following.
$sql="SELECT * FROM ppSD_schools where province_code ='".$_POST['c_id']."'";
$res = $conn->query($sql);
$num_rows = $res->num_rows;
if($num_rows > 0) {
echo "<option value=''>------- Select --------</option>";
while($row = $res->fetch_assoc())
{
?>
echo "<option value=\"" . utf8_encode($row['school_name']) . "\">" . utf8_encode($row['school_name']) . "</option>";
}
But when ever i select another school. it dont save the value selected to MySql
My guess is it dont mark the value as selected because it get filled dynamic
I now have to change the code so when i select it it must marked is as selected
I would use a repeated function to compare the value against the row value
<?php
function selected($a, $b) {
return ($a === $b) ? ' selected' : '';
}
?>
<option name="school" value="My School" <?= selected($row["school_name"], "My School"); ?>>My School</option>
<option name="school" value="Your School" <?= selected($row["school_name"], "Your School"); ?>>Your School</option>

Can't view records based on selected drop down values from two drop downs

I want to show a record from database based on the selected drop down value. I have a page which shows a drop down having column names and another drop down which shows the rows of that selected column from first drop down. After that there is a search button which shows all the records based on those two drop down menus i.e. the selected column name and selected row of that column. Then the search button shows a table having all the columns and shows that specific result.
Problem is I don't know how to use that drop down ids in the select query. Here is my code:
<form id="searchform" action="view.php" method="post" enctype="multipart/form-data" >
<select id="select1" onChange="check(this);">
<option selected value="" disabled="disabled">Select an Option</option>
<option value="all">Select All</option>
<option value="names" >Names</option>
<option value="courses" >Courses</option>
</select>
<select id="select2" disabled="disabled">
<option>Select an option</option>
<?php
$sql="SELECT DISTINCT names FROM table ";
$result = mysqli_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option class='names' value=' " . $row['names'] ."'>" . $row['names'] ."</option>";
}
?>
<?php
$sql="SELECT DISTINCT courses FROM table ";
$result = mysqli_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option class='courses' value=' " . $row['courses'] ."'>" . $row['courses'] ."</option>";
}
?>
</select>
<input type="submit" name="submit" value="Search" />
</form>
Now on view.php page
<body>
<?php
$count=1;
include("connection.php");
$select1=isset($_POST['select1']);
$select2=isset($_POST['select2']);
$result=mysql_query("SELECT names,courses FROM table WHERE names='.$_REQUEST['select2'].'");
echo "<table border='1' cellpadding='10'>";
echo "<tr><th>Names</th> <th>Courses</th></tr>";
while ($row=mysql_fetch_array($result)){?>
<tr>
<td align="center" ><?php echo $row["names"]; ?></td>
<td align="center" ><?php echo $row["courses"]; ?></td>
</tr>
<?php $count++; } ?>
</table>
</body>
</html>

Submit mysqli query only partly working

I am trying to find a way in PHP to combine data from several drop down boxes into one SQL statement. I can get this to partly work. Here is the SQL query:
$sql = "
SELECT *
FROM books
WHERE
author = '$bird'
AND genre = '$cat'
AND year= '$mouse'
AND publisher = '$goat'
";
$bird, $cat etc are the variables that hold the selection from each drop down box.
I am getting mixed results. All four will work together fine and all will work individually.
So If I select from authors, genre, year and publisher, then press select it works and if I select these individually they work as well.
But if try and just select two items, let's say author and year, it does not work and can produce a variety of incorrect data. Here is the complete code. Any help appreciated:
<html>
<head>
<title>My Page</title>
</head>
<body>
<br>
<form name="myform" action="authors3.php" method="POST">
<select name="author" size="2">
<option value="ken davies">ken davies</option>
<option value= "arthur smith">arthur smith</option>
<option value="gill rafferty">gill rafferty</option><br />
<option value="molly brown">molly brown</option><br />
<option value="gilbert riley">gilbert riley</option><br />
<input type = "submit" name = "submit" value = "go">
<select name="genre" size="4">
<option value="adventure">adventure</option>
<option value="biography">biography</option>
<option value="crime">crime</option><br />
<option value="romance">romance</option>
<option value="thriller">thriller</option>
<input type = "submit" name = "submit" value = "go">
<select name="year" size="4">
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<input type = "submit" name = "submit" value = "go">
<select name="publisher" size="4">
<option value="blue parrot">blue parrot</option>
<option value="yonkers">yonkers</option>
<option value="zoot">zoot</option>
<input type = "submit" name = "submit" value = "go">
<?php
$bird = (!empty($_POST['author'])) ? $_POST['author'] : null;
$cat = (!empty($_POST['genre'])) ? $_POST['genre'] : null;
$mouse = (!empty($_POST['year'])) ? $_POST['year'] : null;
$goat = (!empty($_POST['publisher'])) ? $_POST['publisher'] : null;
$con = mysql_connect("localhost","root","");
If (!$con) {
die("Can not Connect with database" . mysql_error());
}
mysql_select_db("authors",$con);
if (isset($bird) && isset($cat) && isset($mouse) && isset($goat)){
$sql = "SELECT * FROM books WHERE author = '$bird'
AND genre = '$cat' AND year = '$mouse' AND
publisher = '$goat' ";
}
else if (isset($bird)) {
$sql = "SELECT * FROM books WHERE author = '$bird' ";
}
else if (isset($cat)) {
$sql = "SELECT * FROM books WHERE genre = '$cat' ";
}
else if (isset($mouse)) {
$sql = "SELECT * FROM books WHERE year = '$mouse' ";
}
else if (isset($goat)) {
$sql = "SELECT * FROM books WHERE publisher = '$goat' ";
}
$myData = mysql_query($sql,$con);
echo"<table border=1>
<tr>
<th>id</th>
<th>author</th>
<th>title</th>
<th>publisher</th>
<th>year</th>
<th>genre</th>
<th>sold</th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['author'] . "</td>";
echo "<td>" . $record['title'] . "</td>";
echo "<td>" . $record['publisher'] . "</td>";
echo "<td>" . $record['year'] . "</td>";
echo "<td>" . $record['genre'] . "</td>";
echo "<td>" . $record['sold'] . "</td>";
echo "<tr />";
}
echo "</table>";
mysql_close($con);
?>
note: all four are working<br />
all work individually<br />
two or three dont work together
</form>
</body>
</html>
Apart from the fact that you're using a deprecated way connecting to MySQL (read up on SQL injection and PDO), you're not covering all the use cases in your code.
A better way might be to write a base query ($q = 'SELECT * FROM books WHERE), and extend that query with the appropriate extra WHERE clauses, based on checking if the parameter is empty or not (if (!empty($goat)) // append new clause to the WHERE portion).
You're query is half fine. Your declarations are the cause of your problem! The reason is you're essentially doing this:
genre ='adventure' and year = null.
What you want to do is edit your query accordingly. So you'll want to do
if (!is_null($year)) {
$sql.= "AND Year = $year";
}
Problem is the above method allows injection!! Which if you're fessed about is a BIG PROBLEM!!!!
So I would recommend using bind_params BUT having said that calling cal_user_func_array on bind_params is a bit tricky so I'd recommend using PDO where you can edit your query and manage your parameters safely and effectively

using multiple list menu and checkbox php

Am retrieving some data from the DB and am allowing users to make multiple selection via check box and also selecting a level for each selected check box. when saving, i only get to see the selected check boxes in the DB but not the level selected.
Code for making selection
include ('mysql_connect.php');
$sql = mysql_query("SELECT * FROM competency WHERE department = '$department'");
while($row = mysql_fetch_array($sql))
{
echo "<tr>";
echo "<td>";
echo"<input type='checkbox' name='comp[]' value= ".$row['id']." /> ".$row['competency']." <br /> </td>";
echo"<td> <select name='level[]'value= ".$row['id']." >
<option></option>
<option>level 1</option>
<option>level 2</option>
<option>level 3</option>
<option>level 4</option>
<option>level 5</option> </select> </td> ";
}
echo "</tr>";
?>
<input name="submit" type="submit" value="submit" />
</form>
<?php
echo" </table>";
?>
..
Code for saving into the DB
session_start();
$id = $_SESSION['user_id'];
$hobb = $_POST['comp'];
$level = $_POST['level'];
include ('mysql_connect.php');
$N = count($hobb);
for($i=0; $i < $N; $i++)
{
$var1=$hobb[$i];
$var2 = $level[$i];
//include ('connect.php');
include ('mysql_connect.php');
$table = "INSERT INTO competency_result (user_id,competency_id,level) ".
"VALUES ('$id', '$var1', '$var2')";
mysql_query($table) or die(mysql_error());
$inserted_fid = mysql_insert_id();
mysql_close();
}
Set the key the same for comp[] and level[], ie. $row['id'] -
while($row = mysql_fetch_array($sql))
{
...[your code]...
echo "<input type='checkbox' name='comp[".$row['id']."]' value= ".$row['id']." /> ".$row['competency']." <br /> </td>";
echo "<td> <select name='level[".$row['id']."]' >
...[your code]...
}
(note: the <select> does not have a value attribute. That is defined by the <option>)
Then you can easily get the corresponding values using
foreach($hobb as $key=>$val)
{
$var1=$hobb[$key];
$var2=$level[$key];
...[your code]...
}
(also, it looks like you have <tr> inside your loop, but </tr> after. I would assume you would want to move the closing tag inside the loop to properly close each row)

PHP- Fetch from database and store in drop down menu html

I can't seem to get the following code to make a dropdown menu that contains data from a mysql database. The "include('connect.php');" connects to the mysql database and I know it works on separate pages. Any suggestions?
Below is the entire code.
listCustomer
<BODY>
<H1>Find Customer's Albums Page</H1>
From a dropdown list of customers, a user should be able to pick a customer and see a list of albums (all fields in the CD table) purchased by that customer.
<HR>
<FORM ACTION="listCustomer.php" METHOD="POST"/>
Customer:
<select name="mydropdownCust">
<option value="101">101</option>
<option value="102">102</option>
<option value="103">103</option>
<option value="104">104</option>
<option value="105">105</option>
<option value="106">106</option>
<option value="107">107</option>
<option value="108">108</option>
<option value="109">109</option>
<option value="110">110</option>
</select>
<BR>
<?php
include('connect.php');
$query = "SELECT Cnum, CName FROM Customer";
$result = mysql_query ($query);
echo "<select name=dropdown value=''>Dropdown</option>";
while($r = mysql_fetch_array($result))
{
echo "<option value=$r["Cnum"]>$r["CName"]</option>";
}
echo "</select>";
?>
<BR>
<INPUT TYPE="SUBMIT" Value="Submit"/>
</FORM>
<FORM ACTION="listMenu.html" METHOD="POST"/>
<INPUT TYPE="SUBMIT" Value="Main Menu"/>
</FORM>
</BODY>
</HTML>
<?php
include('connect.php');
$query = "SELECT Cnum, CName FROM Customer";
$result = mysql_query ($query);
echo "<select name='dropdown' value=''><option>Dropdown</option>";
while($r = mysql_fetch_array($result)) {
echo "<option value=".$r['Cnum'].">".$r['CName']."</option>";
}
echo "</select>";
?>
From the looks of things, you're missing an opening option tag, so it's just outputting "Dropdown" as a line of text.
Edit
Just to be completely transparent, because I did not have connect.php, I had to add my own DB connections. My whole page looked thusly:
<?
//Adding to display errors.
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<HTML>
<HEAD>
</HEAD>
<BODY>
<H1>Find Customer's Albums Page</H1>
From a dropdown list of customers, a user should be able to pick a customer and see a list of albums (all fields in the CD table) purchased by that customer.
<HR>
<FORM ACTION="listCustomer.php" METHOD="POST"/>
Customer:
<select name="mydropdownCust">
<option value="101">101</option>
<option value="102">102</option>
<option value="103">103</option>
<option value="104">104</option>
<option value="105">105</option>
<option value="106">106</option>
<option value="107">107</option>
<option value="108">108</option>
<option value="109">109</option>
<option value="110">110</option>
</select>
<BR />
<?php
// BEGIN ADDED CONNECTION HACKY GARBAGE
$con=mysql_connect("localhost","root","root");
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$selected = mysql_select_db("sample",$con)
or die("Could not select examples");
// END ADDED CONNECTION HACKY GARBAGE
$query = "SELECT Cnum, CName FROM Customer";
$result = mysql_query ($query);
echo "<select name='dropdown' value=''><option>Dropdown</option>";
while($r = mysql_fetch_array($result)) {
echo "<option value=".$r['Cnum'].">".$r['CName']."</option>";
}
echo "</select>";
?>
<BR />
<INPUT TYPE="SUBMIT" Value="Submit"/>
</FORM>
<FORM ACTION="listMenu.html" METHOD="POST"/>
<INPUT TYPE="SUBMIT" Value="Main Menu"/>
</FORM>
</BODY>
</HTML>
First off, you are missing an option opening tag, as correctly mentioned by stslavik. But this is not causing the issue here as it seems (it's auto-corrected by the browser - in my tests atleast).
Secondly, this wont work (problem causer):
echo "<option value=$r["Cnum"]>$r["CName"]</option>";
You should use
echo "<option value=".$r["Cnum"].">".$r["CName"]."</option>";
or, as I always prefer single quotes to enclose echo or print output strings:
echo '<option value='.$r['Cnum'].'>'.$r['CName'].'</option>';
Third alternative (complex syntax: What does ${ } mean in PHP syntax?)
echo "<option value={$r["Cnum"]}>{$r["CName"]}</option>";
assuming you get data from the database try this
echo "<option value={$r['Cnum']}>{$r['CName']}</option>";
try,
echo "<option value=' . $r['Cnum'] . '>' . $r['CName'] . '</option>";
instead of
echo "<option value=$r[Cnum]>$r[CName]</option>";

Categories