Selecting SQL Query from Javascript Selections - javascript

https://docs.google.com/file/d/0B9urXGIYtvx-YzdYNlllbUxFeHM/edit?usp=drive_web
Attached is a picture of what I have done so far. This is just the front end and I need help with the backend.
I have a question about using SQL to bring up a table based on these selections. I created these dropdowns and selections using javascript but I want to be able to pass them on to a sql to search the database based on selections and return anything that fits the criteria.
To explain everything:
I want to lists at the bottom to be apart of the Select (ex. Select OrganizationID, OrganizationName, OrganizationType, EventID, EventName)
Then I would like the two selections at the top to be the FROM (ex. FROM Events, Organization) and then of course join these with a WHERE.
Then I would like the include or exclude to be apart of the WHERE (ex. WHERE EventID=32211)
I know that I will have to use PHP for this as well and that's perfectly fine I just need help starting it to find out how to pass these selections.

the easiest way is to wrap everything in a FORM tag with an action property. The action property will specify the page you'll be sending the data to (via an http post by default).
so you could put action="searchresults.php", for example.
Your server will receive the values from all of the inputs on your page inside of the $_POST variable. The $_POST variable is an associative array where the key is the name attribute of the input elements.
so to get the values the people entered you'd do something like this:
if (isset($_POST)){
$table=$_POST["Table"]; //where Table is the name of your first option box, it should get the value assigned to the option element.
}
After you get the values, you need to build out your query. The ONLY ways you should EVER consider doing this is through either a prepared statement or a stored procedure.
here's the php documentation on MSSQL prepared statements: http://us2.php.net/sqlsrv_prepare
the long and the short of it:
//$conn is the database connection, $params is an array of the parameters to fill in the ?.
$sql = "SELECT FROM table WHERE id=?";
$stmt=sqlsrv_prepare ($conn, $sql , $params);
NEVER build a query by concatenating user inputs, this leaves you open to SQL injection attacks.
If you'd like some more specifics, you're going to have to provide more information, a database schema, the HTML on your form, some expected results.

Related

Passing a Cookie Value Through Form To PHP

