Selecting SQL table column with Jquery - SQL injection? - php

I'm looking for a bit of advice on which method is more secure and efficent to use.
OPTION A: I have a database named calendar, and 12 tables in it - "January", "February" etc. Each month has it's own .php page with "select * from jan" etc. I have a dropdown menu, which when the user selects for example "January" I have an ajax script that then loads jan.php into the div "currentmonth"
What I was thinking of doing, because along with the "currentmonth" div, I've also got a "recentlyadded" div showing the last 3 entries sorted by their timestamp. I'm not sure how I could show the 3 most recently added entries in the whole database, so I tried option B.
OPTION B: I have one table called calendar, and each row has a column called month. This made it more simple for display the recently added, but I'm not sure how to go about implementing the dropdown menu. From what I've read the idea I have can leave me open to sql injection.
Here's the idea: I have a jquery variable called "selectedmonth" which is equal to the value of the selected month. I then want to take that variable... for example, user selects "January" the value is "jan", and I want the sql statement to then update with SELECT * FROM calendar WHERE months = "jan", but as I said, I hear this can leave me wide open to SQL injection.
Is there anyway to dynamically update the SQL statement, maybe with AJAX or JSON? Is there a way to do OPTION B without leaving myself open to SQL injection? Or is there an easier way for me to use OPTION A, and be able to find the 3 most recent added rows in the entire database?
The one thing I'm wondering though is with option A, I would obviously have 12 "month".php files, will that add a lot to page load times?
Any advice would be greatly appreciated.

Use prepared statements and you should be fine. The second option is preferable, the first is not a good idea...
All you have to do is something like:
$row = $conn->prepare("SELECT * FROM calendar WHERE months = ?");
$row->bind_param('s', $_GET['month']);
$row->execute();
$row = $row->get_result();
And you'll be SQL injection-free. Read more here.

Related

Mysqli php ajax Pagination

can someone please explain to me how to approach this issue?
I have a table with 4000 records, a select option and a search field to filter out the table
however I'm trying to figure out the best way to set up pagination.
1st Approach:
Should I make one query against the database and populate the table with all records and then set up the pagination with javascript so I can be able to search for records that are not only shown on the current page?
2nd Approach
Set up the pagination with PHP, make a query via ajax for each page? however I'm afraid that this approach would not allow me to filter out the table if I need to search for a record that is not on the current page.
1st approach: definitely not, loading large number of results for nothing is not recommended.
2nd approach makes more sense. You can use the LIMIT statement inside your SELECT statement to decide which records you want. Ex. if you paginate on 10 elements perpage, you could do
SELECT * FROM Table LIMIT 10
then
SELECT * FROM Table LIMIT 10,10
and so on. Indexes start at 0.
Note that you don't even need Ajax to do that, your next button can specify the offset for the next load of the page. It's a choice based on your knowledge, the size of the rest of the page (minimize load time), ...

MySQL - ListMenus/Comboboxes

I am trying to build a dynamic set of comboboxes/listMenus getting data from a MySQL DB. My database has 5 fields, 1st being id and
topic, sub_topic, info and url
I want to make it so that until user selects a valid choice from box1 that the others are disabled. Once user selects from box 1 box 2 will be activated. Once you make a selection from box 2 then the info and url will be shown.
I have followed a tutorial http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html and so most of this code is not mine apart from the SELECT statements
I am having problems writing the MySQL for update.php as this populates the other boxes (currently I am sticking with the comboboxes until I have it working.)
I would be grateful for some help, due to the amount of code it can be seen here http://pastebin.com/QNbHR9JK
Thanks in advance.
The first thing I see is that in update.php query, you aren't actually using a where clause. When you execute the prepared query, you pass in a value array, but there aren't any placeholders in the prepared query.
I would expect something like:
$sql = "SELECT `topic`,`sub_topic`,`info`,`url`
FROM `links` WHERE sub_topic=?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
One other thing I notice is that in your foreach in update.php, you are using $row['id'] but you aren't selecting that column in your query.
EDIT
I updated the query to use the proper column in where clause, and removed to group by clause based on discussion.

PHP MySQL advanced filtering

