Filter MySQLi with checkboxes - php

At the moment, I have a page that is displaying some posts. News posts, blog posts etc. What I want to achieve is having checkboxes so the user can check off, whatever kind of post he/she wants to see.
I should for instance be able to check off ´news´ and ´talking points´ and only see posts with those categories, and not see posts with the category ´blog´ for instance.
My current query looks like this (gets all posts, no matter the category). I believe some jQuery should be involved but I am not sure. How can I connect checkboxes with the query?
Can anyone help me with this?
$sql = "SELECT * FROM articles ORDER BY id DESC";
EDIT
I have tried this, but whenever I use the checkboxes, nothing is shown but I do not get an error?
My code:
<?php
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
$categories = $_POST['check_list'];
// Loop to store and display values of individual checked checkbox.
foreach($categories as $selected){
echo $selected."</br>";
}
}
}
?>
<br /><br />
<?php
if(!empty($_POST['check_list'])){
$sql = "SELECT * FROM articles ORDER BY id DESC WHERE `category` IN (".implode(',',$categories).")";
} else {
$sql = "SELECT * FROM articles ORDER BY id DESC";
}

Each checkbox should have a value. When you submit your form (probably a $_POST) you will see on the backend which checkboxes are checked. You can inspire from this tutorial: https://www.formget.com/php-checkbox/
IMPORTANT - You should filter the form data before using it in your SQL query. You can inspire from here: http://php.net/manual/en/function.filter-input.php
And you should prepare the variable before using it in the SQL Query:
$unsafe_variable = $_POST["user-input"];
$safe_variable = mysql_real_escape_string($unsafe_variable);
Now that you know which checkboxes are checked, you need to change the SQL query in order to filter by them.
So I suppose the checkboxes values are numbers (representing id's). So you will have an array called $ids that will contain all the checked checkboxes. Your mysql query will become something like:
$sql = "SELECT * FROM articles WHERE `id_category` IN (".implode(',',$ids).") ORDER BY id DESC";

Related

Button to post value from fetched database data

I'm a beginner in PHP and PDO.
I'm trying to fetch database data from a database table, display it on a list and add a button that when clicked it adds the itemid value to another table with the name_id of the user.
The issue is even though the list is displaying the items in order and correctly,the button is not working 100%, when pressed on any item from the list it always posts the first itemid value from the database column.
Any help is appreciated.
echo ''.$itemid.'';
echo'<form action="" method="post"><button name="get" type="submit">CLICK ME</button></form>' ;
if(isset($_POST['get'])){
$query = "update table set fetched_item_id='".$row['item_id']."' where name_id='".$_SESSION['id']."' ";
if($query)
{
$query = $conn->prepare($query);
$query->bindParam('1', $itemid);
$query->execute();
echo "Success!";
exit;
}
I tried everything I could according to my knowledge.

MySQL return rows where column contains categories defined by array (and add weight to the results)

In my app, the user can type in an indefinite amount of categories to search by. Once the user hits submit, I am using AJAX to call my PHP script to query my DB and return the results that match what the user defined for the categories.
My category column is separated as so for each row: "blue,red,yellow,green" etc.
I have two questions:
How can I pass an array to MySQL (like so: [blue,yellow,green]) and then search for each term in the categories column? If at-least one category is found, it should return that row.
Can MySQL add weight to a row that has more of the categories that the user typed in, therefor putting it further to the top of the returned results? If MySQL cannot do this, what would be the best way to do this with PHP?
Thanks for taking the time and looking at my issue.
For the part 1 you can use the function below:
<?php
function createquery($dataarray){
$query="select * from table where ";
$loop=1;
foreach($dataarray as $data)
{
$query.="col='$data'";
if(count($dataarray)<$loop-1){
$query.=' or ';
}
$loop++;
}
return $query;
}
?>
This will return the long query.
use this some like this:
mysql_query("select * from table where category in (".implode($yourarray,',').")");
1)
Arrays are not passed to a MySQL database. What's past is a query which is a string that tells the database what action you want to preform. An example would be: SELECT * FROM myTable WHERE id = 1.
Since you are trying to use the values inside your array to search in the database, you could preform a foreach loop to create a valid SQL command with all those columns in PHP, and then send that command / query to the database. For example:
$array = array('blue', 'red', 'yellow', 'green');
$sql = "SELECT ";
foreach ($array as $value)
{
$sql .= $value.", ";
}
$sql .= " FROM myTable WHERE id = 1";
IMPORTANT! It is highly recommended to used prepared statements and binding your parameters in order not to get hacked with sql injection!
2)
You are able to order the results you obtained in whichever way you like. An example of ordering your results would be as follows:
SELECT * FROM myTable WHERE SALARY > 2000 ORDER BY column1, column2 DESC

