display a table when a button is pressed [duplicate] - php

I'm having trouble adding the value of type="button" form elements to a mySql database, and I'm wondering if I'm missing something.
Edit - It doesn't look like the information for that element is being passed from the html to the php because it's not echoing a value. My only problem is with this one element and the rest of the form is being submitted properly.
I'm using this for an online quiz which builds a user profile based upon images they've selected, and am setting the images as background images for the button elements, and I'm trying to do this in straight html (as opposed to using javascript together with radio buttons or check boxes).
<input type="button" name="quiz_start" value="jeans" style="background: url(files/start1.jpg) no-repeat; width:54px;height:140px; cursor:pointer; border:none; color: transparent; font-size : 0">
I've simplified the php code for purposes of asking the question (including specifying the user id and limiting it to only one field). I've also included the full code below.
<?php
//Start session & connect to database
$user_id = 3;
$qry = "INSERT INTO style(user_id, quiz_start) VALUES('$user_id','$_POST[quiz_start]')";
$result = #mysql_query($qry);
header("location: page2.html");
exit();
?>
The full query is:
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.($value).'\',';
}
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$fieldlist.=', user_id';
$vallist.=','.$user_id;
$setlist='';
foreach ($_POST as $key=>$value){
$setlist.=$key .'=\''.$value.'\',';
}
$setlist=substr($setlist, 0, -1);
$result = mysql_query('UPDATE style SET '.$setlist.' WHERE user_id='.$user_id);
if (mysql_affected_rows()==0) {
$result = mysql_query('INSERT INTO style ('.$fieldlist.') VALUES ('.$vallist.')');
}
header("location: page2.html");
exit();
?>

Seeing that you are unable to echo $_POST['quiz_start'] that means your value is not actually set. This is because when you use a class button as in <input type='button'> your form is not actually submitted like <input type='submit'>
One solution would be to change your button to an actual submit and format that... or you need to call a javascript function with an onClick from your button as in:
<input type="button" onClick="myfunction()">
For reference to what I am talking about look at this post.
If as you say the rest of the form values are submitting fine but just the button value is not working you have a few different possible solutions depending on your preference.
Use a select field or checkbox for people to select a type in which you can pass your data.
Submit your form in javascript with <input type="button" onClick="myfunction()"> then running your update query in javascript.
Finally if you still want to run your query in PHP you can run a javascript function to make an AJAX call to return JSON information in which you can define a php variable after the page has loaded in which you can then plug into your update query.

Try this:
<?php
//Start session & connect to database
$user_id = 3;
$qry = "INSERT INTO style(user_id, quiz_start) VALUES('".$user_id."','".$_POST['quiz_start']."')";
$result = #mysql_query($qry);
header("location: page2.html");
exit();
?>

Since it seems that input type="button" can't capture the user's selection, I wanted to share a really simple way I figured out for doing this with radio buttons or check boxes using only html.
All you need to do is set the input element to style="display:none", and surround both the image and input element with a label tag so that users can click anywhere on the image to select the element :-)
<label for="quiz_start">
<img src="files/start1.jpg" />
<input style="display:none" type="radio" id="quiz_start" name="quiz_start" value="jeans">
</label>

Related

Value from input type="button" isn't being added to database

