Simple Chechlist PHP Application Help needed - php

I am building a simple PHP checklist application which takes sentences as input which are stored in MYSQL database then the list is echoed out with remove buttons in front of each list item such as:
1) Do breakfast [remove button]
2) Go to College [remove button]
3) Eat Lunch [remove button]
4) Get back Home [remove button]
Now what would be function that will be executed to remove the current list item being removed.
Here is how I am retrieving the list from database and their corresponding remove buttons:
$sql2 = "SELECT * FROM `info` LIMIT 0, 30 ";
$arr = mysql_query($sql2);
while($data = mysql_fetch_array($arr)){
echo '<strong>'.$data['id'].')</strong>'.' '.$data['text'].'<form action="list.php" method="POST">
<input type="submit" value="Remove" />
</form>'.'<br />';
Please help me how can we approach to a situation like this.
P.S The database has two columns only "ID" and the "List item"

You can use < input type='hidden' name='data' value="<?php echo $data[text]; ?>" > in the form
Finally, you can put this block to remove.
if(isset($_POST['submit']) {
$query = "delete from info where text = '$_POST[data]'";
//run the query here
}

What is it that you want particularly?
Do you mean you want the application to get check box elements and store them in the database.
Then get that data and apply to each a delete command?
be specific my friend and we can help.

Related

Form keeps selecting multiple radio buttons

I have a feeling there is a simple solution to this problem but I can't seem to figure it out.
I'm using a mix of jQuery, PHP and HTML to generate this dynamic form of mine.
Each result SQL finds will be passed into the form, it will display a person along with a radio button. So if there are 3 returned results in the DB, the form will generate 3 people and one of them will have the radio button already checked. My problem is, I only want to be able to select 1 of the 3 radio buttons generated. It keeps multi selecting and I don't know what's causing it or how to stop/fix it.
Example:
Note - showing snipet to illustrate my point
<?php
$group_query = mysqli_query($conn,"SELECT * FROM Groups WHERE gp_ID = '26'")
or die("Error: ".mysqli_error($conn));
?>
<form action="#" class="form-horizontal" method="post">
<?php
$counter = 1;
$passenger_query = mysqli_query($conn,"SELECT * FROM Customers AS C
WHERE C.gp_ID = '".$group_Results['gp_ID']."'")
or die("Error: ".mysqli_error($conn));
while($passenger_Results = mysqli_fetch_array($passenger_query)){
?>
<input type="radio"
class="the_Leader"
name="the_Leader_<?php echo $counter; ?>"
value="<?php echo $passenger_Results['customer_ID'] ?>"
<?php echo $passenger_Results['customer_ID'] == $group_Results['leader_ID'] ? 'checked' : ''; ?>
/>
<?php
echo $passenger_Results['name'];
$counter++;
}//end while loop
?>
</form>
tl;dr dynamic form generated using PHP/MySQL, one of the results is already checked. Want to be able to change it but form multi selects radio buttons.
You are assigning different name= attributes to the buttons when you write name="the_Leader_<?php echo $counter; ?>". To be in a button group, all buttons must have the same name.
You want the names to be the same and the values to be different; the latter lets you know which button was clicked when the form is submitted.

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?

PHP data retrieval from database and display

How do I Limit some information displayed from the database and add a link eg "More" to enable read all information in a drop down using PHP. such as what is on facebook (Read more...). I am dealing with a lot of content and I dont want it all displayed at once.
Here is part of the code
echo "<p>".$row['Firstname']." ".$row['Lastname']."</p>";
echo "<p>".$row["Course"]." | ".$row["RegID"]."</p>";
echo "<p>".$row["Email"]."</p>";
echo "<p>"."Tel:".$row["Telephone"]."</p>";
echo "<p>".$row["info"]."</p>";
The code is running well only that I want to limit the information
echo "<p>".$row["info"]."</p>";
so that not all is displayed
Thanks
Use Jquery-ui click on "view source" and you'll see it's very simple really, just set the row that you want as the header (what's clicked to show the rest) and store the rest in a div below.
Split info into two strings, one intro, and the rest. Display only the intro to begin with. Insert a link that displays the rest when clicked.
$intro = substr($row['info'], 0, 200);
$rest = substr($row['info'], 200);
echo sprintf(
<<<HTML
<p>
<span class="intro">%s</span><span class="rest" class="display: none">%s</span>
Show more
</p>
HTML
, htmlentities($intro)
, htmlentities($rest)
);
displayRest is a Javascript-function that, given a link, finds the previous span with class rest, shows it and removes the link. I leave it as an exercise to implement this in a way that fits your project. You can go with native Javascript, or use a library such as jQuery, YUI, MooTools, Prototype etc.
if(isset($_POST['more']))
{
$query="select col1,col2,col3, ... ,colN from tableName ";
}
else
{
$query="select col1,col2,col3 from tableName ";
}
//HTML
<form method="post">
<input type="submit" name="more" value="More" />
</form>
//PHP
$records=mysql_query($query);
while($row=mysql_fetch_assoc($records))
{
//Display
}
The limit must be fixed on the SQL request.
// If you want to transmit limitation with a GET PARAMETER.
// You can also $_POST ur data.
$limitation = $_GET['limit'];
//..... And in your SQL REQUEST
$sql = "SELECT * FROM your_table LIMIT 0 , $limitation";
//And in the link....
echo 'Show only 10 Results'
?>
You can optimize that and add security precaution to prevent errors when $limitation receive empty or non numeric parameters.
<?php if(isset($_GET['limit']) && !empty($_GET['limit']) && !preg_match(EXPRESSION, $_GET['limit'])){
//YOU CAN DO THE LIMITATION WHITOUT SQL ERRORS
}
else{
//ERROR DIRECTIVE
}
?>

How to get the second value in a dropdown box based on the selected one in the first dropdown box

I have written the following code in PHP to generate two dropdown boxes on the same page.
The first dropdown box gets value from a MySQL table. This dropdpwn box contains some UserIDs. The second dropdown box contains some dates which should be based on the UserID that is selected in the first dropdown box. I have filled the 2nd dropdown box with all the dates in the MySQL table, but, it should be filtered by the UserID which is selected on the first dropdown box.
Just to inform, with these two values from these two dropdown boxes in this PHP page, I have posted them by pressing the submit button to another PHP page to process some other work.
I would appreciate if you can help me to fill the second dropbox only based on the UserID selected on the first dropbox. Here is the code I have written to display and fill those dropdown boxes. Can you please inform me, what part of the code I should modify and I would appreciate if you can show me the modification code as well. I am a newbie in PHP, that's why I am asking for code level help.
My code:
<html>
<head>
<title>
Search Alert DB
</title>
<body>
<br />
<?php>
$con = mysql_connect("localhost","root","root"); // (host, user,pwd)
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql", $con);
echo "<p> Search Alert database </p>";
echo "<br />";
$result = mysql_query("SELECT distinct(UserID) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$options="";
echo "<form action='Search_AlertDB_process.php' method='POST'>\n";
//echo "Please choose a user: ";
echo "Please choose a user: <select name = userid>";
echo "<option>-Select-";
while ($row = mysql_fetch_array($result))
{
$userid=$row["UserID"];
$options ="<option value = \"$userid\">$userid </option>";
echo "$options";
}
echo "</select>";
echo "<br />";
echo "<br />";
$dayresult = mysql_query("SELECT distinct(Occurred_date) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$dayoptions="";
echo "Please pick a date:<select name = day>";
echo "<option>-Select-";
while ($row=mysql_fetch_array($dayresult)) {
$day=$row["Occurred_date"];
$dayoptions ="<option value = \"$day\">$day </option>";
echo "$dayoptions";
//$options.="<OPTION VALUE=\"$id\">".$day;
}
echo "</select>";
echo "<br />";
mysql_close($con);
?>
<br />
<input type="submit" name="Submit" value="Search" /> <br /> <br />
</form>
</body>
</html>
You'll need 3 things
Initial page with select fields
The first select field is pre-populated with user ids
The second field contains no options and is disabled
A separate endpoint/page that takes a user id as a parameter to return relevant dates
It should probably return JSON/XML (or something similar), or you could return the dates pre-rendered in <option /> tags (shouldn't really do this, but it would be quicker to hack this together)
Javascript callback triggered when an option in the first dropdown is selected. The callback should send an AJAX request to the separate endpoint and populate the second dropdown with the result.
It would have probably been easier for me to write it all out for you than [try] to explain it, but that's not really the point. Just trying to set this all up (all be it; relatively simple) will teach you a whole load of things about Javascript, AJAX and web services.
If you choose to return JSON/XML from your web service (the separate endpoint/page), and hopefully you will, you might also start to see the benefit of separating logic from presentation, which will make the world of difference to both your understanding and delivery of code.
Well, we wont write the code for you. Otherwise you are going to be newbie for all your life :)
What you need here is called AJAX. The easiest way to implement it is probably jQuery ajax function. If you don't know jQuery - learn the basics, it shouldn't take more than an hour or so. It's worth it :)

Javascript mysql interface?

I am going back though a web-based document numbering system from few weeks ago. To sum it up, the user types in the project,class,base, and dash number (PPP-CCC-BBBB-DDD) then it is added to a mysql database. Now most doc numbers go in order according to revisions. IE: A document 1465-630-0001-000 becomes, after revision, 1465-630-0002-000.
The boss wants the system to automatically fill the input text box for the base number if it detects that the user is entering a revised doc. So if a user types in 1465 into the project field and 630 into the class field the system should autofill the base field with the next available number. In the previous example this would be 0002.
It needs to be able to search the database for the first two fields so that it can find the next available one. Is there anyway to do this using javascript or something? SO was really helpful with my last javascript question pertaining to this system.
heres an bit of my code if it helps:
` ?>
<div id='preview'></div>
<form id='item' action="submit.php?item=1" method="post">
Enter Title:<input type="text" name="title" size="20"><BR>
Choose Project Code:
<SELECT NAME="project">
<OPTION VALUE="">Project...
<?
$query = "SELECT * FROM project ORDER BY project asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['project']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Choose Class Code:
<SELECT NAME="class">
<OPTION VALUE="">Class...
<?
$query = "SELECT * FROM class ORDER BY class asc";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result))
{
$num = ($row['class']);
$name = ($row['description']);
?>
<OPTION VALUE="<?=$num?>" ><? echo"{$num}" . " | " . "{$name}";?>
<?
}
?>
</SELECT><BR>
Assigned Base Number:<input type="text" name="base" size="20"><BR>
Enter Dash Number:<input type="text" name="dash" size="20"><BR>
Enter Comments:<input type="text" name="comment" size="40"><BR>
<input type="hidden" name="item" value="1"/> `
Just a simple html/php input form with the project and class code list generated from a database pertaining to each.
Thanks for any help-Thomas
Update:
So, you're going to need to make an AJAX call (see example in my comment below) to some PHP script that will retrieve the base value you want and then returns that to the AJAX request. Once the request gets a response, you can use that data to fill in the value the way I originally said...
On a side note, since the example I gave you is a jQuery AJAX function, you should probably check out how to use jQuery to select elements on the page, instead of using straight JS.
E.g. for getting by ID and replacing value:
$("#base").attr('value', valueFromAjaxCall);
How to change value with JS:
If you use PHP to get the base value you want to fill into the field, then you can fill the value in with:
var baseField = document.getElementsByName("base")[0];
baseField.value = <?=$baseValue?>;
The getElementsByName() call returns an array, which is why you have to index into the field you want. I would suggest giving your <input> an id so that you can use document.getElementById() instead. You would do something like:
<input type="text" id="base" size="20">
and the JS to get the input element would be:
var baseField = document.getElementById("base");
...therefore, no need to index, in case you named any fields with the same name.
**Not sure about the PHP syntax.
An ajax call on focus of the 3rd field firing back to the server the values of the first two fields?
first, you'll probably want to use jQuery since it has great support is easy to use and will feel familiar to someone used to PHP.
so include your jQuery javascript code that you can get from :
http://jquery.com/
then, assume a form that looks like:
{form}
<input type=text id='major' name='major' value=''>
{Or a select, your choice}
<input type=text id='minor' name='minor'>
{or a select again}
<input type=text id='sequence' name='sequence' onFocus='getNextSequence()'>
...
{/form}
in your head, have your javascript:
function getNextSequence(){
var major=$('#major').val();
var minor=$('#minor').val();
if(!major){
alert('Select a major version#');
$('#major').focus();
return(false);
}
if(!minor){
alert('Select a minor version#');
$('#minor').focus();
return(false);
}
$.getJSON('http://url.to.getnextNumber.php',
{major:major,minor:minor},
function(data){
if(!data.error){
$('sequence').val(data.nextSequence);
}else{
alert(data.error);
}
}
});
}
the jQuery getJSON call will make a call back to your URL with two $_POST variables, major and minor. do your query, save the result as $result=array('nextSequence'=>$x,'error'=>'false');
and convert it to JSON with echo json_encode($result);
don't include ANY headers or any other content in the output of that file, and jQuery will pull the correct value and insert it where it's supposed to bed

Categories