PHP: Input MySQL query - php

Hey guys I am a little confused, I have a listing page that displays all of my rows in my SQL table.
An example of what I am developing can be seen here: http://www.drivencarsales.co.uk/used-cars.php
So as you can see I have developed a listing page that fetches all of the table rows, each row is equivalent to one vehicle.
I now want to let users filter the results using the form to the left, I was going to use AJAX originally however I feel as if it would take way to long to learn how to develop it that way.
Here is the code setup I am using to achieve the example I have shown:
<?php
include('database.php');
try {
$results = $db->query("SELECT Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive FROM import ORDER BY Make ASC");
} catch (Exception $e) {
echo "Error.";
exit;
}
try {
$filterres = $db->query("SELECT DISTINCT Make FROM import ORDER BY Make ASC");
} catch (Exception $e) {
echo "Error.";
exit;
}
?>
As you can see the first block of code has two SQL selectors, the $results is used to fetch the whole table and list all vehicles.
The second block is used to display the 'Make' column for the form.
This block of code is the actual form:
<form>
<select class="form-control select-box" name="">
<option value="make-any">Make (Any)</option>
<?php while($make = $filterres->fetch(PDO::FETCH_ASSOC))
{
echo '
<option value="">'.$make["Make"].'</option>
';
} ?>
</select>
<button href="#" class="btn btn-block car-search-button btn-lg btn-success"><span class="glyphicon car-search-g glyphicon-search"></span> Search cars
</button>
</form>
As you can see this block is using a while loop to display all of the 'Make's' in the 'Make' column and uses a DISTINCT clause so that it doesn't show identical options.
Here is the block that lists the results to the page:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="listing-container">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
';
} ?>
So down to my question... How can I filter these results displayed in the listing block using the select element, when a user selects a 'Make' from the select element I want them to be able to submit the form and return all rows in the SQL table containing the same 'Make' string and hide other rows that are false.
Any ideas how I can achieve this or any easier ways?
Thanks

My best guess is for you to use JS to submit the form again, when select-option is selected, with a parameter stating the model.
Then in your PHP file, you should look for that parameter and edit the query-string accordingly.
see this answer on how to submit a form when option is selected.
This answer will show you how to handle parameters in PHP (using GET method)

Related

Toggling display of multiple related elements