I'm having trouble adding the value of type="button" form elements to a mySql database, and I'm wondering if I'm missing something.
Edit - It doesn't look like the information for that element is being passed from the html to the php because it's not echoing a value. My only problem is with this one element and the rest of the form is being submitted properly.
I'm using this for an online quiz which builds a user profile based upon images they've selected, and am setting the images as background images for the button elements, and I'm trying to do this in straight html (as opposed to using javascript together with radio buttons or check boxes).
<input type="button" name="quiz_start" value="jeans" style="background: url(files/start1.jpg) no-repeat; width:54px;height:140px; cursor:pointer; border:none; color: transparent; font-size : 0">
I've simplified the php code for purposes of asking the question (including specifying the user id and limiting it to only one field). I've also included the full code below.
<?php
//Start session & connect to database
$user_id = 3;
$qry = "INSERT INTO style(user_id, quiz_start) VALUES('$user_id','$_POST[quiz_start]')";
$result = #mysql_query($qry);
header("location: page2.html");
exit();
?>
The full query is:
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.($value).'\',';
}
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$fieldlist.=', user_id';
$vallist.=','.$user_id;
$setlist='';
foreach ($_POST as $key=>$value){
$setlist.=$key .'=\''.$value.'\',';
}
$setlist=substr($setlist, 0, -1);
$result = mysql_query('UPDATE style SET '.$setlist.' WHERE user_id='.$user_id);
if (mysql_affected_rows()==0) {
$result = mysql_query('INSERT INTO style ('.$fieldlist.') VALUES ('.$vallist.')');
}
header("location: page2.html");
exit();
?>
Seeing that you are unable to echo $_POST['quiz_start'] that means your value is not actually set. This is because when you use a class button as in <input type='button'> your form is not actually submitted like <input type='submit'>
One solution would be to change your button to an actual submit and format that... or you need to call a javascript function with an onClick from your button as in:
<input type="button" onClick="myfunction()">
For reference to what I am talking about look at this post.
If as you say the rest of the form values are submitting fine but just the button value is not working you have a few different possible solutions depending on your preference.
Use a select field or checkbox for people to select a type in which you can pass your data.
Submit your form in javascript with <input type="button" onClick="myfunction()"> then running your update query in javascript.
Finally if you still want to run your query in PHP you can run a javascript function to make an AJAX call to return JSON information in which you can define a php variable after the page has loaded in which you can then plug into your update query.
Try this:
<?php
//Start session & connect to database
$user_id = 3;
$qry = "INSERT INTO style(user_id, quiz_start) VALUES('".$user_id."','".$_POST['quiz_start']."')";
$result = #mysql_query($qry);
header("location: page2.html");
exit();
?>
Since it seems that input type="button" can't capture the user's selection, I wanted to share a really simple way I figured out for doing this with radio buttons or check boxes using only html.
All you need to do is set the input element to style="display:none", and surround both the image and input element with a label tag so that users can click anywhere on the image to select the element :-)
<label for="quiz_start">
<img src="files/start1.jpg" />
<input style="display:none" type="radio" id="quiz_start" name="quiz_start" value="jeans">
</label>

PHP if else statement from two buttons