For a new version of a website, I am making a "Top User" section on the homepage. This allows people to vote for the user on a bunch of different categories. All this information is stored in a MySQL database in two main tables. One table has the information(id*autogenerated*, Username, Date added, etc.) and the other has the rates (id*autogenerated*, linkID, rowAvg, avg, avg2, etc.). The linkID from the rate table corresponds to the id from the information table. How the query works is it queries through the rate_table, orders it by highest averages then selects the first 10 results. Then using the linkID of that row, I select the actual information for that user from the info_table. This is fine and dandy as long as each user only has 1 rate. What happens when a user has 2 or more rates, and both of the rates are positive, is the query selects both of those and pulls the information for each of the 2 rows which is then displayed as two different users even though it is the same person. How can I make the rate_table query know when there are multiple rates for the same linkID and average them together instead of showing them as two different people. I was thinking of inserting each linkID into an array, then for each subsequently selected row, check if that linkID is already in the array. If not, insert it, if it is, then average them together and store it in the array and use the array to populate the table on the homepage. I feel like I am overthinking this. Sorry if this is a little confusing. If you need more information, let me know.
P.S. I'm still learning my way around MySQL queries so I apologize if I am going about this the completely wrong way and you spent the last few minutes trying to understand what I was saying :P
P.P.S. I know I shouldn't be using MySQL_Query anymore, and should be doing prepared statements. I want to master MySQL queries because that is what FMDB databases for iOS use then I will move onto learning prepared statements.
Take a look at some of the MySQL Aggregate Functions.
AVG() may be what you're looking for. The average of one result is just that result, so that should still work. Use the GROUP BY clause on the column that should be unique in order to run the aggregate calculation on the grouped rows.

Dynamic content without multiple pages

Let me start by saying i am new to mysql and php, and I'm sure this is a noob question but I've been searching google and can't find any solution.
Basically I want to create 1 template file that will read all of a table from a database with multiple rows and columns but only display one row at a time.
An example would be http://www.w3schools.com/php/php_mysql_select.asp scroll towards the bottom where it shows peter griffen and glen quagmire i would want it to only display 'glen quagmire' or only display 'peter griffen' depending on which link was previously clicked.
would i need to somehow assign an ID to the link url so php knew which row to parse etc.. ?
One straightforward way is to use the query string. Make the link <a href='stuff.php?id=1'>View #1</a>. Then use a where id='$id' clause in the SQL query, setting $id equal to the query string parameter $_GET['id'].

How to make an SQL query based on some rules

I've got this HTML form where I have multiple input elements: text, radio, and so on. These are intended to be options, conditional items to apply in an SQL query in order to pull more specific data from a database.
For example, the first input field is a textbox, the second a radio button, and the third a SELECT with two options. With the first, I would add a LIKE %name% sentence in the SQL query. The second is a radio button group with, let's say, a color, so I would add a WHERE color = $item comparing the one chosen with the database column. The third would pretty much be just like the second.
Now, I guess I could just use if sentences comparing the three items, in order to know which one to add to the SQL query, but my question is: is there a smarter way to do it? Like an array checking if those variables are set (I'm still using an if here, so nevermind).
I program simple things from time to time, since I've never done anything significantly complex, but sometimes, even for simple things, no matter how hard I strive to design something, I just can't.
In this case, I really can't figure (imagine, visualize) how would I structure the PHP code along with the SQL query, in order to add the these three conditions to the WHERE clause.
I'd greatly appreciate if you can help me out here. If you need more details, just let me know.
You can just build your sql statement as you go.
A simple example:
$sql = "SELECT ... WHERE 1=1"; // 1=1 is just an example to get the WHERE out of the way
if (first condition / certain $_POST variable is set)
{
$sql .= " AND LIKE %...%";
}
if (second condition)
{
$sql .= " AND something=...";
}
// etc.
// run query
Just for adding another solution, I can suggest you using stored procedure.
http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspx
http://www.brainbell.com/tutorials/MySQL/Using_Stored_Procedures.htm
You'll just need to pass values to a sp and generate where condition inside it.
There's another option to generate parameterized query in PHP to prevent SQL Injections.
Here are some links on this topic.
http://us2.php.net/manual/en/security.database.php
http://www.roscripts.com/PHP_MySQL_by_examples-193.html
http://www.webmasterworld.com/php/3110596.htm
http://am.php.net/mysql_real_escape_string

Categories