I have two sets of buttons for every package, one for inserting data into my database and the other for deleting data from the database.
When I click the 'Select' button data will be inserted through AJAX and then hide the 'Select' button and display the 'Selected' button. When I click on the 'Selected' button the data will be deleted from the database through an AJAX call. The 'Selected' button will then be hidden and the 'Select' button will be shown again.
All the select & selected buttons are within a PHP while loop so the buttons have the same name but incremental IDs. When I click on one single 'Select' button, the other button is also showing me 'Selected'. I need something to track the each button ID when I click.
<div class="col-sm-2">
<a class="btn btn-primary select-btn select-btn-broadcast" id="<?php echo $id ; ?>" onClick="addintoListBroadcast(this)">Select</a>
<a class="btn btn-primary active-button active-button-broadcast" id="<?php echo $id ; ?>" onClick="deleteintoListBroadcast(this)" style="display: none;">Selected</a>
</div>
<script>
$('.select-btn-broadcast').click(function (e) {
var pkgId = this.id;
//alert(pkgId);
$('.select-btn-broadcast').hide();
$('.active-button-broadcast').show();
});
$('.active-button-broadcast').click(function(e) {
$('.select-btn-broadcast'.show();
$('.active-button-broadcast').hide();
});
</script>
The main issue with your code is because you select all the elements with the given class, not just the one related to the element which was clicked. To fix this use the this keyword to traverse the DOM to find the sibling() a element, and then amend it as required.
Also note that there's several other things you can improve in your code. Firstly, don't use inline CSS. Use the classes you've already applied to the elements to amend their styling in an external stylesheet.
Similarly, don't use inline event handlers such as onclick. Call the relevant functions within the unobtrusive event handlers you've bound through jQuery.
With all that said, here's a working example:
$('.select-btn-broadcast').on('click', function(e) {
$(this).hide().siblings('.active-button-broadcast').show();
// addintoListBroadcast(this);
});
$('.active-button-broadcast').on('click', function(e) {
$(this).hide().siblings('.select-btn-broadcast').show();
// deleteintoListBroadcast(this);
});
.active-button-broadcast {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-2">
<a class="btn btn-primary select-btn select-btn-broadcast">Select</a>
<a class="btn btn-primary active-button active-button-broadcast">Selected</a>
</div>
<div class="col-sm-2">
<a class="btn btn-primary select-btn select-btn-broadcast">Select</a>
<a class="btn btn-primary active-button active-button-broadcast">Selected</a>
</div>
<div class="col-sm-2">
<a class="btn btn-primary select-btn select-btn-broadcast">Select</a>
<a class="btn btn-primary active-button active-button-broadcast">Selected</a>
</div>

laravel a href validation

I would like to ask if it is possible to validate a href element in laravel.
For example, I'm having a bunch of people responses in my guest book and each user is able do delete his posts. I'm deleting it like this:
<div class="col-lg-2">
<ul class="list-unstyled trash">
<li>
<a href="/responses/{{$response->id}}">
<span onclick="alertDialog()" class="glyphicon glyphicon-trash"></span></a></li>
<li><button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#{{$response->id}}">Edit</button></li>
</ul>
</div>
Unfortunately, every single user can change "/responses/{{$response->id}}"> id via browser developer tools and delete other user's responses. Is there any possible solutions to prevent this issue?
Just check the logged user before rendering that html section:
<div class="col-lg-2">
<!-- assuming post is your variable and user is a property which references the user who created the record -->
#if($post->user == Auth::id())
<ul class="list-unstyled trash">
<li>
<a href="/responses/{{$response->id}}">
<span onclick="alertDialog()" class="glyphicon glyphicon-trash"></span></a></li>
<li><button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#{{$response->id}}">Edit</button></li>
</ul>
#endif
</div>
This way only the user who owns the post will be able to see the button in the html.
You need to use policies to check if the user that tries to delete a record is its owner:
public function delete(User $user, Model $model)
{
return $user->id === $model->user_id;
}
Or you can do it manually in a controller method:
if (auth()->id() === $model->user_id) {
// Delete the record
}
You should make /responses/{{$response->id}} a POST route and verify that the passed id matches with the authenticated users id. ( Auth::user()->id;)
I ended up checking like this in my destroy(id) method:
$count = Comment::where(['response_id' => $id])->count();
if (($responses->where('id',$id)->value('guests_email') == Cookie::get('email') && ($count==0)) || (Auth::check()))

PHP: Filtering SQL query with select options

Hey guys I am a little stuck at the moment, basically I am trying to find out how I can filter my SQL queries however having a bit of trouble understanding how it can be done.
Basically I am listing all of the 'Makes' of the brands I have on my site into a form. I am simply taking the column from my products table that contains every product.
Here is an example of the code, this is the PDO and MySQL selection:
<?php
include('database.php');
try {
$results = $db->query("SELECT Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive FROM import ORDER BY Make ASC");
} catch (Exception $e) {
echo "Error.";
exit;
}
try {
$filterres = $db->query("SELECT DISTINCT Make FROM import ORDER BY Make ASC");
} catch (Exception $e) {
echo "Error.";
exit;
}
?>
I have added DISTINCT to that block of code as there are duplicate 'Make's' in the SQL column.
Here is the form, as you can see I am using a while loop to display every make in the table into it's own option.
<form>
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<?php while($make = $filterres->fetch(PDO::FETCH_ASSOC))
{
echo '
<option value="">'.$make["Make"].'</option>
';
} ?>
</select>
<button href="#" class="btn btn-block car-search-button btn-lg btn-success"><span class="glyphicon car-search-g glyphicon-search"></span> Search cars
</button>
</form>
I am using this code to display the SQL rows into listed results:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="listing-container">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
';
} ?>
My question is how can I use the selection element to filter the exact 'Make', so for example if the SQL row contains the same 'Make' as the user has selected then I would like the whole row to display into the list and any other makes to not show.
Any code examples to how I can achieve this?
Thanks
You need to have something like:
$where = "";
if (!!$selectedMake) {
$stmt = $db->prepare("SELECT Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive FROM import ORDER BY Make ASC");
$stmt->execute();
} else {
$stmt = $db->prepare("SELECT Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive FROM import where Make = ?");
$stmt->execute(array($selectedMake));
}
Note that the order by is not needed in the else block, as you have a unique Make. If your Make is textual, then you might need '%?%' instead of ? in the query.
EDIT:
If I understood well, you still have a problem, namely, you lack the knowledge to determine what the value of $selectedMake should be. First of all, you should have a name for your select tag, so you should have this:
<select class="form-control select-box" name="selected-make">
This way when you submit the form, the value of your selected tag will be sent to the server. So if you want to pass a value when the form submits, you should give the given tag a name.
A form can be get or post. If it is get, then the passed value should be in get. Try it out with:
echo var_dump($_GET);
If it is post, the passed value should be in post. Try it out with:
echo var_dump($_POST);
Finally, you can initialize your $selectedMake like this:
$selectedMake = "";
if (isset($_GET["selected-make"])) {
$selectedMake = $_GET["selected-make"];
} else if (isset($_POST["selected-make"])) {
$selectedMake = $_POST["selected-make"];
}
There are lot of ways to achieve this, but you can use ajax request here.
Send ajax post request to your sql query page with selected option as a post parameter.
On the query page, you can pass that post parameter into where clause of sql query.
Then fill up the table on ajax success response.

PHP, MySQL & jQuery: Display select options dynamically

having a bit of a problem here understanding how I can make the following action happen on my web page:
Right so at the moment I have two select elements on my page, one of the select elements looks like this:
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<?php while($make = $makeFilter->fetch(PDO::FETCH_ASSOC))
{
echo '
<option value="'.$make["Make"].'">'.$make["Make"].'</option>
';
} ?>
</select>
As you can see this code is looping the 'Make' column of my SQL table, in the separate file that contains the queries I have made it so the query is using DISTINCT so it doesn't loop the same 'Makes' as the chances are there will be identical 'Makes' in the column.
I then have this block of code that displays another query into the front end:
<?php while($row = $results->fetch(PDO::FETCH_ASSOC))
{
echo '
<div class="makes ' . $row["Make"] . '">
<div class="listing-container">
<h3 class="model-listing-title clearfix">'.$row["Make"].' '.$row["Model"].' '.$row["Variant"].'</h3>
<h3 class="price-listing">£'.number_format($row['Price']).'</h3>
</div>
<div class="listing-container-spec">
<img src="'.(explode(',', $row["PictureRefs"])[0]).'" class="stock-img-finder"/>
<div class="ul-listing-container">
<ul class="overwrite-btstrp-ul">
<li class="diesel-svg list-svg">'.$row["FuelType"].'</li>
<li class="saloon-svg list-svg">'.$row["Bodytype"].'</li>
<li class="gear-svg list-svg">'.$row["Transmission"].'</li>
<li class="color-svg list-svg">'.$row["Colour"].'</li>
</ul>
</div>
<ul class="overwrite-btstrp-ul other-specs-ul h4-style">
<li>Mileage: '.number_format($row["Mileage"]).'</li>
<li>Engine size: '.$row["EngineSize"].'cc</li>
</ul>
<button href="#" class="btn h4-style checked-btn hover-listing-btn"><span class="glyphicon glyphicon-ok"></span> History checked
</button>
<button href="#" class="btn h4-style more-details-btn hover-listing-btn tst-mre-btn"><span class="glyphicon glyphicon-list"></span> More details
</button>
<button href="#" class="btn h4-style test-drive-btn hover-listing-btn tst-mre-btn"><span class="test-drive-glyph"></span> Test drive
</button>
<h4 class="h4-style listing-photos-count"><span class="glyphicon glyphicon-camera"></span> 5 More photos</h4>
</div>
</div>
';
} ?>
As you can see that block is looping various columns of my SQL table to display pretty much the whole table. PLEASE NOTE that the div with the class of 'makes' also includes the column 'Make' in the div.
I then use this jQuery to filter what results are brought to the screen:
<script>
$(document).ready(function(){
$('.form-control').change(function(){
var make = $(this).val();
if(make != 'make-any'){
$('.makes').hide();
$('.'+make).show();
} else {
$('.makes').show();
}
});
});</script>
As you can see it simply hides divs that don't have the class of the select value that has been selected.
So all of that is great however I get the feeling it just isn't enough for my users, I now want the users to be able to use a second select element to select a 'Model' of the 'Make'.
Now I know I could easily do this with the same technique I did at first but then users would be able to select 'BMW' and then select a model that wasn't associated with the 'Make' and no results would be returned.
I'd like my select element that contains the 'Models' to first of all be disabled until a user has selected a 'Make' then when a user has selected the 'Make' I'd like the second select element to show only the 'Models' that are associated with that 'Make'.
Here is an example of the columns in my SQL table:
Make, Model, Colour, FuelType, Year, Mileage, Bodytype, Doors, Variant, EngineSize, Price, Transmission, PictureRefs, ServiceHistory, PreviousOwners, Options, FourWheelDrive
I am now unsure how I can make this happen, it's really baffled me.
If someone could show me a detailed example and explain what each part does that would be great as I am a little stuck, thanks.
There are two options:
you could preload the data and save it as an object in JS and display when needed.
Or you could use ajax-calls to load the data when you need it(most websites do that nowadays)
use
$('makeselect').on('change', function() {
$.get("getmodels.php?make="+$("makeselect").val(),function(data){
var models=json.parse(data);
//iterate through the object and create the option tags
});
});
and give the select an id.
on php you should send the data encoded with json. json_encode(...)

Query to show "standard" theme first, then rest of the results

I have following query to show a list of installed themes. But users can make one theme as standard and I wonder if there is a way to pin the standard theme at the top?
Example:
Design 1
Design 2 (Standard)
Design 2 is marked as standard, and should be visible at top and not everywhere else.
Design 2 (Standard)
Design 1
Design 3
Design 4
SQL/PHP
$find_themes = mysqli_query($con, "SELECT * FROM installed_designs WHERE u_id='$user[id]' order by tmp_id desc");
while($themes = mysqli_fetch_array($find_themes))
{
echo '<tr>
<td>'.$themes["name"].'</td>
<td>'; if($themes["standard"]=='1') { echo '<b>Standard</b>'; } echo '</td>
<td>
<div class="btn-group pull-right">
<button type="button" class="btn btn-default btn-sm btn-grey own-toggle" data-toggle="dropdown">
Velg handling <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>Sett som standard</li>
<li>Endre HTML/CSS</li>
<li>Historikk</li>
<li class="divider"></li>
<li>Slett og fjern</li>
</ul>
</div>
</td>
</tr>';
}
Alter your query like this:
SELECT
*
FROM
installed_designs
WHERE
u_id='$user[id]'
ORDER BY
standard DESC,
tmp_id DESC
I noticed you have a standard flag in your table so use two ordering rules: first by standard descending (standard will go first, then non-standards) and then by your tmp_id (if the standard value is the same this rule will be applied).

Categories