I'm trying to make a simple vote script in PHP and need help. The problem I'm having is that I've created a form with two buttons, like and dislike, which correspond to an if else statement.
If the like button is clicked do an update, else the dislike button was clicked do an update.
Here is the code I have so far, there is more above it, but not necessary to my problem:
while($row = $q2->fetch())
{
$up_vote= $row['up_votes']; /*Current Up Votes*/
$down_vote= $row['down_votes']; /* Current Down Votes*/
echo '<form method="post" action="">';
echo '<input type="button" id="up_vote" name="up_vote" value="Like" /> OR';
echo '<input type="button" id="down_vote" name="down_vote" value="Dislike" />';
echo '</form>';
echo round($row['rating'], 0);
echo '% of voters Liked this';
}
$up_votes = $up_vote +1;/*$up_vote referes to original # of up_votes, $up_votes adds 1 to the number of votes*/
$down_votes = $down_vote +1;/*$down_vote referes to original # of down_votes, $up_votes adds 1 to the number of votes*/
if ($something);/*upvote clicked*/
{
$vote_update = "UPDATE images
SET up_votes:up_votes
WHERE vote_item_id: vote_item_id";
$q3 = $conn-> prepare($vote_update);
$q3->execute(array(':up_votes'=>$up_votes, /*$up_vote referes to original # of up_votes, $up_votes adds 1 to the number of votes*/
':vote_item_id'=>$current_vote_item_id));
/* ALSO create INSERT INTO votes_done to track the user vote*/
$conn = null;
}
else ($something2);/*down vote clicked*/
{
$vote_update = "UPDATE images
SET down_votes:down_votes
WHERE vote_item_id: vote_item_id";
$q3 = $conn-> prepare($vote_update);
$q3->execute(array(':down_votes'=>$down_votes, /*$down_vote referes to original # of down_votes, $up_votes adds 1 to the number of votes*/
':vote_item_id'=>$current_vote_item_id));
/* ALSO create INSERT INTO votes_done to track the user vote*/
}
What should the if and else statements look like? I'm not sure how to go about this, can't have two submits, should I have two different forms, one for each button? Either way how can I say if like was clicked go to if and run code, or if dislike was clicked go to else and run code?
Thanks
Syntax errors aside, you can give the two buttons the same name, but different values.
echo '<form method="post" action="___URL OF YOUR PAGE___">';
echo '<input type="submit" id="up_vote" name="vote" value="Like" /> OR';
echo '<input type="submit" id="down_vote" name="vote" value="Dislike" />';
echo '</form>'
...
if($_POST['vote'] == "Like") {
...
} else if ($_POST['vote'] == "Dislike") {
...
}
Note that I changed the input's type to submit instead of button. This will cause the data to send itself to the page (button won't do anything unless you start adding JavaScript).
You can read more about this in these answers:
https://stackoverflow.com/a/6129301/1451957
html button v.s. html submit?
PHP is server side, while you want to control events triggered in client side (a user clicks one button, or another).
Javascript/Jquery are client side, there you can control and trigger events that call to PHP scripts that will do the query.
Also else(){ is not valid in PHP, you should use elseif(){.
This sounds like an instance where using JavaScript would be more useful, but if you really want to use PHP you can either use two separate forms or change the buttons to links that look like buttons and add URL parameters.
Also: you've got some syntax errors. Examples: you shouldn't be putting semicolons after your if/elseif conditions, else() should be elseif(), you're using two different variable names when trying to increment $up_votes and $down_votes, etc.
Why dont't you add an 'onclick' event to each of the like and dislike buttons, and execute different script?

check if checkbox is checked in php

I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>

implement a button to send information to another php file?

I've got the following php code printing out the contents of a SQL table.
$query="select * from TABLE";
$rt=mysql_query($query);
echo mysql_error();
mysql_close();
?>
<i>Name, Message, Type, Lat, Lng, File </i><br/><br/>
<?php
while($nt=mysql_fetch_array($rt)){
if($nt[name] != null){
echo "$nt[id] $nt[name] $nt[message] $nt[type] $nt[lat] $nt[lng] $nt[file]";
}
}
?>
How would I implement a button so for each "row" if the button is clicked on that row it'll submit the information of that row to another php file?
I want it looking something like...
details details2 details3 BUTTON
details4 details5 details6 BUTTON
details7 details8 details9 BUTTON
details10 details11 details12 BUTTON
Where if BUTTON was hit on row 1 details1,2,3 would be sent to a php file, on row 2 detals 4,5,6 would be sent etc. How would I do this?
Thanks.
it's going to be something like that, depending on the data you need to send:
while($nt = mysql_fetch_array($rt)) {
if($nt[name] != null){
echo "$nt[id] $nt[name] $nt[message] $nt[type] $nt[lat] $nt[lng] $nt[file] ".'send request<br/>';
}
}
You can either use GET method and send a query string to the second php page and receive the variables there, like
next.php?variable1=value1&variable2=value2&...
or use POST method by making a hidden form for each row and assign a hidden field for each variable you want to send.
<form method="post" action"next.php">
<input type="hidden" name="variable1" value="value1" />
<input type="hidden" name="variable2" value="value2" />
.
.
.
</form>
or instead of sending all the values, just send the row ID (if any) using any of these two methods and run another query in next.php to get the information you need from database.
Instead of submitting the entire data, just send the ID and fetch the results from the database in the other script. If you want to have an input button, you can do
<form action="/other-script.php" method="GET">
<?php printf('<input type="submit" name="id" value="%s" />', $nt["id"]); ?>
</form>
but you could also just add a link, e.g.
printf('Submit ID', $nt["id"]);
If you really want to send the entire row values over again, you have to make them into form inputs. In that case, I'd send them via POST though.

Can one form have multiple actions?

I am wanting to submit a form to different places based on selections made in the form. I had originally been planning to to send all to a central file/location and have it determine where to go next. However, I would like to do without this extra step if I could.
If the user wants to create/edit/delete elements go to page 1.
If the user wants to group/attach elements go to page 3.
I am trying to write a form builder. You can create/edit/delete forms, questions, and answers. I have everything for creating, editing, and deleting done. Those functions are performed without leaving the page, but now I am looking to assign answers to specific questions. The questions page and the answers page are separate. I am wanting to select a group of answers and submit an array of answer Ids (selected check boxes) to the question page where those Ids will then be assigned to a question. So basically the create, edit, and delete functions are on without leaving the page, but the assign function would be performed on a different page.
if(empty($delRowID) || empty(updateRowID) || empty($groupRows)) {
qInsert();
}else{
if(!empty($delRowID)) qDelete($delRowID);
if(!empty(updateRowID)) qUpdate($updateRowID);
if(!empty($groupRows)) {
submit $groupRows to Question.php;
}
}
No, a form has only one action.
But you have options:
Javascript
However, you may change the action attribute with javascript:
<input type="submit" value="Edit" onclick="editform();return true;">
<input type="submit" value="Delete" onclick="deleteform();return true;">
together with a little javascript:
function editform() {
document.myform.action = '/edit';
}
function deleteform() {
document.myform.action = '/delete';
}
See also
How to set form action through JavaScript?
Different form ACTION depending on button pressed
jquery, changing form action
Multiple forms
If javascript is not an option for you, you may consider multiple forms in your page.
Multiple forms = multiple actions
No problems with javascript disabled clients, and standards compliant.
Multiple submit buttons - server side
Or you may handle the distinction of editing or deleting on the server side. No javascript needed.
Add multiple submit buttons to your form and give them the same name but a different value:
<input type="submit" name="btSubmit" value="Edit">
<input type="submit" name="btSubmit" value="Delete">
You then can retrieve the value of the button which has been clicked. In php, the following should do the job:
$_POST['btSubmit']
See http://www.chami.com/tips/internet/042599I.html for an example with classic asp.
It is possible using JavaScript, but it's not recommended because some people turn JS off by default because of trojans and noisy behavior of some sites. It is considered polite to have your site working both with JS enabled and disabled.
Actually you don't need many form actions because every operation can be done using branching in the single form handler script.
Here is the very simple CRUD application example, performing displaying, editing, adding - all in one body and utilizing templates:
index.php
<?
mysql_connect();
mysql_select_db("new");
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part:
$name = mysql_real_escape_string($_POST['name']);
if ($id = intval($_POST['id'])) {
$query="UPDATE $table SET name='$name' WHERE id=$id";
} else {
$query="INSERT INTO $table SET name='$name'";
}
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) { //listing part:
$LIST=array();
$query="SELECT * FROM $table";
$res=mysql_query($query);
while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
include 'list.php';
} else { // form displaying part:
if ($id=intval($_GET['id'])) {
$query="SELECT * FROM $table WHERE id=$id";
$res=mysql_query($query);
$row=mysql_fetch_assoc($res);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
?>
form.php
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
list.php
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
Just send them to a central location and use logic to send them somewhere else depending on what they selected.
eg:
<?php
switch($_POST['choice']) {
case 'edit':
$page = 'edit.php';
break;
case 'group':
$page = 'group.php';
break;
}
header("Location: " . $page);
(obviously needs some input filtering and default values)
EDIT: as pointed out by Col. Shrapnel below, using header() for this is pretty pointless as it'll then wipe out your $_POST array - use include() instead, but be careful to only allow your own files and never let the user name the file which will be included (eg using a form field value to pick the included file).
No, you can't have multiple actions just in the html, but you can use javascript to switch up the action depending on what button is hit.
I would do something like this (in pseudo-mootools)
<form action='default.php'>
... form elements ...
<button onclick='editButtonClick()' value='edit'/>
<button onclick='deleteButtonClick()' value='delete'/>
</form>
function editButtonClick() {
$('form').action = 'editaction.php';
$('form').submit();
}
function deleteButtonClick) {
$('form').action = 'deleteaction.php';
$('form').submit();
}
No, it can't (at least not without depending on JavaScript).
Submit to one URI, and have a dispatch routine pass the data off to different functions depending on which radio button (or whatever) is selected.
If I was looking at doing this I would pass a vaule of what you want doing by POST.
Then check that value against a set of functions and each function will do a different thing based on it selection
<input type="submit" value="Add" onclick="submitForm(this,'add')" />
<input type="submit" value="Update" onclick="submitForm(this,'update')" />
<input type="submit" value="Delete" onclick="submitForm(this,'delete')" />
var submitForm = function(context,uri)
{
form = contenxt.parent; //Go back to the form
form.action = uri; // Set the action
form.submit(); //Submit the form;
}
Java script is the best way to handle this, there's not really much alternative unless you create 3 sole forms.
Post your form to a central formhandler script. On that page just use simple logic (using php in this instance) to redirect the user to the specific page you want
on Submit page you can call CURL and give all Get or post variables to that url.

Categories