I am trying to create a calender with a checkbox for each date. When a user clicks the submit button, I want to get those selected dates inserted into the database and those which are not selected would be deleted from the database if those already exist before. I have created a index.php page where I wrote the following code to generate dates:
index.php:
<form name="form1" method="post" action="show.php">
<?php
$year="2011";
$month="8";
$d=cal_days_in_month(CAL_GREGORIAN,1,2011);
$i=1;
while($i<=$d)
{
?>
<input type="checkbox" name="date[]" value="<? echo " $year-$month- " . $i . ""."<br>"; ?>">
<? echo " $year-$month- " . $i . ""."<br>"; ?>
<?
$i++;
}
?>
<input type="submit" name="Submit" value="Submit">
</form>
show.php:
<?
mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
$media_array = $_POST['date'];
foreach ($media_array as $one_media)
{
$source .= $one_media.", ";
}
$media = substr($source, 0, -2);
$query = "INSERT INTO table1 (id,media) VALUES('', '$media')";
$result = mysql_query($query); }
?>
And then I created page another page named show.php where I tried to write codes for inserting information, but I failed.
Would you please kindly help me to do this? I have tried my best but I couldn't make it happened. Thanks in advance.
The easiest way would be to make use of Ajax (going to use the JQuery library to make it a bit easier). So every time a checkbox changes values an Ajax request is triggered to updateDatabase.php and it either deletes or inserts a record.
So if you are showing your checkboxes on the page do:
<script>
$(document).ready(function() {
//Every time a checkbox changes (gets ticked or unticked) send n Ajax request
//to updateDatabase.php containing its value and a BOOLEAN checked/unchecked
$('input[type="checkbox"]').change(function() {
var checked = $(this).is(':checked');
$.ajax({
url: "updateDatabase.php",
type: "POST",
data: {value : $(this).val(),
checked : checked },
dataType: "html",
async:false,
success: function(msg) {
//Show the answer from the file in an alertbox.
//Use this to debug your code. Leave it out afterwards.
alert(msg);
}
});
});
});
</script>
So every time a checkbox is checked or unchecked it sends its value and the "checked" boolean value to updateDatabase.php.
In this file you can do something similar to:
updateDatabase.php
<?php
//Get POST variables
$value = mysql_real_escape_string($_POST['value']);
$checked = $_POST['checked'];
//If the checkbox was checked, INSERT its value into the database
//else you remove it.
if ($checked == true) {
$query = "INSERT INTO table (value) VALUES ('" . $value . "')";
}
else {
$query = "DELETE FROM table WHERE value = '" . $value . "'";
}
mysql_query($query);
?>
EDIT: Added the code to process the data after you click SUBMIT
If you do not want to do this on the flow
If you want to update your database when the user clicks SUBMIT, you simply submit the form to show.php.
show.php
<?php
$dates = $_POST["date"];
echo "Dates chosen: " . count($dates) . "<br /><br />";
if (count($dates)>0) {
echo "You picked the following dates:<br />";
}
for ($i=0; $i<count($dates); $i++) {
echo ($i+1) . ") " . $dates[$i] . "<br />";
mysql_query("INSERT INTO table (value) VALUES ('" . mysql_real_escape_string($dates[$i]) . "')");
}
?>
Hope this helps you!
(I did not test this code so I'm sorry if there are some minor errors in there still. But I'm sure you catch the drift!)
Related
I'm doing an input with autocomplete where my user can select multiple users from database and I want to submit those select users in my form where action goes to a php file that does a INSERT in the database.
So this is the input, I want the selected users to show up in p#selecionados but user selects one at a time:
<form id="formCriaJogo" method="post" action="./components/insert.php">
<label>Other users</label>
<input type="text" name="autor" id="autor" placeholder="Write users name" />
<div id="autorLista"></div>
<p id="selecionados"></p>
<button type="submit">Insert</button>
</form>
And this is jquery code to do the autocomplete:
$(document).ready(function() {
$('#autor').keyup(function() {
var query = $(this).val();;
if (query != '') {
$.ajax({
url: "./components/search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$("input#autor").css("margin-bottom", '0');
$("#autorLista").css("display", 'block');
$('#autorLista').fadeIn();
$('#autorLista').html(data);
},
error: function(error) {
console.log(error);
}
});
}
});
$('input#autor').on('change', function() {
alert($('input[name=autor]:checked', '#formCriaJogo').val());
});
});
Also, here is search.php that does the search:
<?php
include_once "../connection/connection.php";
if (isset($_POST['query'])) {
$link = new_db_connection();
$stmt = mysqli_stmt_init($link);
$output = '';
$input = $_POST['query'];
$query = "SELECT id_user, nome_user FROM users WHERE nome_user LIKE CONCAT(?, '%')";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, 's', $input);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_user, $name_user);
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) > 0) {
while (mysqli_stmt_fetch($stmt)) {
$output .= "<input type='radio' value='" . $id_user . "' name='autor'>" . $name_user . "<br>";
}
} else {
$output .= '<p>The user your looking for doesn't exist.</p>';
}
echo $output;
}
Now the clicked input type=radio value which contains users' id and name I want the user name in p#selecionados just to show them what he selected and also send id and name of user selected when submitting my form.
You can create an array in jquery so , whenever you select an option from autocomplete box.. put that value inside that array in jquery .I have use checkbox instead of radio-button in below code and whenever user select any option that data will get inserted in array i.e:index and when insert button is clicked the selected data will get display in p#selecionados tag and also an ajax will call to send your selected data to php page.Also i have added value='" . $id_user."," . $name_user . "' you can split this using .split() with delimiter , to get both userid and username.Sample code :
var index = [];
//when check-box is changed
$('input[name=autor]').change(function() {
//checking if checkbox is check put it in array
if ($(this).is(':checked')) {
index.push($(this).val());
console.log(index)
} else {
//if uncheck remove the element from array
if ((index1 = index.indexOf($(this).val()) !== -1)) {
index.splice($.inArray(index1, index), 1);
console.log("remove");
}
}
});
//when insert button is click
$("button").click(function() {
//clear the p tag content
$("p#selecionados").html("");
for (var i = 0; i < index.length; i++) {
//append all selected check box
$("p#selecionados").append(index[i] + "<br />");
console.log("userid & username" + index[i]);
}
if (index != '') {
$.ajax({
url: "yourphp_page_name",
method: "POST",
data: {
//sending array to php
data: index
},
success: function(data) {
//do something
},
error: function(error) {
//do something
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<button type="submit">Insert</button> <br/><br/> Selected data :
<p id="selecionados"></p>
Then in your php side ,you need to get that array i.e : data using $_POST['data'] and then explode your array and use it as per your requirement.
I am creating a application that lets you design a meal and add or remove ingredients. However, the issue I am struggling with is $_POST data. The issue I am running into is I need a button for every $_POST data form submitted.
For example, I can use view meal button to list the ingredients (as seen in the picture), however since this action refreshes the page, the $_POST[meal] data is no longer there. So when I try to remove a ingredient, it can give me the selected ingredient but not the meals name.
What is the right way to get $_POST data? I am having to basically make a new form and button for every submission. Do I need to use some sort of AJAX so it doesn't necessarily refresh the page and I lose that data? Or do I need to use the $_GET method?
<?php
if (isset($_POST['view_meal'])){
$meal = (string)$_POST['meal_names'];
$meal_fk_q = "SELECT item
FROM meal_ingredients
WHERE meal_name='$meal'
ORDER BY item";
$meal_fk_c = $conn->query($meal_fk_q);
$option_string = "";
echo "<div class='view_meal_table_wrapper'>";
while ($row = $meal_fk_c->fetch_assoc()){
$view_ingredient = $row['item'];
echo "<table class='view_meal_table'>
<tr>
<td class='view_meal cell'>$view_ingredient</td>
</tr>
</table>";
$option_string .= "<option>" . $view_ingredient . "</option>";
}
echo "</div>";
echo "<form action='createmeal.php' method='post'>
<select name='remove_ingredients'>
<option disabled selected value> -- Remove Ingredient -- </option>";
echo $option_string;
echo "</select>
<input type='submit' name='remove_ingredient' value='Remove Ingredient'>";
}
if (isset($_POST['remove_ingredient'])){
$ingr = $_POST['remove_ingredients'];
$sql = "DELETE FROM meal_ingredients
WHERE item='$ingr'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
?>
Ajax is the way forwards for you on this one. There are loads more you can add to it to improve, but the basics - using jQuery:
var variable-to-send = 42;
$.ajax ({
type: 'POST',
url: 'php_file_location.php',
data: {name-in-post: variable-to-send, more: more, andmore: andmore}
success: function (response) {
// handle the returned details here
console.log(response);
}
});
Then in php you'd do $data = $_POST ['name-in-post'];
Typed on mobile so apologies if any errors
I am creating a basic auction site and got quite far with help from this community. I am near finishing this now but having a slight issue with server side validation.
Auctions are listed on a PHP page with html and PHP, PHP runs a MySQL query and then lists the results. Example here:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction" . $row['ID'] . "'>
<input type='hidden' name='id' value='" . $row['ID'] . "' />
<div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
echo "<div class='bid-success' id='bid" . $row['ID'] . "'>Bid placed!</div>";
echo "</div></form>";
}
echo "</table>";
mysqli_close($con);
Once the user clicks the submit button, the following jQuery is executed:
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).find('input[name="bid"]').val();
var currentbid = $('#'+id).text();
var itemdesc = $(this).find('.auction-name').text();
bid = parseFloat(parseFloat(bid).toFixed(2));
currentbid = parseFloat(parseFloat(currentbid).toFixed(2));
if (bidname == '')
{
alert("No name!")
return false;
}
/* if (bid > currentbid)
{
alert("Bid is greater than current bid");
}
else
{
alert("Bid is too low!");
return false;
}*/
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
success: function(data){
$('#bid'+id).fadeIn('slow', function () {
$(this).delay(1500).fadeOut('slow');
});
//$('#auction' + id).find('.nospace').html(currentbid);
},
error: function() {
alert("bid too low");
}
});
return false;
});
});
If the code POSTS, the following PHP code is run on the handler page:
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$itemdesc = $_POST['itemdesc'];
$highestbid = mysqli_fetch_row(mysqli_query($con,"SELECT CurrentBid from Auction WHERE ID = '$id'"));
if ($bid <= $highestbid)
{
$_SESSION['errors']['bid'] = 'Sorry, but the bid is too low';
echo json_encode($_SESSION['errors']);
exit;
}
else
{
$query = "UPDATE auction SET CurrentBid = '$bid', Bidder = '$bidname' WHERE ID = '$id'";
$query2 = "INSERT INTO auction_log (Item, Bid, Bidder) VALUES ('$itemdesc','$bid','$bidname')";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_query($con, $query2) or die(mysqli_error());
mysqli_close($con);
I added some server side validation to make sure that the bid posted is higher than what is currently in the MySQL table.
The problem I am having is that I get the "Sorry, but the bid is too low" error no matter what bid I put in.
If I put a bid higher than the current bid, I get the error, if I put a bid in lower, I get the error.
Both ways I go about it also trigger the success section of the AJAX.
I feel like I'm missing something very simple, so if anyone could help that would be great.
I am not sure why it's being downvoted, I am just looking for some help.
Thanks
The way that you're handling AJAX error is not very good because it only alerts you that you have an error, but you don't know what goes wrong.
In the AJAX object, replace the current error callback with one that logs the actual error to the console:
replace
error: function() {
alert("bid too low");
}
with
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
and you'll know for sure what is the error
I am displaying some data from my database, and I wnat to be able to put checkboxes next to each record displayed.
Afther that I want the user to be able to submit their selection and that will then delete the selected records.
I googled a lot of things, but could not make anything work. I'm looking for smething simple.
Here is my code:
<?php
//include('conn.php');
$con=mysqli_connect();
session_start();
if (!isset($_SESSION['ID'])){
header('location:login.php');
}
//
?>
<?php
if (!$link = mysql_connect()) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db()) {
echo 'Could not select database';
exit;
}
$villageId = $_GET['village'];
$ID = $_SESSION['ID'];
$sql ="SELECT *
FROM favourites
INNER JOIN attractions ON favourites.AttractionID = attractions.AttractionID
INNER JOIN customer ON favourites.ID = customer.ID
WHERE favourites.ID = '$ID' ";
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['Name'] ;
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Can anyone give me some suggestions?
Thanks.
Simple add checkbox near data output:
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' /> ".$row['Name'];
}
As I understand you need this:
Output some rows data - checkbox
User will select some checkboxes and data, connected with that checkboxes will be deleted from the database.
Delete deleted data from the page.
How to achieve this?
You need html code below to ahieve what you want (+ you need some javascript, I will tell about it later):
<form id='myForm'>
<div id='1'>
<input type='checkbox' name='data[]' value='1' />Row 1</div>
<div id='2'>
<input type='checkbox' name='data[]' value='2' />Row 1</div>
<div id='3'>
<input type='checkbox' name='data[]' value='3' />Row 1</div>
</form>
Look the example of that code + serialize form on link onclick handler here.
Generate same output in PHP:
// execute query
echo "<form id='myForm'>";
while ($row = mysql_fetch_assoc($result)) {
echo "<div id='".$row['id']."'><input type='checkbox' value='".$row['id']."' /> ".$row['Name']." </div>";
}
echo "<a href='#' id='delete'>Delete</a>";
echo "</form>";
So, now we made 1st item of our list and half of 2nd (serialize form).
How to achieve another half of 2nd item. We have to create php script where we will delete rows from the database.
deleteScript.php script:
// connect to the base
foreach($id in $_POST['data']) {
$query = "delete from `favourites` where `id` = ".$id;
// execute your query
}
Script ready. Now you have to send request from our page to this script. Use ajax request for it:
$("#delete").on('click', function () {
var data = $("#myForm").serialize();
if(data != '') {
$.ajax({
url: "deleteScript.php",
data: data
});
}
else
{
alert("select some checkboxes");
}
});
This javascript code works with previous html code
Example here.
Now, 1st and 2nd items of our list done.
Let's delete deleted items from our page immidiately (3rd item of todo list):
$("input:checkbox:checked").each(function()
{
var id = $(this).val();
$("div#"+id).remove();
});
You can test this code here
That example was created to show you, that my approach works. But! You have to remove div's only if request had been sent successfully. So you have to edit $.ajax success handler. Check this fiddle for it.
So, now we made all items from our list.
Final example here: http://jsfiddle.net/575VS/18/
You have to copy past it just to your files :)
Hope, this will help.
Note, that you can get ajax-request response.
$.ajax({
//some properties
success: function(data) {
//response will be in data variable
}
});
If you want to redirect page right after deleting selected rows in database use this code:
if(data != '') {
$.ajax({
url: "deleteScript.php",
data: data,
success: function() {
window.location.replace("new link here");
}
});
}
Just to expand on Sharikov's answer: You need to place the checkbox in the loop as he described, but if you want to be able to pass that info to another script, that works on the user input you need several more things:
echo "<form action='receiver.php' method='post'>";
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' name='checkedBoxes[]'/> ".$row['Name'];
}
echo "<input type='submit' value='process'>";
echo "</form>";
Then on receiver.php:
foreach($_POST['checkedBoxes'] as $box){
$id = $box;
//THEN DO SOMETHING TO EACH ID
}
If you also want to see which boxes were unchecked, then things get a little more complicated because POST and GET will only pass the values of checked check-boxes. and there are several ways I can think of to do this. One way would be to pass an array of the all ids displayed via a $_SESSION variable to the next script:
session_start();
$ids = new Array();
echo "<form action='receiver.php' method='post'>";
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' name='checkedBoxes[]'/> ".$row['Name'];
array_push($ids, $row['id'];
}
$_SESSION['ids'] = $ids;
echo "<input type='submit' value='process'>";
echo "</form>";
And then on receiver.php you can reference that array with $_SESSION['ids'] and compare it to the values that were checked. Just make sure you place session_start(); in your code to be able to see the variable!
Good Luck!
I am trying to use a dynamically generated dropdown list to populate a table. I have a drop down list that is generated from my database (it grabs all the years available for a specific player). I want to be able to select a year from the dropdown and have it update my table. I have the dropdown being generated, but I am not able to get the selected value from the dropdown. I have code below that I found here, but it doesn't seem to work. Here is the code I have so far:
<input name="update" type="submit" value="Update" />
</form>
<p></p>
<form action="player_login.html">
<input type="submit" value="Logout" />
</form>
</div>
<div style="float: left">
<p></p>
<h1>Player Stats</h1>
<table width="300" border="1" cellpadding="2" cellspacing="2">
<?php
// get "id" field from player table
$login_id = $_COOKIE["DB"];
$id = "select id from player where login_id='$login_id';";
$result1=mysql_query($id) or die('Select1 Query failed: ' . mysql_error());
$row = mysql_fetch_array($result1);
// create a dropdown from stats table in db
echo "--Select Year--";
$years_query = "select year from stats where player_id='$row[id]';";
$years = mysql_query($years_query, $connect);
// fill array with db info
$var = array();
while ($row2 = mysql_fetch_array($years))
{
$var[] = $row2['year'];
}
// create dropdown
echo'<select name="years" id="years">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select>';
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query) or die('Select2 Query failed: ' . mysql_error());
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
// create table with results
echo "<tr>";
echo "<td>Year</td>";
$j=1;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>Total Points</td>";
$j=2;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>PPG</td>";
$j=3;
echo "<td><input name='$j' type='text' value='$line[$j]' size=20/></td>";
echo "</tr>";
?>
</table>
</div>
I see that you use $_POST and since form is not submitted and thus data of $_POST is not set. Best available option I have used to catch the event and send the AJAX Query fetch results and update it.
I have done this with the help of J Query as under
$('#years').change(function() {
$.ajax({
//request of AJAX
type : 'POST',
url : 'players_data.php',
dataType : 'json',
data: {
//Data with $_POST request
years : $('#years').val();
},
success: function(data){
//Things to be done with returned data
}
}};
Create a new file players_data.php and there you write the code for fetching data from the db as:
// get selected option from dropdown
$selected_key = $_POST['years'];
$selected_val = $var[$_POST['years']];
echo "<p></p>selected key: " . $selected_val; // this wont print anything???
$search_query="select * from stats where player_id='$row[id]' and year=2013;";
$result=mysql_query($search_query);
$num_cols = mysql_num_fields($result);
$line = mysql_fetch_row($result);
$return['year']=$line;
echo json_encode($return);
I see that you are using $_POST, and why do you don't use a form?
//This is for get the form
echo '<script type="text/javascript">
//<![CDATA[
function get_form( element )
{
while( element )
{
element = element.parentNode
if( element.tagName.toLowerCase() == "form" )
{
return element
}
}
return 0; //error: no form found in ancestors
}
//]]>
</script>';
//create a form
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="post">';
// create dropdown; onchange will send the form when selected index changes...
echo '<select name="years" id="years" onchange="get_form(this).submit(); return false;">';
// For each value of the array assign variable name "city"
foreach($var as $year)
{
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select></form>';
And that's all! :D
I'm seeing too that you are using an unique form for update all the page... It's isn't work, because you only have a submit button and no more element in the form, please read that: http://www.w3schools.com/tags/tag_form.asp
From your code i can see that u want to get the value from the select box and immediately populate the table and display the results..use jquery to get the value of selected object and assign the javascript variable to a php variable. and insert into the db..
<script type="text/javascript">
$( "#years" ).change(function() {
var value=document.getElementById("years").value;
alert(value);
</script>
assign the variable to php and execute you php query.
<?php
$data = "<script>document.write(value)</script>";
//execute your query here..
?>
Also have a look at ajax..it does that so well...