Show certain code depending on mysql query? (php)

I need a little kickstart here.
We're just learning php in school and we have this project where we're making a website for movie browsing. So we wanna be able to select genre, and show all movies from that genre using a MySQL database. We're all clear on the SQL queries and such, my question is rather how I make the browser show movies depending on SQL query?
Let me explain. Say we're movies.com
So on movies.com/genre is where you select the genre right, and on movies.com/display is where you're supposed to see the movies from the genre selected. So, clicking on "Comedy" should take you to movies.com/display and show you only the comedy movies. Selecting "Drama" should take you to the same site (movies.com/display) and show you only the drama movies.
Problem here is that we just don't know where to begin, it became a problem when switching page to show certain sql queries depending on what you selected in a previous page. I am not sure how to Google it, but just a link or a suggestion will help. I'm sure it can't really be too hard.
Thanks in advance.
Start with the html to choose a genre:
<form action="display.php" method="POST">
<select name="genre">
<option value="drama">Drama</option>
<option value="comedy">Comedy</option>
<option value="thriller">Thriller</option>
<option value="horror">Horror</option>
</select>
<input type="submit" value="Submit"/>
</form>
Here we have a form with a dropdown menu to select the genre. The forms action goes to display.php
Create display.php where we can get the submitted value and put that into our query:
// get the submitted value
$genre = $_POST['genre'];
// set a default genre if the POST genre is empty
if(empty($genre)) {
$genre = 'comedy';
}
// connect to database
$link = mysqli_connect("localhost", "my_user", "my_password", "db_name");
// check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: (" . mysqli_connect_errno() . ") ";
}
// build the query
$query = "SELECT * FROM movie WHERE genre = '".$genre."'"; // unsafe !!
$query = "SELECT * FROM movie WHERE genre = '".mysqli_real_escape_string($link, $genre)."'"; // safer
// execute query
$result = mysqli_query($link, $query);
// check result
if (!$result) {
echo 'Query unsuccessfull!';
}
// show values
while($row = mysqli_fetch_assoc($result)) {
echo $row['title'];
echo $row['description'];
echo "<br/>";
}
// close connection
mysqli_close($link);
I would suggest having a table of genres. That way you can display the list of genres easily for a user to select from (ie, you could populate an HTML forms select list from that table). The list of genres would have a unique id (an integer) and a text description, so when the list of produced you display the description but have a value that is the id.
Then have a table of movies (I presume you already have this). Each movie would be identified by a unique integer id field/
Lastly a table of movies to genres. This would just link the id of the movie to the id of the genre(s) for the movie. This way you can have a movie linked to several genres if required.
Doing it this way also means that the values you return from the HTML forms can just be integers, which are easily made safe (just use the php intval() function).
In use you would provide a list of genres as a SELECT list. When the user selects an item and submits the form the id of the selected genre is returned to the script. The script can then do a query that joins the tables together, checking the genre is the selected genre that has been returned to the script.
For example.
tbl_genres
id
genre_name
tbl_movies
id
movie_name
tbl_genre_movie
genre_id
movie_id
Then to get the details for a returned genre id:-
$sql = "SELECT *
FROM tbl_genres
INNER JOIN tbl_genre_movie
ON tbl_genres.id = tbl_genre_movie.genre_id
INNER JOIN tbl_movies
ON tbl_genre_movie.movie_id = tbl_movies.id
WHERE tbl_genres.id = ".intval($_POST['genre_id']);

