I am busy working on a university assignment which must do the following:
Show list of sporting events for week
User Submits the teams they think will win
At end of week, calculate which users had the most correct picks
In working on above I have created a form like this, which lets the user select who they think will win.
The form data is collected from a database called events which looks like this:
My form is generate with the following code
//create form
echo'<form name="" action="" method="post">';
echo'<fieldset>';
echo'<legend>Make Your Picks</legend>';
//create query
$sql = "Select * FROM events";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)){
$team1 = $row['team1'];
$team2 = $row['team2'];
//dislay teams
echo'<h3>'.$team1.' VS '.$team2.'</h3>';
echo'<select name="'.$row['event_id'].'">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
}//while
echo'</legend></fieldset>';
echo'<input type="submit" class="buttono" value="Submit" name="submit" />';
echo'</form>'
I would like to get a more experienced users opinion on my logic and perhaps a tip if I am on the correct path and what I could be doing better, in terms of implementation,since I have ZERO confidence in my current approach.
I am creating multiple selectboxes inside the while loop, each select box has a unique name of the event_id value from db which will get inserted into the picks database (see below), this doesn't seem very efficient is there an alternative way I can approach this?
Am I correct in assigning the name attribute of the selctbox the value of the fixture_id?
Is there perhaps a more efficient way I can approach this problem that you can suggest?
Just thought it would be interesting getting an experienced users view on this
use an array for your name variable like name="event[7]" which would look like
echo'<select name="event['.$row['event_id'].']">';
then when you are gathering data you run a loop like
foreach($_POST['event'] as $event_id => $winner){
// do something here
}
Related
I'm trying to create a form that retrieves data from a database and then allows me to add data to one column for multiple entries.
Every entry has an ID, a lot of other fields, and a category. I am trying to add these categories for every ID in the database using one form.
I came up with the solution below, but (of course)this only inserts the LAST entry in the form, because the variable ID is changed with every new row.
The form I have now shows me what I want to see, but it does not save it the way I need it to.
The question is, (how) can I make a form that has all entries in the database with a dropdown menu next to it,
lets me select the right category from the dropdown, and save it to the database?
The form:
$result = mysqli_query($con,"SELECT * FROM aw");
while($row = mysqli_fetch_array($result))
{
echo '<tr><td><input type="hidden" name="ID" value="'.$row[ID].'."> '.$row[ID].'</td><td>';
echo '
<select name="cat" onchange="this.form.submit()">
<option value="C1">category1</option>
<option value="C2"">category2</option>
</select></td></tr>
';
}
?>
<tr><td><input type="submit" title="SAVE" ></td></tr>
</form>
The insert.php
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$_POST[ID]','$_POST[cat]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
I changed my code according to Tom's answer and I now have the following:
This does print the values like they should be, but it still saves only the last entry into the database. I'm sure I must be missing something here..
$name = $_POST['ID'];
$category = $_POST['cat'];
foreach( $name as $key => $n ) {
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$n','$category[$key]')";
print "The id is ".$n.", category is ".$category[$key]."<br>";
}
First of all, use PDO::Mysql, the SQL functions you are using are a bit deprecated and do not focus much on security. At the moment your code is vulnerable to SQL injections and your output is sensitive to XSS attacks (always sanitize output).
I was wrong, MySQL is deprecated but MySQLi is not! I do prefer using PDO::Mysql because of the range of databases it supports (MySQLi only supports a MySQL database, PDO::Mysql supports many more)
Now to your original question, you can create a sort of array. By making name="ID" to name="ID[]" and name="cat" to name="cat[]".
Now you can do
$name = $_POST['ID'];
$category = $_POST['cat'];
foreach( $name as $key => $n ) {
print "The id is ".$n.", category is ".$category[$key];
}
The problem is your using the name elements regardless of how many rows..
So name="ID" & name="cat" needs to change on each row or have an array type
you could use something like name="ID[]" as this would append/ create an array to $_POST['ID']... but you still would want to change your SQL query to handle each of these.
EDIT
If i understand, you want to be able to identify a row from the table so you can use that in the database?? One way todo this is when creating the table.. Give the TR a id/name attribute that is the row id from the database.
Then can simply know by checking that if your using the select menu from row #4, you check the id/name attribute of the current row and you have your database id.
<tr id='my_row_1'>
<td class='colName'>John</td>
<td class='colPhone'>1111</td>
<td class='colOther'>....</td>
</tr>
<tr id='my_row_2'>
<td class='colName'>Bill</td>
<td class='colPhone'>2222</td>
<td class='colOther'>....</td>
</tr>
<tr id='my_row_3'>
<td class='colName'>Roger</td>
<td class='colPhone'>3333</td>
<td class='colOther'>....</td>
</tr>
With something like the above, Say i had a button in on of the columns... When i click on that button.. all i have todo is find the parent TR and get its id value.... Then explode it by "_" and get the last piece to have the id..
So your PHP would generate the id easily... Also, using a form would not be the best case here.. Using multiple forms within a table is... wasteful... sort of ..
I would suggest more so, having a button that simple calls a js function which will then post/ajax/jquery what you need from that row.
--- Trying to understand exactly what you need??
My webpage is pulling data from two tables - applications and archiveapps - and displays them using the following:
$sql = "SELECT * FROM applications";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Lots of info, including some html thrown in for style."
I want users to be able to click a checkbox listed next to each row and then hit an "Archive Selections" button that then moves all the selected entries from the applications table to the archiveapps one.
So far I've tried a form with it's code half in the echo above (so that a checkbox would go by each listed row from the $sql query) with the submit button outside (so that there would only be one "Archive Selections" button) but I'm sure this isn't proper syntax.
To actually move the data, I had this for the checkbox:
<form method='post' action=''><input type='checkbox' name='archname' value=".$row["charname"].">
(The above was inside an echo statement, so I assume it was able to pull the $row["charname"] no problem, but am unsure how to verify that.)
A little further down the page is the submit button and </form>.
And then I've got the function I want it to run when the submit button is clicked, to check if boxes have been selected and copy them into the archiveapps table. I'm sure there's something I'm missing here, probably in referencing what exactly is selected, and then copying that row's data to the other table... but honestly I just don't know enough about php to know what I'm missing.
if(!empty($_POST['archname'])) {
foreach($_POST['archname'] as $check) {
function archiveapp() {
$sqli="INSERT INTO archiveapps SELECT * FROM applications";
if ($conn->query($sqli) === TRUE) {
echo "<i>Archived</i>";
} else {
echo "Error: " . $sqli . "<br>" . $conn->error;
}}}}
Most of this has just been gathered from google searches and kind of mushed together, so I'm sure there are a lot of things done wrong. Any pointers or advice would be greatly appreciated!
Oh and my end goal is to copy the data to the archiveapps table and then delete it from the applications table, but for now I've just been focusing on the copying part, since I assume deleting a row will be fairly simple? Either way it's not the priority for this question.
Thanks in advance for any help!
Use a tool like FireBug to see what you are actually posting to server. You have multiple checkboxes with the same name, so you are sending only 1 value (the last checked, I think).
You need to send all of them, so use brackets after the name:
<!-- this is just an example -->
<input type="checkbox" name="archname[]" value="1">
<input type="checkbox" name="archname[]" value="2" checked>
<input type="checkbox" name="archname[]" value="3" checked>
Then on PHP, inside $_POST['archname'] you will get this:
Array(2, 3)
After this, you can do a foreach(...) loop like you are already doing, inserting only the ID you get from the $_POST variable:
foreach($_POST['archname'] as $id){
$sqli = "INSERT INTO archiveapps (id) VALUES (".(int)$id.")";
}
Sorry if this has been asked and answered but I have looked and can't see it anywhere. Yes I am a nooby.
I have a DB with 3 tables: flour, filler and others.
What I would like to do is have a dropdown List. So, if user chooses flour from the Drop Down box it will display flour table. If the user chooses filler then filler table be displayed.
Hope this is clear. I hope you can help. Thanks in advance.
<Form id="form1" name="form1" method="get" >
Supplies of
<select name=filler action="flour.php">
<option value="1" selected>flour</option>
<option value="2">filler</option>
<option value="3">others</option>
</select>
<input type="submit" value="Submit" />
</form>
<?php
header("Content-Type: text/html; charset=windows-1251");
#mysql_connect('localhost','root','');
#mysql_select_db('krendel');
#mysql_query('SET NAMES cp1251');
$res = mysql_query("SELECT * FROM `flour` ") or die(mysql_error());
$res2 = mysql_query("SELECT * FROM `filler` ") or die(mysql_error());
$res3 = mysql_query("SELECT * FROM `addit` ") or die(mysql_error());
Add the action to the form, not select element. So you'd have
<form method="get" action="flour.php">
and
In your form processing script (flour.php), you could so something like this:
switch($_GET['filler'])
{
case '1':
$table = 'flour';
break;
case '2':
$table = 'filler';
break;
case '3':
default:
$table = 'addit';
}
$res = mysql_query("SELECT * FROM {$table}");
If all tables have the same structure, consider combining the tables, and adding a type column (varchar containing either flour, filler, or addit for simplicity).
you could then write the query like this (still using the $table variable name to work with the code above.
$res = mysql_query("SELECT * FROM table WHERE type='{$table}'");
Using mysql_query, and concatenating variables into the SQL is not good practice now - have a look at PDO and parameterised queries as you learn more.
Some quick and dirty display code:
<?php
$results = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC)) { ?>
$results[] = $row;
}
?>
<table>
<?php foreach($results as $result) { ?>
<td><?php echo $result['column_name'] ?></td>
<?php } ?>
</table>
This should get you started - as I said above, it's quick and dirty. You'll be able to improve upon this as you get more knowledge (properly separating out the HTML from PHP, for example - it's really worthwhile reading up on MVC amongst other patterns).
Just don't use this code on a production system!
Hope this helps.
The page that is going to display the table needs to check the $_GET['filler'] and see what the value is. Since you are using $_GET and a drop box, you should have a white list something like: $filler_white_list = array('flower', 'filler', 'other');
Check to see if the value of $_GET['filler'] is in the $filler_white_list array. If the $_GET['filler'] value is valid, then make your query:
$res = mysqli_query('SELECT * FROM '.$_GET['filler'].';') or die(mysqli_error());
Then loop through the result set to print out to the page:
while($row = mysqli_fetch_array($res)){
//get the columns by using $row['column_name']
//decide how you want to format
}
Things to note: I used mysqli instead of mysql, because the mysql is deprecated (no longer supported), The SELECT statement uses an *, but it is better to list out the names of the column since it is faster. It is not a good idea to use the the values of the drop box as the name of you tables in the database. The less information you reveal about your database, the better. Of course, if this is not for a production DB, then it doesn't matter. But, I think it is always best to think about security even when you're just practicing. Also, I put the $_GET['filler'] in the middle of the SELECT statement because the table's names are the same as the drop box.
I run a script to create an order form, this is just a really small sample. I'm not so good with PHP and dynamic forms. It pulls data from mysql database.
<td>
<h3>Round Cuts</h3>
<?php while($row = mysql_fetch_array($round_cuts)){
$round_box_value = #$row["meat_names"];
$round_box_value_name = #$row["meat_names"];
echo " <input type=\"checkbox\" name=\"round_box_value\" value=\"$round_box_value_name\"> $round_box_value_name";
echo "<br>";
}?>
</td>
I've ever really only built basic contact forms, how could I process a dynamic form like this. If all else fails I would just take all the possible elements and program this like it was a not dynamic. There must be a better way though.
Even a link to a website would be helpful. I've been searching for a solution. Thanks.
I'll assume your table as a primary key of id
Start off with a minor change to your checkboxes:
<?php
while($row = mysql_fetch_array($round_cuts)){
echo sprintf('<label><input type="checkbox" name="round_box_value[]" value="%s"> %s</label><br>', $row['id'], $row['meat_names']);
}
?>
The name now has an [] at the end to tell php it's an array of values + I've wrapped the checkbox in a label for convenience.
Then when you process the form, you can simply iterate through round_box_value like so
<?php
foreach ($_POST['round_box_value'] as $id) {
// $id is the table reference from your previous table
}
// or query all the rows selected
$ids = array_map('intval', $_POST['round_box_value']); // "basic" sql injection handler
$sql = "SELECT * FROM table WHERE id IN (".implode(",", $ids).")";
should produce something like:
SELECT * FROM table WHERE id IN (2,5,7)
Can any one please help me? I am new to php, currently I am trying to use $_POST['item'] to obtain a string (consists of many words) from a dropdown box and then process it. However, when I use $_POST['item'], only first word is returned, the rest of words are missing.
I have a dropdown box, something like:
echo "<form action='process_form.php' method='post'>";
echo "Select an item<br />";
echo "<select name='item' id='item'>";
...
...
...
each item in the dropdown box is a string that has product names like:
dressmaker mannequin size 12
torso mannequin in white color
...
User will then select an item from the dropdown box. When I used $_POST['item'] to obtain this string, I get the first word "dressmaker", all the rests were missing.
How do I get the whole string?
Many thanks in advance.
I am not sure exactly what you are doing but I would do something like this. For this example I assume that the values "dressmaker mannequin size 12" will correspond to the values of the columns in the database to which I will refer to as "colA, colB, colC, and colD", and in addition I assume you have an "ID" column in your database.
Here is the code I would use to generate the select drop-down list:
//$query is the variable storing the result of the mysql_query();
//assumption is that the result-set is non-empty
echo '<select name="item" id="item">\n'; //\n - new line character
//run through the loop to generate the items inside the list
while ($result = mysql_fetch_assoc($query)) {
//note the id - it will be used to find data in the
//database after the POST is complete
//couple of temp variables (not necessary but makes code cleaner)
$database_id = $result["ID"];
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//add option to the select drop-down
echo "<option value=\"$database_id\">$colA $colB $colC $colD</option>\n";
}
echo "</select>";
Now to retrieve the data from the POST. I am including the code Drewdin suggested.
//form was submitted already
//assumption is that the database connection is established
$item_id = mysql_real_escape_string(trim($_POST["item"]));
//Now get the info from the database for this id
//table is "table"
$string = "SELECT * FROM table WHERE ID = $item_id";
$query = mysql_query($string) or die("Could not complete the query: $string");
//assumption here is that the result set is non-empty
$result = mysql_fetch_assoc($query);
$colA = $result["colA"]; //ex:dressmaker
$colB = $result["colB"]; //ex:mannequin
$colC = $result["colC"]; //ex:size
$colD = $result["colD"]; //ex:12
//now you can use the values of colA-D to compute whatever you want
Hope this helps. Using database ids is nice for security plus it makes things more manageable.
Regarding using this blog. You can post comments to the answers people post. If you want however to add something to your question, you can edit your original question and just make sure its obvious what was added.
When the issue is resolved and if any answer helped and you liked it, you can pick it as the final answer by clicking the check mark next to it.
Best of luck
without seeing your select options i think this might help you
if (isset($_POST['submit'])) {
// Grab the output of the select list
$Select_Output = mysqli_real_escape_string( $dbc, trim($_POST['item']));
//What ever else you want to do here...
}
I also would use Miki725's post to make sure your select list is setup correctly
This is how the php gets the values from the HTML select item:
<select name="item" id="item">
<option value="this is option 1">option 1</option>
<option value="this is option 2">option 2</option>
<option value="this is option 4">option 3</option>
...
</select>
Basically you would do something like:
$var = $_POST['item'];
The $var will be the whatever was entered into the "value" of the option tag. So just make sure you have the proper values entered into the value fields.
Hope that helps.