PHP MySQL string showing up as an integer - php

I have a field called 'score' in a database table that an ajax call is adding values to.
The query below causes it to add values of 1 and 2 under 'score'. It should be looking for "$usrscore1" and "$usrscore2" in my ajax call but it seems to just see the integers (1 and 2) in $us and incorrectly post them as the values under 'score'.
for ( $counter4 = 1; $counter4 <= 2; $counter4 += 1) {
$mess4 = $messages + $counter4;
$us = $usrscore + $counter4;
mysql_query("INSERT INTO messages" . $counter4 . " (`score`)
VALUES ($us)",$dbconn);
}
If I change:
$us = $usrscore + $counter4;
to
$us = $usrscore1;
it correctly looks for $usrscore1 in my ajax call and puts the correct value in the database field under 'score'. But I need it to work in the for loop so just writing it out as $usrscore1 won't work, even though it reads it correctly that way.
Just in case it helps to see it, here's what the ajax call looks like:
$('#rateplugin' + instance).raty({
half: true,
start: totalavgRounded,
click: function(score){
$.ajax({
type: 'POST',
url: 'backend.php',
data: "usrscore"+instance+"="+score+"&action=postmsg",
success: function(xml) {
$.fn.raty.readOnly(true,'#rateplugin' + instance);
}
});
return false;
} // end click
}); // rat
Update:
I may have not been very clear. I set the loop up to only make 2 database tables, but I did that really just for testing purposes. In reality, once this is live, there could be thousands of these to create which is why I'm doing it with a loop. Would the URL variable still be a good solution here? I'm not exactly sure how I would implement it.
My main point of absolute confusion here is that that no matter how I broke up the variable integer from $usrscore it would always ignore the $usrscore part and only see the integer and then just use that as the final value which will always be wrong. Is there something weird about the VALUE MySQL bit that does this? Does anyone have any ideas as to why it is doing that and how to get around it? If that URL variable idea might work, could you please give me some direction into its application here?

from what i can see, you only have limited $usrscore1 and $usrscore2. i suggest you put a single variable $usrscore and populate it based on the parameter in the url.

Related

delete checked table rows with ajax

I have checked through numerous questions to find the solution. I know I'm close, but I'm still not getting anything happening with my deleteData.php after confirming to delete.
Status:
Testing the array provides successful result.
Example: I checked rows 1, 2 & 31...then press #btn_del.
First, I get the confirm "Are you sure...?"
Next, I see the correct alert(array) 1,2,31
The next step...ajax is supposed to be sending this array data to deleteData.php for processing.
script
$('a#btn_del').click(function(e) {
e.preventDefault();
page = $(this).attr("href");
ids = new Array()
a = 0;
$(".chk:checked").each(function(){
ids[a] = $(this).val();
a++;
})
// alert(ids);
if (confirm("Are you sure you want to delete these courses?")) {
$.ajax({
url : 'deleteData.php',
data : ids,
type : "POST",
//dataType : 'json',
success : function(res) {
if ( res == 1 ) {
$(".chk:checked").each(function() {
$(this).parent().parent().remove();
}) // end if then remove table row
} // end success response function
} // end ajax
}) // end confirmed
}
return false;
}); // end button click function
}); // end doc ready
deleteData.php
<?php
require_once('config.php'); // Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.'.$dbc);
foreach ($_POST['ids']
as $id) {
$sql = "DELETE FROM unit_genData
WHERE unit_id='" . $id . "'";
$result = mysqli_query($sql)
or die(mysqli_error($dbc));
} // end echo result count
mysqli_close($dbc); // close MySQL
echo json_encode(1);
?>
Edited:
Updated GET to POST.
Updated data: 'ids' to data: ids
Tested:
a) In php...echo $_POST['ids'];
NO RESULT
b) In js...commented out the if(confirm...
NO RESULT
Status:
Looks like the AJAX isn't firing (so to speak)
First of all, I would use POST instead of GET for a delete.
Then you need to send the correct data to your php script. What you have now is just a string, no key-value pairs which is what you expect at the backend.
The easiest way to send your data would be to use something like (assuming you have a form):
data: $('form').serialize(),
but you can also send an array like the one you are building:
data: ids,
The advantage of the first method is that values automatically get escaped / encoded (wouldn't make a difference with just integers obviously...).
At the backend you would need to prevent the sql injection problem you have now. You can do that using a prepared statement with bound parameters or in the case of numeric ID's you can cast them to integers.
Edit: As noted in the comments by #Fred-ii-, additional spaces in a string will cause your condition to fail. I would recommend a prepared statement but if you decide to cast to int and use that, just remove the quotes.
Also note that the procedural mysqli_* functions take the database link as the first parameter, that applies both to the query and to the error handling.

PHP/JQuery: Posting to a PHP Script then returning the values and updating HTML with JQuery

I'm fairly new to PHP and really new to JQuery.
So I writ some JQuery that does some calculations, I writ something below that is similar:
//on change of a selectbox with the class item
$('.item').change(function() {
// set variable id as the id name of this id
var id = this.id;
// price variable is equal to the value of the element id 'hiddenprice'
price = $("#hiddenprice").val();
// number of items is the value of the select box
numberofitems = $(this).val();
// number of days is equal to a php variable I set on the page
numofdays = "<?php echo $length->days; ?>";
//totalprice is equal to the 'price' multiplied by 'numofdays'
totalprice = Number(price) * Number(numofdays);
//calculates final total by multiplying the 'totalprice' by 'numofitems'
finaltotal = Number(totalprice ) * Number(numofitems);
//updates the HTML with the new price
$('#'+id).html("€" + finaltotal.toFixed(2));
});
I was trying this and although I got it to work, after reading up some I am aware that because this script is in my footer of the page that is getting updated, it is unsafe and easy to manipulate if a user wanted to be malicious.
So I want to do the calculations server side, by posting values to a PHP script and then returning the values.
// POST values to PHP Script
$id = (posted select id);
$price = (#hiddenprice variable value);
$numofitems = (posted value of the select);
$numofdays = $length->days;
$totalprice = (int)$price * (int)$numofdays;
$finaltotal = (int)$totalprice * (int)numofitems;
//Then push $finaltotal and $id back to the user viewed page
$('#'+<?php echo $id; ?>).html("€" + <?php echo $finaltotal; ?>.toFixed(2));
I'm just not sure how to push them to the page without refresh and then return them, also without refresh.
Again, sorry if this is simple, I have looked at JQuery form plugins, I just wondered if there is more apt solution for what I would like to do.
Thanks in advance.
You may want to check out ajax, it can post or get data without refreshing the page. Also the answer of this question may be helpful too.
You need to use AJAX. This sends data to the server and allows you to execute a callback once you receive a response.
If you are using jQuery, then read up about the $.ajax method.
To handle the response, the easiest data type to use is JSON.
So a quick example
Javascript
$.ajax({
url: calculation_url.php,
method: 'post',
dataType: 'JSON',
data: {price: price, days: numofdays },
success: function(response) {
// you should check a valid response was received
$("#result").html(response.html);
}
});
PHP - calculatin_url.php
$price = $_POST['price'];
$days = $_POST['days'];
// do calculations
// send data back as json
die(json_encode(array('html' => $finalTotal)));
To start this process you will need to attach events to the calculation button. Read about registering events with the on method and you may find it helpful to read about the event.preventDefault() method.

javascript if checkbox is checked, href to ?page2, if at ?page2: keep cb checked, when unchecked, href to ?page1

Im totally new to javascript and i have no clue how to get this to work... I modified the code a little, but note that line 6 makes no sense. That is the main reason for this post.
<script>
function checkReloading() {
if (window.location.href.split=="?showpastdate") {
document.getElementById("showpastdate").checked=true;
} else {
document.getElementById("showpastdate").checked=false;
}
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
} else {
window.location.replace("");
}
}
window.onload=checkReloading;
</script>
Ok i think this is pretty readable.
First of all window.location.href.split doesn't work because I have to give in the full path. But how can I make this dynamic, so it can be used on more websites? Everywhere I see: window.location.protocol + "//" + window.location.host + "/" + window.location.pathname; but how do I implement this line of code for dynamic webpages? Can someone give me an example?
What I want to achieve with this code is:
When showpastdate is checked, href to ?showpastdate, when at ?showpastdate stay checked so i can use php $_GET on ?showpastdate. This works (when i use static full url). But than...
How do I have to modify this code so that the checkbox remains checked at ?showpastdate untill clicked again, than url goes back to original .php state or other GET var?
Sorry for asking for code writing, but I bet some of u can write this simple lines in 2 minutes while I'm surfing around for 8 hours. Not about to learn javascript, but this really would be a nice option for my program to toggle item showing past date ON/OFF, nicer than having 2 checkboxes, 1 for ON and 1 for OFF :x EDIT: + a submit button #(O _o)#
Thanx in advance.
.split() is a function you can execute on a string object, to split it up in pieces, depending on a parameter provided:
"abcdefg|hijklmnop|qrstuvw".split('|')
would result in a array like this:
["abcdefg","hijklmnop","qrstuvw"]
Now, I am guessing you have added a "?showpastdate" parameter to the url, to change a checkbox's "checked" status.
The easiest way to do that would be:
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
This part: window.location.href.indexOf("?showpastdate") Searches the href for
"?showpastdate"
If the string has been found, it will return a index. if not, it will return -1.
The squiggly in front of it is to convert the -1 or 0 (or higher) to a true / false.
I'm not quite sure what the toggleAutoRefresh() is supposed to do, though
Edit 1
Ah, for the toggleAutoRefresh(), just add this:
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}
instead of that if-else block you have there.
The .replace() function works on a string the same way .split() does. It takes 2 arguments: What to look for, and what to replace it with.
So, for example:
var someString = "words and stuff"
var result = someString.replace(" ","_");
//result will be "words_and_stuff"
Edit 2
These functions should work:
function checkReloading() {
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}else{
window.location.href += "?showpastdate";
}
}
Where are you calling toggleAutoRefresh() from?
Edit 3
What I can conclude from your last comment, is that you want to do something like this:
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && ~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
Note the use of the "~" in front of the indexOf.
If string.indexOf("text") finds "text" at the beginning of a string, like it would in "tekstbooks bla bla bla", it returns 0. First index, starting count at 0.
This zero is interpreted as a false, when implicitly casting it to a boolean. So, if the indexOf were to find a result at the first index, it should (In this situation) return true to indicate a string has been found. That's why we apply the Bitwise NOT ~ to the results of indexOf. -1, indexOf's "Not found" value returns false, and all other results return true.
URL Change Event - JavaScript
http://help.dottoro.com/ljgggdjt.php
I think you could also use the onchange() javascript event.
I'll explain a little bit more.
I have a JQuery datatable, and through CSS I have different <tr classes>. Depending on the information stored in the database, these <tr> get a different class, thus a different color in the datatable.
Now for one <tr class> I'd like to give the user the option to hide/show. I was thinking to do this with a checkbox, and the javascript would parse an url when checked, and remove it when unchecked again. This URL can be used for php to run different queries, if $_GET['parsedurl']: query to show all tables, elseif $_GET['empty']: query for not showing that 1 information.
But this is the worst way to do it. I need to find something to toggle the display: none on or off of the table class, since this is working client-side.
So Im now thinking to keep the parsing of the javascript in an URL and depending on the URL, I run the .php GET to echo out <tr style: display: none> or just simply <tr>
Therefore I need some javascript which does this:
If checkbox is checked, redirect to projectlist.php?showpastdate
When URL = projectlist.php?showpastdate, make checkbox checked.
When URL = projectlist.php?showpastdate and checkbox gets unchecked, redirect to projectlist.php, where the checkbox is unchecked.
I think these triggers are the best options?
With .PHP I'll do:
if (isset($_GET['showpastdate']))
{
<tr style: display: none>
}
else
{
<tr>
}
Maybe someone has an even better solution? I'd like to hear!
Thanks.
EDIT
The javascript I now have is:
<script>
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
}
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && !~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
}
</script>
After checking the checkbox, it goes to the page projectlist.php?showpastdate and gets unchecked there. When checking again, it goes to projectlist.php?showpastdate?showpastdate. It should remove the ?showpastdate, not add another.
This is could do with PHP too, but I really don´t like a submit button for this checkbox. Just check and execute.
Okay. I got it.
<script>
function toggleAutoRefresh(cb) {
if (~window.location.href.indexOf("?hidepastdate") == 0){
window.location.replace("?hidepastdate");
document.getElementById("showpastdate").checked == true;
}
if (~window.location.href.indexOf("?showpastdate") == 0){
window.location.replace("?showpastdate");
document.getElementById("showpastdate").checked == true;
}
}
</script>
Now the URL gets toggled every time at clicking and PHP does the CSS display work.
Thanks for the effort and for pointing me to the right direction, Cerbrus! Saved me alot of time.