SQL "LIKE" If empty returns all rows

Hello I have 2 textboxes and i want to give to the user the option to choose one in order to find results. The user can search through the id or the name. My problem is because i use LIKE%field% when the user chooses to search through the id the name field stays empty and returns all the table rows. I want to have results only if the user enters some value in the textbox. This is my sql query. I'm using mysql
"SELECT * FROM properties WHERE ID='$id' OR Name LIKE '%$name%'"
Thank you all
If the user has to select which field to search, you can do:
if ($_POST['search'] == 'id') {
$sql = "SELECT * FROM properties WHERE ID='$id'"
} else {
$sql = "SELECT * FROM properties WHERE Name LIKE '%$name%'"
}
You can do this in a single query (values are checked from the query itself):
"SELECT * FROM properties WHERE ('$id'='' OR ID='$id') AND ('$name' ='' OR Name LIKE '%$name%')"
Explanation:
First condition:
The query will select records with ID='$id' only when $id is not empty.
If $id is empty, query will not go for the second part ID='$id'
Second condition:
The query filters records with Name LIKE '%$name%' only when $name is not empty.
If $name is empty, query will not go for Name LIKE '%$name%'.
NB: This technique is extremely useful when you have numerous parameters to check, rather than using a bunch of if...elses at php side.

Get the last checked checkboxes

I'm not sure how to accomplish this issue which has been confusing me for a few days. I have a form that updates a user record in MySQL when a checkbox is checked. Now, this is how my form does this:
if (isset($_POST['Update'])) {
$paymentr = $_POST['paymentr']; //put checkboxes array into variable
$paymentr2 = implode(', ', $paymentr); //implode array for mysql
$query = "UPDATE transactions SET paymentreceived=NULL";
$result = mysql_query($query);
$query = "UPDATE transactions SET paymentdate='0000-00-00'";
$result = mysql_query($query);
$query = "UPDATE transactions SET paymentreceived='Yes' WHERE id IN ($paymentr2)";
$result = mysql_query($query);
$query = "UPDATE transactions SET paymentdate=NOW() WHERE id IN ($paymentr2)";
$result = mysql_query($query);
foreach ($paymentr as $v) { //should collect last updated records and put them into variable for emailing.
$query = "SELECT id, refid, affid FROM transactions WHERE id = '$v'";
$result = mysql_query($query) or die("Query Failed: ".mysql_errno()." - ".mysql_error()."<BR>\n$query<BR>\n");
$trans = mysql_fetch_array($result, MYSQL_ASSOC);
$transactions .= '<br>User ID:'.$trans['id'].' -- '.$trans['refid'].' -- '.$trans['affid'].'<br>';
}
}
Unfortunately, it then updates ALL the user records with the latest date which is not what I want it to do. The alternative I thought of was, via Javascript, giving the checkbox a value that would be dynamically updated when the user selected it. Then, only THOSE checkboxes would be put into the array. Is this possible? Is there a better solution? I'm not even sure I could wrap my brain around how to do that WITH Javascript. Does the answer perhaps lie in how my mysql code is written?
--
Edit: Ok, just more information. The SQL Queries I have going on - the first two are to wipe everything clean (in case a checkbox is UNCHECKED) and then next they are updating the SQL queries based on which checkboxes are checked upon post.
However, I'm thinking this is a bad way to do it. Why force the database to first wipe out ALL data for paymetreceived, paymetdate? The problem with this, also, is that *all the subsequent checkboxes, regardless of how long ago they were checked, get updated in the SQL query as it is now.*There's got to be a way to update it better. I'm just not sure HOW to do it. any ideas?
You are not filtering by id in this queries:
$query = "UPDATE transactions SET paymentreceived=NULL";
$query = "UPDATE transactions SET paymentdate='0000-00-00'";
Try adding: WHERE id IN ($paymentr2)";
The problem is in your first 2 sql UPDATE statements. You don't provide a WHERE clause, so that's going to update all your records. You could add:
WHERE id IN ($paymentr2)
to your first two UPDATE statements

Categories