简体   繁体   中英

Selecting SQL table column with Jquery - SQL injection?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM