I am trying to learn html, php and all of that. So what im trying to do right now is, I have created a SQL database in phpmyadmin, it's just a name and an integer value like:
Nickname 20
Nickname 30
bank 10 and etc.
So what I want to do now is:
var textil= 20;
function displayImage(){
if (textil >= 2) {
var num = Math.floor(Math.random() * 21);
document.canvas.src = imagesArray[num];
textil=textil-2;
} else {
alert("Insufficient funds.");
}
}
This is what I did before, and it works now, but now comes the real problem for me because I have no idea how to do this, how do I deduct that "textil" value from the SQL database instead from a var.
like when i click, ofc onclick=displayimage(); it goes -2 on the textil value, but from SQL not this in html. Thank you!
Theres no way to access your SQL database directly from the browser.
You will probably need a Server which will access the SQL database.
After you have retrieved the data, there are two methods to feed this data to your webpage:
1) AJAX - the technology which drives the mordern web. Look it up and study it thoroughly
2) Use a programming language capable of generating HTML output. Access your data from SQL, and generate the relevant javascript based on it.
You mentioned you are learning php. Go a few chapters deep into it and you will get your answer.
Related
I want to get data from a database, to show on a page. There is a huge amount of rows in the table, so I'm using pages to avoid having to scroll forever.
I have functionnalities to search words (no specific columns), order by any column, and obviously change the page size and which page I am on.
I could, in theory, just ask the database for everything (SELECT * FROM myTable), send it to my html view, and work through the data entirely in javascript. The problem is, there is so much data that this is extremely slow using my structure (page controller calls my main logic, which calls a webservice, which calls the database), sometimes waiting up to 20 seconds for the original load of the page. After it's loaded, the javascript is usually fast.
Or, I could do most of that work in the controller, using Linq. I could also do the work in the webservice (it's mine), still in Linq. Or, I could straight away use WHERE, ORDER BY, COUNT, and a bunch of dynamic SQL requests so that I get instantly what I want from the database. But any of those forces me to refresh the page every time one of the parameters changes.
So I'm wondering about performance. For example, which is faster between:
var listObjects = ExecuteSQL("SELECT * FROM myTable");
return listObjects.Where(x => x.field == word).OrderBy(x => x.field);
and
var listObjects = ExecuteSQL("SELECT * FROM myTable WHERE field = :param1 ORDER BY field", word);
return listObjects;
And in what specific situations would using the different methods I've mentioned be better or worse?
No.
You want to do the work of selecting a block (pagefull) of data on your dataserver. That's it's job; it knows how to do it best.
So, forget the ExecuteSQL. You are pretty much shutting down everything's ability to help you. Try LINQ:
var page = (from m in MyTable
where m.field == param1
orderby m.field
select m)
.Skip((nPage-1)*pageLength).Take(pageLength);
That will generate the exact SQL to tell the Data Server to return just the rows you want.
i have read many things here about how to prevent SQL injection also on other website and forums. Only thing is thats it makes me really confused on the way how to protect your website when writing stuff to the database.
I'm creating as schol project something where there alot of input from the users wil be writte to the database, i'm currently check them by javascript if they contains iligal char. Then i use ajax to activate my controller, use the query in my model send it back to the view.
But lets go on on my problem.
If i validate a input first with javascript, (client-side), then server side with PHP. If i first check in php if the input contains iligal char like * '' `` > <, that kind of things. What you whould use in a query for geting information from the database. Then escape the whitescpases since i don't want to have things with spaces on the website as users input.
Then use mysqli_real_escape_string() on the input. Then send it to the query that will looks like this.
/**
* #param string
* #param string
* #return mixed
*/
public function updateUsername($oldUsername, $newUsername) {
return $this->_db->query("UPDATE `users` SET `username` = :new_username WHERE `username` = :old_username",
[':new_username' => $newUsername,':old_username' => $oldUsername]);
}
So
1 > Check using javascript
2 > Check by php on char like * < > ' #
3 > using mysqli_real_escape_string()
4 > To the PDO query
Is this a good way for prefending SQL injection, i really don't want to send my school project live in the air with SQL injection haha.
Greetz,
Also many thanks for reading my long story
No. Banning characters prevents people from using them and there are often valid reasons to use them. If it makes no sense for the characters to appear in the data, then you can filter them to help keep the data sane. Don't do it as a security measure.
Ditto
No. Parametrised queries are better.
Yes, but not in combination with mysqli_real_escape_string since you shouldn't mix APIs and if you used both you would double escape things and put \ characters in your data.
I have a database with roughly 1.2M names. I'm using Twitter's typeahead.js to remotely fetch the autocomplete suggestions when you type someone's name. In my local environment this takes roughly 1-2 seconds for the results to appear after you stop typing (the autocomplete doesn't appear while you are typing), and 2-5+ seconds on the deployed app on Heroku (using only 1 dyno).
I'm wondering if the reason why it only shows the suggestions after you stop typing (and a few seconds delay) is because my code isn't as optimized?
The script on the page:
<script type="text/javascript">
$(document).ready(function() {
$("#navPersonSearch").typeahead({
name: 'people',
remote: 'name_autocomplete/?q=%QUERY'
})
.keydown(function(e) {
if (e.keyCode === 13) {
$("form").trigger('submit');
}
});
});
</script>
The keydown snippet is because without it my form doesn't submit for some reason when pushing enter.
my django view:
def name_autocomplete(request):
query = request.GET.get('q','')
if(len(query) > 0):
results = Person.objects.filter(short__istartswith=query)
result_list = []
for item in results:
result_list.append(item.short)
else:
result_list = []
response_text = json.dumps(result_list, separators=(',',':'))
return HttpResponse(response_text, content_type="application/json")
The short field in my Person model is also indexed. Is there a way to improve the performance of my typeahead?
I don't think this is directly related Django, but I may be wrong. I can offer some generic advice for this kind of situations:
(My money is on #4 or #5 below).
1) What is an average "ping" from your machine to Heroku? If it's far, that's a little bit extra overhead. Not much, though. Certainly not much when compared to then 8-9 seconds you are referring to. The penalty will be larger with https, mind you.
2) Check the value of waitLimitFn and rateLimitWait in your remote dataset. Are they the default?
3) In all likelyhood, the problem is database/dataset related. First thing to check is how long it takes you to establish a connection to the database (do you use a connection pool?).
4) Second thing: how long it takes to run the query. My bet is on this point or the next. Add debug prints, or use NewRelic (even the free plan is OK). Have a look at the generated query and make sure it is indexed. Have your DB "explain" the execution plan for such a query and make it is uses the index.
5) Third thing: are the results large? If, for example, you specify "J" as the query, I imagine there will be lots of answers. Just getting them and streaming them to the client will take time. In such cases:
5.1) Specify a minLength for your dataset. Make it at least 3, if not 4.
5.2) Limit the result set that your DB query returns. Make it return no more than 10, say.
6) I am no Django expert, but make sure the way you use your model in Django doesn't make it load the entire table into memory first. Just sayin'.
HTH.
results = Person.objects.filter(short__istartswith=query)
result_list = []
for item in results:
result_list.append(item.short)
Probably not the only cause of your slowness but this horrible from a performance point of view: never loop over a django queryset. To assemble a list from a django queryset you should always use values_list. In this specific case:
results = Person.objects.filter(short__istartswith=query)
result_list = results.values_list('short', flat=True)
This way you are getting the single field you need straight from the db instead of: getting all the table row, creating a Person instance from it and finally reading the single attribute from it.
Nitzan covered a lot of the main points that would improve performance, but unlike him I think this might be directly related to Django (at at least, sever side).
A quick way to test this would be to update your name_autocomplete method to simply return 10 random generated strings in the format that Typeahead expects. (The reason we want them random is so that Typeahead's caching doesn't skew any results).
What I suspect you will see is that Typeahead is now running pretty quick and you should start seeing results appear as soon as your minLength of string has been typed.
If that is the case then we will need to into what could be slowing the query up, my Python skills are non-existent so I can't help you there sorry!
If that isn't the case then I would maybe consider doing some logging of when $('#navPersonSearch') calls typeahead:initialized and typeahead:opened to see if they bring up anything odd.
You can use django haystack, and your server side code would be roughly like:
def autocomplete(request):
sqs = SearchQuerySet().filter(content_auto=request.GET.get('q', ''))[:5] # or how many names you need
suggestions = [result.first_name for result in sqs]
# you have to configure typeahead how to process returned data, this is a simple example
data = json.dumps({'q': suggestions})
return HttpResponse(data, content_type='application/json')
Im customizing a payment gateway solution using php and jquery. Before i pass the data(ie. customer address, tele, amount of purchase, etc.), I want to deduct 2.9% from the purchase/product amount.(which would be my personal service fee) and then pass the remaining balance to the payment gateway for processing. How would i do this using PHP?
var $adjustedamount;
var $mypercentage = 0.029;
function computemypercentage($original_price){
$adjustedamount = ($original_price += ($original_price * $mypercentage));
return $adjustedamount;
}
document.getElementById("trueamount").innerHTML= computemypercentage(29.99);
As I stated in the comments already, please ensure ANY calculations about money are done on the server side. JavaScript is great for providing a better user experience, but not for critical business logic.
The reason for this is that it is simply too easy to modify those values. Pull up any modern browser and open the developer tools. You can change form values and JavaScript at will, making anything coming from the client untrustworthy by default.
As for assigning the value to some element... your code should work fine: http://jsfiddle.net/yPC3K/
I connect up to my DB and a user submit their email address. This is stored in the DB. This is something I have grabbed from a turorial.
I'd like a user-unique code generated through JS on document load..
Format should be 6 digits in length and only using only A-Z and 0-9. ie: F4DRB6
Once that is done I'd need to store that unique code for that user in the DB.
The generator should check if the unique code exists in the DB, to ensure it is actually unique.
The trouble I am having is; I don't know how to create the unique code in the above format, checking if it is unique from the DB, and then storing it in the DB corresponding to that user. I'd assume another column to match the row somehow?
Thanks!
EDIT: I have attempted with this.. if there is any error please do point it out. Thanks
function genRandomString() {
$length = 5;
$characters = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
do {
$random_string = $this->genRandomString();
} while (mysql_num_rows(mysql_query("SELECT referralcode FROM ".coming_soon_emails." WHERE rand_string='{$random_string}'")));
$q = "INSERT INTO ".coming_soon_emails." SET referralcode='{$random_string}'";
$result = mysql_query($q);
why you need that to be created in client-side? Why can't you just create the code when the client submits the "final" form?
You can create this code randomly and you put the column that handles the code as unique. If you get a violation error, you generate another and try again.
Well, this is one of the ways to do...
Its simple math,
6^36 is large enough that creating a random id is mostly unique.
If you wanna be 100% sure use AJAX to check the generated ID in database and recreate if existing.
In a causal way, a simple walk-through would be:
write a function/SP in mysql :
First, generate a random code, as AbiusX said, depends on your user pool size, the new code is probably rarely used.
This will generate one Hex character for you and should get you started.
SELECT conv(FLOOR((RAND() * 16)),10,16);
Then you will need to check if this code has been used already.
`
SELECT * FROM usertable where code =
generatedcode
if so, generate a new one.
In a more robust setting, I always pre-generate the unique codes, and store them in a table "unused code" etc, so I can just grab any code off there and ensure it is unique and not used.