Not able to copy data from one table to another - javascript

I have two tables: trade and user_pokemon_db
I want to copy a specific rows from user_pokemon_db, when an event occurs.
Html code:
echo "<a href='tradecenter.php' onClick='document.write(".trade($db_id).")' >Put in Trade</a>";
When the user clicks on the link, the php function is called which consists on sql query to copy the row.
$sql = " INSERT INTO trade (trade_id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
SELECT (id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
FROM user_pokemon_db WHERE user_id = '".$id."' AND id = '".$db_id."' ";
Problem maybe due to improper writting of the query.. or maybe due to improper formatting of the href!??
What should I do?

I don't know the content of your php function trade() but it seems that you are confusing javascript and PHP.
Keep in mind that in most of case, once the web page is sent to the user browser, the PHP execution is finished. If you want to do a SQL request after a link click, you need to load a new page or to use something like Ajax to run some PHP code again.
The simplest way to do what you want is to pass the pokemon id as a GET variable (= in the URL)
and check this variable on another page and generate the good SQL query :
echo '<a href="trade.php?pokemon_id='.$id.'" >Trade </a>' ;
And the trade.php would do something like that :
$id = $_GET['pokemon_id'] ; // Be Aware of SQL Injections !!
trade($id);
Have a look at this page for more information about forms : http://www.w3schools.com/php/php_forms.asp
( And if you are using GET or POST variables in your SQL query, be aware of SQL Injections )
If you want to run your PHP function without reloading the page, you should use AJAX. Check this page to understand how it works. A very easy way to use it is to use jQuery

Related

Check if a $_SESSION variable is set from Javascript

I'm building a message system to learn how it works, and I've already got
pretty much everything. I can log in and make a post on a board, but now I would like to be able to edit it. The back-end is ready, it receives a POST request
Basically what I need to do is check if the currently logged in user is the author of a certain post from Javascript to show or hide the edit button. I know how to tell if the user is logged in from PHP so that it blocks requests if you aren't the author, but I can't hide or show the buttons as the posts are dinamically generated from a <template> using JS.
Login snippet:
$_SESSION["userid"] = $userid;
Edit check PHP snippet (kinda pseudo-code):
if ($_POST["action"] == "modifypost" && isset($_POST["postid"]) && isset($_POST["content"]))
{
$post = get_post($_POST["postid"]);
if ($post.userid != $_SESSION["userid"])
{
die("you are not allowed");
}
//MySQL queries
}
Post dynamic generation (abbreviated):
function add_post(post) {
var t = document.querySelector('#historypost');
t.content.querySelector(".content").innerHTML = post.content;
var clone = document.importNode(t.content, true);
document.body.appendChild(clone);
}
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>, but then the user would be able to manually set that variable from the console and show the buttons.
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>
Yes, this is one correct approach. Basically, use PHP to tell JavaScript which posts actually belong to the current user.
but then the user would be able to manually set that variable from the console and show the buttons
True. There is no way to secure information from user-meddling once you've sent it to the browser. This is because the user is in control of what gets executed in the browser. Instead of thinking of the button visibility as a security feature, think of it as a convenience -- something to make the user experience more pleasing.
Application security is really enforced on the server. Just make sure that one user is not allowed to edit another user's posts, and do not trust what comes from the browser. Verify inputs.
Ideally, I would prefer to put the post rendering logic inside the server-side.
But as your solution is focused in javascript, an option makes PHP render a javascript variable that tells if the user is the post author.
Example:
Inside your PHP file, in the HTML render part you can do this:
<script>var isAuthor = '<?php echo ($post.userid == $_SESSION["userid"])'; ?></script>
Doing this you will have javascript script variable called isAuthor, that will have value "1" is the user is the author.
-
But as I said, this doesn't look like a good approach to solve the problem. It's something that PHP can handle better, without expose your logic to the client.

Multiple choice list to PHP request

I have this datatable which gets its data from a server. The problem now is that the database contains a bit more data than i first imagined it would. So for keeping the browser from loading all entries i've created a multiple select list that I will use for only pulling out the essential information.
The input from this list is then matched with what's in the database. The result of that is then stored in $results as can be seen below.
The problem here is that i have no idea how to get the input data, especially if its multiple choice, to go in to the last mysql query which then go into $results.
Later on I use $results for pushing out data to a table. Though as i said it gets a bit crowded in the table when i load all my data into $results.
Everything else is working properly and I get my scopeIDs in my multiple select list.
So, how do I get my selected option/s to go in to
<?php
$results = mysql_query("SELECT * FROM tableID LIKE (/*some cool way of putting the input here*/)";
?>
Complete Code for the task:
///Connection parameters above///
$multiplechoice = mysql_query("SELECT scopeId FROM tableID");
$storeArray = array();
print"<select multiple name=\"scopeValues\" id=\"scopeIdchoice\">";
while ($rowchoice = mysql_fetch_array($multiplechoice, MYSQL_ASSOC)) {
$storeArray = $rowchoice['scopeId'];
print"<option id='".strtolower($storeArray)."'>";
print $storeArray;
print"</option>";
}
<?php
$results = mysql_query("SELECT * FROM tableID LIKE (/*some cool way of putting the input here*/)";
?>
Change the name of the select to scopeValues[].
From the select you will get an array of values in the $_POST array. You might pass that as a list of values to the SQL query like below. You need to adopt the xx_thefield_xxto the proper column name and of course need to do checks against SQL-injection, which are missing for better reading over here.
<?php
$scopeVals = $_POST['scopeValues[]'];
// … remember to sanitize $scopeVals before the next step
$results = mysql_query("SELECT * FROM tableID where xx_thefield_xx in ('" .
implode("','", $scopeVals) . "');";
?>
Because there is more than one value associated with a input now you need to tell the server to store all values in a array (notice the brackets):
name=\"scopeValues[]\"
Then you implode the array and run the SQL. I'll assume that you're POSTing the form data:
$scopeValues = implode(',', $_POST['scopeValues']);
// … remember to sanitize $scopeValues before the query
$results = mysql_query("SELECT * FROM tableID WHERE scopeId IN ($scopeValues) )";
Make sure to sanitize all the values in $scopeValues before interpolating them into the query to protect against SQL Injection. A more secure way would be not to use ext/mysql (it's deprecated anyway) and use PDO or ext/mysqli and use prepared statements.
(Are the IDs strings?)
I don't know if you knew this, but PHP is executed on the server. Requesting your pages goes as follows:
A browser sends a request to your server;
The server executes the PHP;
The server sends the output to the browser;
The browser renders the HTML.
This poses a problem: if you change your selection (which happens in the browser), the PHP has already been executed. It can't magically change its output that got sent to the browser. So to refresh the result, you should make a form and POST the input to the same page, which would check if data had been posted, if it had, output only the selected data, if it hadn't, show everything. If you want to make it a bit more complicated (but more usable too), you could use AJAX to retrieve the results of the select query.
The other answers covered the form already, the AJAX way would be like this:
Have a separate page which SELECTs the data using the POSTed input to filter.
Make an AJAX request (on the page that displays the data) every time the <select> changes.
(Maybe this answer is totally useless to you because you already knew PHP is server-side.)

how to fetch the current user data in phpfox

Topic: Fetch current user(some particular fields) data from the DB and display it on the Welcome Screen.
Explaination of UI : On the Registration Page, A dropdown would appear. As the user selects an option, it would trigger an event to fetch user image to show on the welcome page.
I have put following code in (pages.process) module
function getUserId($iUserId)
{
$aRows = $this->database()->select('p.image_path')->from($this->_sTable, 'p')
->Join(Phpfox::getT('user') , 'u', ' p.page_id = u.college_name') ->
where('u.college_name = p.page_id AND u.user_id = ' .
(int)$iUserId)->execute('getRows');
return $aRows;
}
The data will selected from User & Pages Table, and will be used to show the user image. Please suggest.
There is a service to get user details by is
$user_id = Phpfox::getUserId();
$aRow = Phpfox::getService('user')->getUser($user_id);
This will give you user details
For performance, check if the page you are altering already has the information you need, maybe you dont need to query the database in ajax if the page, when being created, already has that info and you can store it in javascript.
Since you mentioned an ajax situation (trigger an event on drop down to query the database), then you need to include a JS file (my suggestion since you can do this from a plugin), there are other ways but this is the best in my opinion.
Please read my article about plugins if you need help with writing one. My suggestion is to write a plugin to include your JS file in the page.
In the JS file you can call a "controller function" like this:
$.ajaxCall('mymodule.myfunction', 'param1=value1&param2=value2');
this would run the function "myfunction" in the file /module/mymodule/include/component/ajax/ajax.class.php
From this ajax file you can call "service functions" and send code to the browser, for example:
$value = Phpfox::getService('mmodule')->someOtherFunction();
$this->call('alert("' . $value . '");');
Hope it helps

Creating dynamic order basket using php javascript

I am creating an ePos system, that adds any item user clicks to the basket and calculate the total in the end all done without total page refresh.
I tried using $_SESSION and storing as order ( [item] => [price] ) but failed, as i need to refresh.
what I need is:
to display added Items [id name Qnty price]
calculate total price of added items.
please advice me on the best method to do this.
thanks
this is what I attempter in javascript
function addItem(name, price, id)
{
var table=document.getElementById("basket");
var row=table.insertRow(-1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
cell1.innerHTML=name;
cell2.innerHTML=1;
cell3.innerHTML=price;
}
but my issue was, i could not find a way to add decimals, parseFloat made alot of bugs for me
You should not need to refresh the page in order to save information into the PHP Session object. PHP Session information is stored on the server, so you can do an asynchronous HTTP request to the backend, and store information the PHP Session. I would suggest using the jQuery.ajax function (http://api.jquery.com/jQuery.ajax/) to do your async HTTP requests. If you are not familiar with jQuery, I highly suggest you get familiar with it. I also suggest you look into how AJAX works.
Also, if you are using the PHP session, if you are not using some kind of framework which does session management, you must make sure to call session_start() before using the $_SESSION variable.

jump out of a JS variable encapsulation

I'm reading a boook on XSS attacks, and I've found an example about XSS filter evasion that is a little weird (IMHO).
This is the example text:
Another possible injection point that could exist is when the developer uses unsanitized
user input as part of the generated HTML within a script element. For example:
<script>
var query_string="<XSS>";
somefunction(query_string);
function somefunction {
...
}
</script>
It appears we have access to the inside of the JavaScript function. Let’s try adding some
quotes and see if we can jump out of the encapsulation:
<script>
var query_string="”<XSS>";
somefunction(query_string);
function somefunction {
...
}
<script>
It worked, and also caused a JavaScript error in the process as shown in Figure 3.38.
Let’s try one more time, but instead of trying to inject HTML, let’s use straight
JavaScript. Because we are in a script tag anyway, why not use it to our advantage?
<script>
var query_string="”;alert(“XSS”);//";
somefunction(query_string);
function somefunction {
...
}
</script>
the bold text is what I suppose to be the user input, taken for example from a form.
Back to my question: is there any way that this kind of attack works? For example, suppose somefunction(query_string) is used to run some sql query, and query_string is a product name to search within the database. If inside the search function I create sql_query = 'SELECT name FROM table WHERE name = "'+query_string+'"';, I think there's no way to inject some string with quotes to "jump out of the encapsulation", i.e inputting YAY";alert('hi');// will not change the JS to this:
var query_string = [user input, in this case YAY";alert('hi');//]
function abc(query_string){
sql_query = "select name FROM table WHERE name = 'YAY';
alert('hi');//
....
}
Am I wrong? What do you think? Can you make me a simple example (if it possible) on how this kind of attack can make some sort of damages?
I thought about something like an online shop, but assuming the JS is not used on server side, the only thing this attack can do is modify the query string and then submit it to the server..
Hope you can understand what I wrote and what I'd like to understand, thanks, best regards.
You should only look at the first line. The rest doesn't come into play in this xss example. It's a badly chosen example. So take this much simple example
var first_name="<XSS>";
In this example <xss> is user generated content. So your e.g. php code looks like this
var first_name="<? echo $firstName; ?>";
$firstName is taken from some database or something else, and was generated by the user who typed it into some textfield. Say the user typed: ";alert("XSS");//. PHP will generate the following code
var first_name="";alert("XSS");//";
Pretty printed:
var first_name="";
alert("XSS");
//";
As you see the user was able to run his code alert("XSS") in every other users browser that visited the page. In this example nothing bad will happen except some alert box, but the user might inject some code that gets the cookie info and sends it to some server, so the attacker can steal someone's login session.
This same problem - forgetting to escape user generated content - also applies for creating sql queries, but this isn't related to this example. The creator of this example should have used query_string in his example, as it is obviously confusing.

Categories

Resources