PHP / jQuery based school project

I'm developing a parents evening booking system as part of my A level programming project, but I've just gotten stuck.
I'll try explain the project the best I can in this post, so I can give you guys a clear picture of what the application does.
So far:
I have created a sort of language selector function with php, which gets the users language selection before logging in based upon a cookie. Here's the code for the script (Yes, very messy right now, but i'll fix it later on):
function check_language() {
//directory name for the custom defined languages.
$dir = 'languages';
//set a default language
$default = 'english';
//make sure that we have a language selected...
if (!isset($_COOKIE["lang"])){
//if there is no cookie set, set one.
setcookie("lang", "english", time()+3600*24*365);
}else{
$lang = ($_COOKIE["lang"]);
}
//build the path string.
$path = $dir."/".$lang.".php";
if (file_exists($path)) {
//return the selected language pack directory.
return $path;
}else{
//protect the server, by returning the default language path...
return $dir."/".$default.".php";
}
}
Whenever I want my PHP script to access language files, I call the function I have created and then include the language file on the page like so:
$lang = check_language();
include_once($lang);
english.php file...
$txt['languagename'] = "English";
//text for the index page...
$txt['titletext'] = 'Parents evening booking system';
$txt['welcometext1'] = 'Welcome to the parents evening booking system for ';
welsh.php file...
$txt['languagename'] = "Cymraeg";
//text am y tudalen index...
$txt['titletext'] = 'System bwcio noson rhieni';
$txt['welcometext1'] = 'Croeso i system bwcio noson rhieni ';
So for example, if the users cookie contains 'welsh', the file welsh.php would be included, and I would have access to an associative array ($txt), with the supplied translations.
That part of my script works perfectly so far.
Now i'm coding the admin page, and I need an option to be able to add a school year to the database through the admin panel.
This is where i'm a bit confused on what to do, as the string ('year 10' for example) would be 'blwyddyn 10' in welsh. So this means I would need to add another element to the associate array for all language files with a string for the required language so it could be accessed in the script. (if this makes any sense at all).
I have created a table in the database for all languages like so:
languageid name filename
1 English english.php
2 Welsh welsh.php
Then I wrote this code to connect to the database and create an input box for each language in the database, along with a "translation id key" input box.
include'/inc/functions.php');
ConnectToDB();
$query = "SELECT * FROM languages WHERE 1";
$result = mysql_query($query);
$languages = array();
while($row = mysql_fetch_assoc($result)){
$languages[] = $row['name'];
}
echo 'Translation key id: <input type="text" name="languagetermkey"/>';
echo '</br>';
foreach($languages as $item){
echo 'Year name ('.$item. " string):";
echo '<input type="text" name="'.$item.'String'.'"/>'; //e.g "EnglishString"
echo "</br>";
}
Now if I wanted to add the terms above (the text from both input boxes) into my language files ("english.php" and "welsh.php") how would I go about sending an array with an ajax post request?
Previously I have been using this code, but I guess it won't work for what I want to do this time :(
$.ajax({
type: 'post',
url: 'add_class.php',
data: 'classname=' + "test",
error: function(){
alert('There was a problem adding the class !');
},
success: function() {
alert("Class has been added successfuly");
}
});
Is this the right way to go about doing this sort of thing ? If not, can somebody guide me towards the right direction on what to do? i'm just a bit confused and this is my first time using jQuery.
I know this post is long, and I do appreciate people's efforts for reading the whole thing.
Thanks in advance for any replies (Y)
For the bit about sending the array with AJAX, you can serialize a form and pass that, meaning you can access it just as if it was a normal POST from PHP.
$.ajax({
type: 'post',
url: 'add_class.php',
data: $('#formID').serialize(),
error: function(){
alert('There was a problem adding the class !');
},
success: function() {
alert("Class has been added successfuly");
}
});
For the "Year 10", you can use sprintf or vsprintf like this - example showing both sprintf and vsprintf.
$year = 'Year %d';
$yearWelsh = 'Blwyddyn %d';
echo sprintf($year, 10) . ', or in Welsh, we say ' . vsprintf($yearWelsh, array(10));
If I understand correctly, you want to change the language cookie when a new language is selected. You can use jQuery to set this cookie and then load the page. Php can then select the right language file.
Of course there are numerous other ways to do the same thing. Hope this helps though.
$.ajax is a more complicated though valid method to send an ajax request via jquery. You are looking for something like this - jQuery getJSON or jQuery get. Scheme is the same:
$.get('{queryURL}, data, function(response) { /* do something with the response */ });
The data variable may be an array, object or string created by jQuery's form.serialize().

Strange POST data junk being returned

I'm writing a fairly basic commenting function for a site using post method to pass input values to a php file that performs the relevant mysql query.
The $.ajax part is as follows:
// AJAX URL ENCODING
$("#add").click(function() {
// POST COMMENT FORM VALUES
var ajaxOpts = {
type: "post",
url: "includes/addComment.php",
data: "&author=" + $("#author").find("input").val() + "&email=" + $("#email").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val() + "&parent=<?php echo $vid_id; ?>",
success: function(data) {
// IMMEDIATE DISPLAY
// Not relevant to this problem.
// CLEAR TEXTAREA FOR NEXT COMMENT
$("textarea").val('');
}
};
$.ajax(ajaxOpts);
});
This is passed through to addcomment.php:
require('connection.php');
//get POST data
$name = mysql_real_escape_string($_POST["author"]);
$email = strtolower(md5(trim(mysql_real_escape_string($_POST["email"]))));
$comment = mysql_real_escape_string($_POST["comment"]);
$time = Date ('c');
$parent = trim(mysql_real_escape_string($_POST["parent"]));
//add new comment to database
mysql_query("INSERT INTO comments VALUES(' $name ',' $email ',' $comment ', ' $time ', ' $parent ')");
Everything works fine except that the mysql_query doesn't end up inserting any values into my database. After a bit of digging I found this:
So i'm assuming my query isn't going ahead because the ' : ' bit of junk(?) data is throwing everything out?
I'm trying to figure out where this errant ' : ' has come from, anyone have any ideas?
P.S - Apologies for the length of this question, I've tried to narrow down possible culprits as much as I can.
You dont have to do that URI encoding yourself. Read the documentation of jquery, the 'data' to be sent could be a map/json.
http://api.jquery.com/jQuery.post/
change
data: "&author=" + $("#author").find("input").val() + "&email=" + $("#email").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val() + "&parent=<?php echo $vid_id; ?>"
into
{ author: 'something',email:'test' }
or more professionally
$("#testform").serialize() //here #("#testform") stands for a '<form>' tag
And try not to complicate the problem, start with some simple functions, use more echo() and alert() to debug.
what happens if you remove the & from the front of &author?
normally the first data field doesn't have an &
data: "&author="
also as others have mentioned this would be a welcome addition
or die (mysql_error())
and its usually good practice to name your database columns on the insert
otherwise you risk breaking the insert statement if you ever alter the table structure
insert into (colname1, colname2) values ('value1', 'value2')
you can print_r($_POST) to see if the colon is really there.
secondly, while debugging it wouldn't hurt to throw an
or die (mysql_error())
at the end of your query.
Without those two, it's hard to debug.
2 things :
ajaxOpts variable is out of scope , you will have a error ( ajaxOpts is not defined)
In you example, you miss }); at the end , you should check your JS validate too before checking your php script is working. If you have a JS error, the ajax call will not be called.

Categories