Getting rid of duplicates in PHP while loop - php

So here's my php code:
$sql1 = "SELECT year FROM reports ORDER BY year DESC";
$res1 = mysql_query($sql1);
while($row = mysql_fetch_array($res1)) {
$selectYear = "
<select id='select_year'>
<option value='".$row['year']."'>".$row['year']."</option>
</select>
";
}
What I want it to do is just output one year instead of what its doing now which is outputting every single year and there is one entry for each month of the year so there are 12 entries with the same year so my html is this:
<select id='select_year'>
<option value='2013'>2013</option>
<option value='2013'>2013</option>
<option value='2013'>2013</option>
<option value='2013'>2013</option>
<option value='2012'>2012</option>
</select>
But this is what I actually want:
<select id='select_year'>
<option value='2013'>2013</option>
<option value='2012'>2012</option>
</select>
This is to sort through all the results by year so that the user can just use the select to select which year they want to view.

There are lots of ways of doing this, but the easiest is probably:
$sql1 = "SELECT DISTINCT year FROM reports ORDER BY year DESC";
With DISTINCT, the database will only return one of each value. Then you don't have to waste any resources processing data on the PHP side.

#Thomas Kelley has given the perfect answer above.
However, if you insist on PHP solution. You can do it as follows.
$res1 = mysql_query($sql1);
$placeHolder = ",";
while($row = mysql_fetch_array($res1)) {
if ( strpos($placeHolder , $row['year']) )
continue;
$placeHolder .= $row['year'] .',';
$selectYear = "
<select id='select_year'>
<option value='".$row['year']."'>".$row['year']."</option>
</select>
";
}

Related

Ignore empty "$_POST" values in MySQL queries

I have three select box menus:
<select name="category" id="category" class="form-control" size="5">
<option value="">Delete</option>
<option value="0">Option 0</option>
<option value="1">Option 1</option>
</select>
<select name="category2" id="category2" class="form-control" size="5">
<option value="">Delete</option>
<option value="0">Option 0</option>
<option value="1">Option 1</option>
</select>
<select name="category3" id="category3" class="form-control" size="5">
<option value="">Delete</option>
<option value="0">Option 0</option>
<option value="1">Option 1</option>
</select>
The selected options are sent with ajax to a server sided script. Here I catch the selected options and use them in MySQL queries:
$query = "
SELECT * FROM itemSparse
INNER JOIN item
ON item.id = itemSparse.id
LEFT JOIN itemsubtest
ON itemsubtest.subclass = item.Material
INNER JOIN itemModifiedAppearance
ON itemModifiedAppearance.ItemID = itemSparse.id
INNER JOIN ItemAppearance
ON ItemAppearance.identifier = itemModifiedAppearance.ItemAppearanceID
INNER JOIN manifestInterfaceData
ON manifestInterfaceData.ID = ItemAppearance.DefaultIconFileDataID
WHERE 1=1
";
$query.= " WHERE item.ClassID = 4 ";
if(isset($_POST["is_category"]))
{
$query .= " AND item.Material = '".$_POST["is_category"]."'";
}
if(isset($_POST["is_category2"]))
{
$query .= " AND itemSparse.OverallQualityID = '".$_POST["is_category2"]."'";
}
if(isset($_POST["is_category3"]))
{
$query .= " AND itemSparse.StatModifier_bonusStat1 = '".$_POST["is_category3"]."'";
}
The problem:
The queries are only working when all three select menus have a selected value. If not all three menus have a selected option no results are shown.
I want that results are shown even if only one or two select menus have options selected. This means a query with an empty $_POST value should be ignored, but the others should be executed. How can I handle that?
The easiest way is to put WHERE 1=1 clause, that will result TRUE. After that you can append any AND clause.
$query = "SELECT * FROM table WHERE 1=1 "
if(isset($_POST["is_category"]))
{
$query .= " AND item.Material = '".$_POST["is_category"]."'";
}
if(isset($_POST["is_category2"]))
{
$query .= " AND itemSparse.OverallQualityID = '".$_POST["is_category2"]."'";
}
if(isset($_POST["is_category3"]))
{
$query .= " AND itemSparse.StatModifier_bonusStat1 = '".$_POST["is_category3"]."'";
}
Also change this to use prepared statement, otherwise the query is vulnerable to SQL Injection attack
The issue you have is that the $_POST variables are all sent, because they are all part of the same form, so the resulting query has all the conditions with ='' for every field that is empty.
So you if you use !empty() instead of isset() your code should work
if(!empty($_POST["is_category"]))
{
$query .= "item.Material = '".$_POST["is_category"]."' AND ";
}
if(!empty($_POST["is_category2"]))
{
$query .= "itemSparse.OverallQualityID = '".$_POST["is_category2"]."' AND ";
}
if(!empty($_POST["is_category3"]))
{
$query .= "itemSparse.StatModifier_bonusStat1 = '".$_POST["is_category3"]."' AND ";
}
However, do note that your query has a major sql injection vulnerability, so such code should not be used in a production environment. For a production server you need to use prepared statement.

