I have a control panel in php and mysql that displays on page load. I have a checkbox on that page(default off, not stored in db or tied to anything other than being an option to show old items), that when i click it, i want the query to refresh the data with the new filter applied. Basically on load it show only active items, when they check the checkbox i want the page to reload showing outdated items.
My code is:
<form action="" method="POST">
<input type="checkbox" name="filter" value="true">
</form>
<?PHP
$showold = (isset($_REQUEST['filter']));
if ($showold === 'checked' )
{
$showold = "WHERE `MyTable` = '0'";
}
else
{
$showold = "WHERE `MyTable` = '1'";
}
$query_NowPouring = "SELECT * FROM MyTable $showold";
$result = mysqli_query($mysqli, $query_NowPouring);
if($result){
while($row = mysqli_fetch_array($result)){
#set variables here and display the info in table here.
}
}
?>
Your code (isset($_REQUEST['filter'])); is returning boolean like 0 or 1 not string and you are matching it with string at if ($showold === 'checked' ) .
Problem is you can not compare boolean with string.
Related
I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)
I'd like to ask two things for this particular user ability. The first is how to delete a row upon user clicking a button. The second is....would this be a good idea? How can I create a safe environment for someone to do this. This is what I've got so far :
<?php
include_once "db_conx.php";
if($_POST['wall'] == "post") {
//open if($_POST['wall'] == "post")
$id = mysqli_real_escape_string($db_conx, trim($_POST['id1']));
if($id == " ")
{
exit();
}
else
$sql = "SELECT FROM courseprogress WHERE userid='$id' LIMIT 1";
$results = mysqli_query($db_conx, $sql);
$sidebar = mysqli_num_rows($results);
if($sidebar > 0) {
//close if($sidebar > 0)
while($row = mysqli_fetch_assoc($results))
{
$sql = mysqli_query("DELETE FROM courseprogress WHERE userid='$id'");
$results = mysqli_query($db_conx, $sql);
}
//close if($sidebar > 0)
}
else
{
echo 'Already Complete!';
echo "<pre>";
var_dump($sql);
echo "</pre><br>";
}
//close if($_POST['wall'] == "post")
}
?>
Right now I'm in the process of dumping out variables, but can't seem to get my id variable right.
The idea is to "start over" in a sense. The table holds the user progression and settings. Once they've decided they need to start over they will be allowed to do so by simply deleting the row. When the begin again the row will be created again.
A little more information:
The small form script I was trying to use is:
<div class="userInfoContain"><div class="positionRight"><div id="form"> <form><div class="submit"><input type="hidden" id="id" value="'.$id.'" /><input type="submit" name="button" id="button" value="Start Over" onclick="return false" onmousedown="javascript:wall();"/><img src="images/loading.gif" alt="" width="15" height="15" id="loadingstart" /></div></form></div></div></div>
<script type="text/javascript">
$(document).ready(function(){
$('#loadingstart').hide();
});
function wall(){
$('#loadingstart').show();
var id = $('#id').val();
var URL = "./includes/start-over-user.php"; /////post.php will be equal the variable "comment"
$.post(URL,{wall:"post",id1:id},function(data){//parameter wall will be equal "post", name1 will be equal to the var "name" and comment1 will be equal to the var "comment"
$("#result").prepend(data).show();// the result will be placed above the the #result div
$('#loadingstart').hide();
});
}
</script>
1) Safely allow user to delete: The safest way is to not allow delete permissions on the MySQL user that is being used by the website. A method called soft delete is much safer for deleting rows in MySQL tables. This involves adding a column named "is_deleted" to the table where you are making this update. When is_deleted is set to 0, allow the row to act normally. When a user sets is_deleted to 1, it should act as if it doesn't exist. In this example, I am assuming you have set $is_deleted to the column is_deleted in your table:
if($is_deleted == '1')
{
// Don't display
}
else
{
// Display
}
2) How to implement: The best way to do this is with:
UPDATE tablename SET is_deleted = '1' WHERE id = '".$id."'
which should be executed through AJAX command or a link that will execute the MySQL query.
to delete I advice you to use ajax , it's perfect and you can have more control on this action
the other Problem i need more explanation i didn't understand you good
I have a binary field in a mysql database that gets updated by a button on an html form.
So, I click the button for every row and it changes the mysql value for each of the rows…
The problem is that it has a delay, when I click on one button of a certain row it only gets updated when I click on the next. But if I click on that button and refresh the page it gets changed.
I've look into ways of updating the page, but I just can't get it to work...
<form action='index.php' method='POST'>
<input type=hidden name='keyword2' value='$keyword'>
<input type='submit' value = 'SELECT' >
</form>";
<?php
j($_POST['keyword2']);
function j($q){
$n = "SELECT `CÔR` FROM `keywords` WHERE `keyword`='$q'";
$b = mysql_query ($n);
$row = mysql_fetch_array($b);
echo $row['CÔR'];
$t = $row['CÔR'];
if ($t == 1) {
$m = "UPDATE `keywords` SET `CÔR`=0 WHERE `keyword`='$q'";
mysql_query ($m);
}
if ($t == 0) {
$l = "UPDATE `keywords` SET `CÔR`=1 WHERE `keyword`='$q'";
mysql_query ($l);
}
I am totally stuck here and found tens of samples on posting to get and set values. What I am trying to do is -
Let a user enter a vehicles year model into a textbox in my form (set to post)
I then need to get this value to a variable state
$vehicle_year = $_GET['vyear'];
First error is here... vyear is the name and id for my textbox. Error - Undefined index 'vyear'. There is no submission of the form etc, because I am still on the same form/page.
With this value captured, I then search my database to return all of the manufacturers that has a year (as returned) attached to it -
$query = "SELECT * FROM `vehicledata` WHERE `year`='$vehicle_year'";
Obviously it does not work because I still do not have the value as yet returned from above with the undefined error. I've tried to change the name and id of the textbox, no luck.
Once these records has been returned, I need to add the values to a select (drop down) box. I have no idea how to get the values in there - seems I need to run a loop, which I know how to, just don't know how to add the options to the select box.
Please note that my form is NOT submitted, I need to load all the relevant data first before it gets submitted.
Any help will be appreciated, thanx guys.
P.S. I will add against sql injection once I know how to get the values and add the options. Just need the basics to get me going.
HTML:
//This would be my code...
Search Just my Wheels
Year
<?php
$vehicle_year = isset($_POST['vehicleyear']) ? $_POST['vehicleyear'] : -1;
if ($vehicle_year == -1) {
echo 'No Value Returned...';
//returns no value...
} else {
//How to get the value and echo it out...
echo $vehicle_year;
}
//$query = "SELECT * FROM (SELECT * FROM `vehicledata` WHERE `year`='$vehicle_year' ORDER BY `cid` DESC LIMIT 1, 10) AS `table` ORDER BY `cid` ASC";
$query = "SELECT * FROM `vehicledata` WHERE `year`='$vehicle_year'";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$vehicle_id = $line['cid'];
$vehicle_year = $line['year'];
$manufacturer = $line['carfindmake'];
//Get manufacturer data...
$images = get_make($vehicle_year);
if (!empty($make)) {
echo 'No data';
} else {
echo 'Found stuff';
}
}
?>
<td align="right"><span style="visibility:hidden" id="makelabel"><strong>Make</strong> </span></td>
<!--<td><input name="make" id="make" type="text" class="searchbox" style="visibility:hidden" onClick="toggleVisibility('modellabel'); toggleVisibility('model');"/></td>-->
<td><select name="make" id="make" class="searchbox" style="visibility:hidden" onClick="toggleVisibility('modellabel'); toggleVisibility('model');"/></td>
2) This is causing an error when your form has not yet been submitted because the value is not set.
Fix this by the following:
$vehicle_year = '';
if ( isset( $_POST['vyear'] ) ) {
$vehicle_year = $_POST['vyear'];
}
1 - If the form is set to POST, you've got to use $_POST["vyear"] to recover the value.
2 - Double check the case of the textbox's name.
my form (set to post)
$vehicle_year = $_GET['vyear'];
If your form is set to use POST, you'll need to access the form elements through the $_POST superglobal as such:
$vehicle_year = $_POST['vyear'];
If you're having issues because an index may or may not be set, use PHP's isset() to check. If the index isn't set, it won't cause an error.
if(isset($_POST['vyear'])) {
$vehicle_year = $_POST['vyear'];
}
I have the following query that I ran on my database to remove some data:
delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;
But I now need to make the a php function that runs when I press a button called clean
then print out all the subscriber data that was deleted.
Not quitesure where to start with this.
this is my html so far:
<form id="form1" name="form1" method="post" action="">
Clean subscribers:
<input type="submit" name="clean" id="clean" value="Clean" />
</form>
Any help or advice with this is very much appreciated.
C
You'll need the button to submit a form to a handler page, the handler page would then run the query, and collect+print the data.
If you don't want to refresh the page (or have your users diverted into another page), you'll want to use Ajax.
That's where you start.
Is abvious you made no effort! but I will answer you anyway.
<?php
$con = mysql_connect("serverUrl","login","password");
mysql_select_db("dbName", $con);
$result = mysql_query("SELECT * FROM subscriber, subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
while($row = mysql_fetch_array($result))
{
echo $row['subscriber.name']; //assuming you have a field {name} in your table
echo "<br />";
}
mysql_query("delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
?>
First you'll need to select the data you're about to delete.
Then you'll need to delete it and return the selected rows.
$rows = array();
mysql_connect(...);
$res = mysql_query(...select query here...);
while($row=mysql_fetch_assoc($res)) {
$rows[] = $row;
}
$res = mysql_query(...delete query here...);
return $rows;
You might not want to totally delete the subscriber. If I were you I would include a field named "deleted" or something along those lines, indicating whether or not the subscriber has been deleted. Then query according to whether or not that field is true or false.