I made this post to try to see if there is a different way (or something I'm doing wrong) to get my Cookie with an value into a hidden input which can send the value through a form to my MySQL database.
I am trying to grab a cookie with my "getCookie()" function and then put it in a hidden form to then pass through to my database. There may be simpler ways I am unaware of, but currently this is what I have:
Inside my form I have:
var cookie_val = getCookie("id"); and
$('input[name=id]').val(cookie_val);
When outputting the "getCookie("user")" simply with a document write I get the value that I am looking for, however, in my MySQL database when it arrives it ends up as a value of 0. I am not fully understanding of how
$('input[name=id]').val(cookie_val);
works.
I am fairly confident that my PHP code is not the issue in all of this.

How to show records *only* from current user php

I'm developing a web app that allows me to generate product orders in PHP. When I first started, I was thinking only about my product orders, however, I have 3 more sales representatives and I would like for them to use it as well.
The problem I'm currently facing is that whenever I'm looking for product orders (using an ajax), all users are allowed to see all the product orders. I would like that each user can only see **their* product orders, but I'm not sure how the query should be.
What would the query be considering these tables?
Thanks in advance!
UPDATE:
So, thanks to #Nicolas answer, I was able to get only information for a selected vendor. However, the 'nombre_cliente(client name)' from 'clientes' tables is wrong for every row. It is showing only the first row. Other information is correct, except for the name. Here is what the results look like now, and how I'm looping through the data.
results
looping
Thanks in advance to everyone.
From what i understand, You would need to know who's asking the server for every request. There's multiple way to achieve this and we don't have enough informations about your infrastructure to give you a good way to accomplish this. Are you using PHP session, are you using an API with API keys, etc. Either way, To get only the product order for a particular vendor, you would need to execute a SQL that would look like that :
SELECT * FROM `facturas` WHERE `id_vendedor` = 1;
In this example, 1 is the id of the connected user.
This request will filter every order and returns only the one that have been done by the user with the id : 1.
You could also join both tables together and filter by some other property of the user table. Lets say we want to get every order by the user whose name contains "john". we would do a request like that :
SELECT facturas.* FROM `facturas` JOIN `users` ON `facturas`.`id_vendedor` = `users`. `user_id` WHERE `users`.`firstname` LIKE '%john%';
In this case, we are joining both table, mapping every id_vendedor to an user_id in the user table, and filtering by firstname. The like operator can be translate to : 'anything john anything'.
IMPORTANT
If you are doing SQL request in any language, make sure you are binding your parameters
Thanks to #Nicolas help, I was able to fix my problem. The final query is:
SELECT * FROM facturas JOIN clientes ON facturas.id_cliente=clientes.id_cliente where facturas.id_vendedor=$current_user (variable that I used to keep track of who is logged in)

how to add security to updating rows in a database PHP

Say in my ajax request page, I have a row of results pulled from the database that looks something like this:
while ($stmt->fetch()) {
echo "<p value='".$taskId."' class='titleRsltTask'>".$taskTitle."</p><br>";
}
Here $taskId is the primary key for the row returned. When the results are returned to the DOM, a user can inspect and change this id. Say I have another ajax request to delete or update the above results when .titleRsltTask is clicked,
$(document).ready(function(){
$('.titleRsltTask').click(function(){
id = $(this).attr('value');
$('#taskResults').load('Includes/updateTask.inc.php', {
Id: id
});
});
which uses the value $taskId to find which row to update in updateTask.inc.php.
What are some ways I can verify that the row that the user is updating belongs to them so that they can't update any rows in the table by changing the value in the inspect element?
Is there a better way to set this up in the first place? Does using an SSL help in any way?
Are there other security measures you want to point out, I'd be glad to hear them.
I've done some research on authorization, authentication, and encryption but still not exactly sure what to do in this situation.
I do understand your concern about security, as the value returned are auto incremented numbers.
Using a ssl wont encrypt or provide you any security with such things.
SSL only encrypts other users connection to your website.
SSL encrypts the packets transmitted to your website.
One way you could apply additional layer of security is by encrypting the numeric id returned from the server using some salt algorithm and displaying it in the view in encrypted format.And then decrypt it at the server.
Updating and changing the encrypted value wont do any good even if someone changes it using inspect element, as that would not be processed into a valid value when being decrypted in the server.
Hope this helps.
Thanks
You should reconsider your table structure. If users are only able to change certain row, then on each row include the user ID that can edit it, use authentication with the request (by including a session cookie etc), and add that logic to the UPDATE command. If a group of users can change certain rows, then have an extra column specifying the group ID/privilege, and ensure each user has a privilege level set.

How to secure the JSON data that's being passed from the AJAX file to jqGrid

First of all, thank you so very much for making jqGrid! It's an excellent piece of work!
When my index.php file POSTs the JSON-encoded search criteria to my grid.php file, grid.php processes the criteria, queries the database, and returns a JSON-encoded string back to index.php, which in turn takes the results and renders them in a jqGrid table.
Everything works splendidly.
However, if an in-house user points their browser to grid.php, it will return a set of records that satisfies the default criteria (30 records per page, the fields and their data, as programmed). And because I have it setup to POST, a user could append query parameters manually to grid.php, e.g.:
http://foo.bar/grid.php?clientID=123&city=anytown
I've placed security checks in both my index.php and grid.php. As an example:
if(userGroup='Sales'){
$sqlstr = "SELECT * FROM table WHERE group='SALES'";
}else{
$sqlstr = "SELECT * FROM table";
}
But the problem is that they can bypass these checks by pointing their browser to grid.php directly.
Does anyone have suggestions of how to secure the string that's returned by grid.php?
UPDATE
Per Justin's suggestion, I think that I might be on the right path now. Something like this might work:
$trace = debug_backtrace();
if ($trace[0]['file'] != 'index.php'){
echo "There was an error. Please contact your Systems Administrator.";
return 0;
}
Well, that didn't work as expected. I'm leaving this info here for posterity.
You need to add PHP code to secure the grid.php URL. First, if it is feasible for your application, you can add an authentication system to prevent just any users from accessing the URL. Once that is in place, you could secure it even more by adding role-based or user-based permissions.
For example, only allow the user group of "sales" to be appended if the user provides that option and they are a member of the "sales" group.
How you will actually implement this depends up on what PHP framework you are using (if any) and the requirements of your application.

Drop down Selection -> Search database

How would I search an SQL database when a user makes a selection in a dropdown list. I know how to change/add text to areas using some javascript but not with a SQL search as well.
Ideally I don't want to be changing pages in this process as I'm thinking they won't be sticking on a single option in the drop down for long.
Cheers in advance. =)
You have to add an onchange event listener to the dropdown box. When the user selects an option, an AJAX (XmlHttpRequest) should be send to the server. A serverside script, a PHP page for example, should parse the parameters (after checking).
When these parameters have been checked, they should be escaped for this reason. Perform a search query, parse the results, and send the output back to the client (the user, browser).
Useful links:
http://www.php.net/manual/en/ref.mysql.php
https://developer.mozilla.org/en/xmlhttprequest
you should look into implementing Ajax for this.
Here's a simple example and tutorial utilizing a drop down list that fetches information from a database on selection, without changing pages :)
http://www.w3schools.com/php/php_ajax_database.asp
You should also look into using jquery for your Ajax requests as stated in the answer below. (Do more with less code).
See also:
http://15daysofjquery.com/quick-and-dirty-ajax/14/ for a simple jquery Ajax tutorial.
Before you render the page, make sure you do a grab the info you want presented from the database.
select distinct NAME, ID
from tableName
You can use the information obtained here to generate the html for a drop down box. Include something to the effect
<select onchange="doAction(this.value);">
<option value="userID">userName</option>
<option value="userID">userName</option>
<option value="userID">userName</option>
...
</select>
Then perform an AJAX request back to your site. Get your information from your second query to the database, and return with the information you need. When you perform your second query (and in general) you have to protect yourself against injection attack vectors. The best start for this is to make sure you have encoded(HTML, SQL) correctly.
Without more information I can only really give you the below as a guide. It uses the jQuery load function to put the contents of one page into an element. Note that .load cannot be used across domains.
$("#searchButton").live("click", function() {
$("#results").load("/SearchResults.php?s=" + $("#searchBox").val());
});
Also note that you should use something to filter out HTML tags to prevent SQL injection, as well as taking other measures.

Categories

Resources