Dropdown menu to filter results in php get all results from sql

I have this drop down:
<select class="w-select filterdropdown" id="Tipo-de-cocina" name="tipofiltro" data-name="Tipo de cocina">
<?php
if (isset($_GET['tipofiltro'])) {
echo '<option value="' .$filtrocuisine. '"> ' .$filtrocuisine. "</option>";
} else {
echo '<option value="Todos los tipos">Todos los tipos</option>';
}
?>
<option value="Japonesa">Japonesa</option>
<option value="Mexicana">Mexicana</option>
<option value="India">India</option>
<option value="Mediterranea">Mediterranea</option>
<option value="Italiana">Italiana</option>
<option value="Americana">Americana</option>
<option value="Asiatica">Asiatica</option>
<option value="Thai">Thai</option>
<option value="China">China</option>
<option value="Francesa">Francesa</option>
<option value="Turca">Turca</option>
<option value="Latina">Latina</option>
<option value="Africana">Africana</option>
<option value="Griega">Griega</option>
<option value="Arabe">Arabe</option>
</select>
How can i make that when the user selects the field "Todos los tipos" my sql query returns all types? This is the sql behind:
if (isset($_GET['preciofiltro']) OR isset($_GET['preciofiltro'])) {
$filtroprecio = $_GET['preciofiltro'];
$filtrocuisine = $_GET['tipofiltro'];
$sql = "SELECT Meals.Meal_ID, Meals.Name, Price, Cooks.Cook_ID
FROM Meals
INNER JOIN Cooks ON Cooks.Cook_ID = Meals.Cook_ID
WHERE Cooks.Area = '$area'
AND Meals.Capacity > 0
AND Meals.Price < '$filtroprecio'
AND Meals.Type = '$filtrocuisine'";
$result = mysqli_query($conn, $sql);
Basically I would need something such as "AND Meals.Type = any"
Cheers!
Well there are simpler methods but without rewriting everything the simple answer is that if the user selects Todos los tipos from the dropdown what you actually want to do is remove this selection criteria AND Meals.Type = '$filtrocuisine' from the query completely i.e. you no longer limit the query with that criteria.
So change your script like this :-
I am of course assuming that you have taken data from the $_GET array, validated it, and cleansed it before we get to this code.
if (isset($_GET['preciofiltro']) OR isset($_GET['preciofiltro'])) {
$filtroprecio = $_GET['preciofiltro'];
$filtrocuisine = $_GET['tipofiltro'];
$sql = "SELECT Meals.Meal_ID, Meals.Name, Price, Cooks.Cook_ID
FROM Meals
INNER JOIN Cooks ON Cooks.Cook_ID = Meals.Cook_ID
WHERE Cooks.Area = '$area'
AND Meals.Capacity > 0
AND Meals.Price < '$filtroprecio'";
if ( isset($filtrocuisine) && $filtrocuisine == 'Todos los tipos' ) {
$sql .= " AND Meals.Type = '$filtrocuisine'";
}
$result = mysqli_query($conn, $sql);

how can i make this dynamic BETWEEN '2014-07-01 00:00:00' AND '2014-07-31 23:59:59'";

Im still a noob php programmer. Please help me with my problem. I was trying to code a timeline. Im stuck at the query part. Let's say i have a select element with the months in it. If ever I want to select the July, the timeline displays all the events listed on July 2014. What if its already 2015? my query remains static (BETWEEN '2014-07-01 00:00:00' AND '2014-07-31 23:59:59'";)
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("prototype") or die(mysql_error());
if(isset($_POST['submit'])) {
if($_POST['month'] == 'July') {
$sql = "SELECT * FROM events WHERE event_schedule BETWEEN '2014-07-01 00:00:00' AND '2014-07-31 23:59:59'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo "Title:".$row['event_title']."<br>";
echo "Description:".$row['event_description']."<br>";
echo "Schedule:".$row['event_schedule']."<br>";
echo "Date Created:".$row['date_created']."<br>";
echo "Posted By:".$row['posted_by']."<br>";
}
}
if($_POST['month'] == 'August') {
$sql = "SELECT * FROM events WHERE event_schedule BETWEEN '2014-08-01 00:00:00' AND '2014-08-31 23:59:59'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo "Title:".$row['event_title']."<br>";
echo "Description:".$row['event_description']."<br>";
echo "Schedule:".$row['event_schedule']."<br>";
echo "Date Created:".$row['date_created']."<br>";
echo "Posted By:".$row['posted_by'];
}
}
}
echo date("F Y");
?>
<html>
<form method="post">
<select name="month">
<option selected="selected">Select a month...</option>
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
<input type="submit" name="submit" value="Submit">
</form>
</html>
You can embed PHP vars into your query text. So you can pull the current year with date():
$queryYear = date('Y');
$sql = "SELECT * FROM events WHERE event_schedule BETWEEN '{$queryYear}-07-01 00:00:00' AND '{$queryYear}-07-31 23:59:59'";
You can try something like this
$sql = "SELECT * FROM events WHERE event_schedule LIKE '%-07-%'";
As already been commented you should consider in changing your code to work with MYSQLi or PDO functions. Mysql_* functions is deprecated.
As for your answer I would recomment two things.
1 - Add the month values on your html form
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
...
2 - Change your PHP with just on set of code, you don't need to test each case and repeat your code. Something like this:
if(isset($_POST['submit'])) {
/*AGAIN THIS IS NOT RECOMMENDED AS IT CAN BE SQLInjected*/
$sql = "SELECT *
FROM events ";
if ($_POST['month']!=''){
$sql .= " WHERE extract(YEAR from event_schedule) = extract(YEAR from now())
and extract(MONTH from event_schedule) = $_POST['month']";
}
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo "Title:".$row['event_title']."<br>";
echo "Description:".$row['event_description']."<br>";
echo "Schedule:".$row['event_schedule']."<br>";
echo "Date Created:".$row['date_created']."<br>";
echo "Posted By:".$row['posted_by']."<br>";
}
}

Make mysql query connect to the selected table in a drop down menu

I have a working mysql query that retrieves data from table1.
Now I will add every month a new table (table2, table3..etc).
Goal 1 : I would like to add a drop down menu and populate it with all tables as user options.
Goal 2 : I would like to make the query connect to the table that the user selects from the drop down menu, retrieves data and then refresh the page or just the table's div to display updated data.
my current mysql/php code :
$query = "SELECT X, Y, Z FROM **table1**";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['X'];
echo $row['Y'];
echo $row['Z'];
}
Instead of "table1" it should be a variable linked to the drop down menu that the user selects.
I feel it should be simple, but I am bit new to this and could not find a similar case.
Thanks a lot gents.
I like the comment above but here is an example not sure if that what you are looking for
<form action="process.php" method='post'>
<select name="tables">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" />
</form>
process.php file
$table=$_POST['tables'];
$query = "SELECT X, Y, Z FROM ".$table;
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['X'];
echo $row['Y'];
echo $row['Z'];
}
$result = 'SHOW TABLES [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr];';
while($row = mysql_fetch_array($result))
{
echo $row['Tables_from_db_name'];
}

How to update mysql data when using explode

I have this code to load the month of the birthday that corresponds to the id number:
<?php
$query = "SELECT DISTINCT BIRTHDAY FROM student WHERE IDNO='".$_GET['id']."'";
if($result = mysql_query($query))
{
if($success = mysql_num_rows($result) > 0)
{
?>
<select title="- Select Month -" name="mm" id="mm" class="" >
<?php
while ($row = mysql_fetch_array($result))
list($year,$month,$day)=explode("-", $row['BIRTHDAY']);
?>
<option value="<?php echo $month;?>"><?php echo $month; ?></option>\n";
And this is the form action:
$birthday = mysql_real_escape_string($_POST['mm']);
mysql_query("UPDATE student SET YEAR = FIRSTNAME='$fname', BIRTHDAY='$birthday'
WHERE IDNO ='$idnum'");
What should I do, when I click on the update button, it executes, but I see the undefined offset error is stored in the mysql database and not the month.
I'm just a beginner, can you give me some tips on how can I achieve updating the data
In cases like this... you will have to use 3 selects and then join them to update the database... so, in the form you have something like this:
<select name='month'>
<option value='1'>January</option>
<option value='xx'>etc</option>
</select>
<select name='day'>
<option value='1'>1</option>
<option value='xx'>etc</option>
</select>
<select name='year'>
<option value='1980'>1980</option>
<option value='xx'>etc</option>
</select>
Then... the PHP that receives that data should do something like:
$year = mysql_real_escape_string($_REQUEST['year']);
$month = mysql_real_escape_string($_REQUEST['month']);
$day = mysql_real_escape_string($_REQUEST['day']);
$birthday = $year.'-'.$month.'-'.$day;
mysql_query("UPDATE student SET YEAR = FIRSTNAME='$fname', BIRTHDAY='$birthday'
WHERE IDNO ='$idnum'");
Of course... you have to verify first whether all variables are set or not. You can do so by using the isset method.
Check your update query, It may be wrong in that.
mysql_query("UPDATE student SET YEAR = FIRSTNAME='$fname', BIRTHDAY='$birthday'
WHERE IDNO ='$idnum'");
See this year and firstname, in this year is assigned to null character for you.
Just assign like this,
$birthday = mysql_real_escape_string($_POST['mm']);

Categories