Creating fusioncharts from database with variable where-condition - php

I'm creating FusionCharts with data from my database. It works if I set a static where-condition with a variable set in the code ($kommunenr = '3001';). But I would like the user of the website to choose which data the chart is based on, by inserting a number in a form field, i.e. 3018. So the value of the variable should come from the user's choice. But when I test the variable seems empty.
My code is based on these tutorials:
https://www.fusioncharts.com/dev/using-with-server-side-languages/tutorials/php-mysql-charts
https://www.youtube.com/watch?v=nqavhILvBVU
https://a1websitepro.com/jquery-ajax-form-submit-with-php-processing/2/
I have the following files:
valginfo.php (the main page)
skjema.js (get the data (the number) from the form on the main page)
chart_sample.php (lists the data from the database)
app.js (creates the chart)
I have tried to find the error by both posting the content from chart_sample.php in a div on the mainpage, and in an iframe. And of course googling.
My query in my chart-data.php (choosing the data to use in making the chart):
$query = "SELECT * FROM valg19_kommune WHERE kommunenr = $kommunenr AND kandidatnr = 1 ORDER BY kommunenr, sortering, kandidatnr LIMIT 500";
It works if the variable is static, set like this:
$kommunenr = '3001';
But when I set the variable like this, it looks empty:
$nr=$_POST['nr1'];
$kommunenr=$nr;
I expect the posted number to be stored as the value of the variable and beeing part of the query, but it is not. When I echo the query and the result from chart_sample.php into a div on the main page, I looks perfect:
SELECT * FROM valg19_kommune WHERE kommunenr = 3018 AND kandidatnr = 1 ORDER BY kommunenr, sortering, kandidatnr LIMIT 500
[{"label":"Fremskrittspartiet","value":"42","color":"#000099","tooltext":"Elisabeth Stene"},{"label":"H\u00f8yre","value":"64","color":"#3366ff","tooltext":"Benedicte Dyvik"},{"label":"Kristelig Folkeparti","value":"56","color":"#ffff00","tooltext":"Brynjar H\u00f8idebraaten"},{"label":"Senterpartiet","value":"45","color":"#00cc00","tooltext":"Reidar Kaabbel"},{"label":"Arbeiderpartiet","value":"44","color":"#ff3300","tooltext":"Kai Guttulsr\u00f8d"},{"label":"SV - Sosialistisk Venstreparti","value":"39","color":"#ff4d4d","tooltext":"Tore Andersen"},{"label":"R\u00f8dt","value":"37","color":"#cc0000","tooltext":"Martin Werner Olsen"}]
But in my iFrame this is displayed:
SELECT * FROM valg19_kommune WHERE kommunenr = AND kandidatnr = 1 ORDER BY kommunenr, sortering, kandidatnr LIMIT 500[]
The iframe content is not updated when I submit the number.
How can I make sure the chart is made based on the number entered by the user?
Before I enter a number in the form field
After I entered the number
If I set the variable as this $kommunenr = '3001'; and remove the echo og the query.

Now I feel really stupid! I should use sessions and globals!
Start each page with session_start(); and first set and then use the global variables:
$_SESSION["kommunenr"] = $kommunenr;
$kommunenr = $_SESSION["kommunenr"];

Related

How to pass query through an Ajax request

I'm working on paginating some data with Ajax requests. When one of the page number buttons is pressed it will send a request to a separate file to generate the next page in a table.
On my main page I'll have something like:
$query = "Select * from table WHERE field = 'something' LIMIT 5";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($result);
// dump results as table
When I write the script to create a new xmlhttp request object to my "paginate.php" file, how can I carry this same query over to the file since it may dynamically change based on user input?
I was thinking of just passing the whole query string as a function parameter via a POST request, but am wondering if there is a more efficient way of doing this.
I was thinking of just passing the whole query string as a function
parameter via a POST request
Definitely do not do this! It's really really bad security practice to let the browser (ie. user) run queries directly against your database. I made this mistake in early days and my site got 0wned in no time.
Your PHP file should accept parameters, validate them, then use them to run the query
1. You XHR object sends: page_number=5
2. Your PHP validates the input and dynamically builds the query:
//set page to 1 if none was provided.
$pg = isset($_POST['page_number'])? (int)$_POST['page_number']: 1;
$pg = max(1,$pg); // lowest allowed pg number is 1
Once you have the page number, and you are sure it's an integer (not some nefarious SQL command that a user sent to your server), you can use it in your query:
$size = 5; //# of results per page
$start = ($pg-1) * 5;
$query = "SELECT * from myTable WHERE field='something' LIMIT $start,$size";
Note that if the field value something comes from the user, you don't want to include it in the query directly (this goes for any user-supplied value). Instead, you should use prepared statements and parameterized queries
Resource: https://www.owasp.org/index.php/SQL_Injection

PHP Paging with HTML variables

I have been going through pagination tutorials for past 1 week. I have an html page wherein user enter values into the textfields and click submit button. The page then redirects to a php page which displays corresponding output from the sql database. The database makes use of variables which were received by the php script from the HTML page. I am trying to paginate the final table displayed on the php page but have been unable to do so. Relevant Code for the same is:
Search.html
ClOrdID
Symbol
**index.php**
<?php $clordid = $_POST['clordid'];?>
<?php $orderid = $_POST['orderid'];?>
//connected to database using mysqli
$result = mysqli_query($con,"SELECT * FROM abc where clordid like '$clordid' and orderid like '$orderid'
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
echo "<tr>";
for($k=0;$k<150;$k++){
echo "<td>" .$row[$k]. "</td>";}
This code works fine. When I run this query again to calculate total number of rows and also total number of page links to be displayed in pagination, that works as well. However, whenever I click next page using pagination, the code forgets the value of variables imported earlier from html page. I tried to pass it using the url but has been unsuccessful. I believe somehow the values from html page must be retained by the program at all times to make query execute successfully at all times. Can anyone provide me some basic example (or a url) that could help me understand the process? Thanks
You can assign the variable to the session like so:
session_start();
if ($_GET['page_number'] == 1){
$_SESSION['clordid'] = $_POST['clordid'];
}

How to encrypt product ID in URL

I have a database with just over 800 data.
product table
pid name p_page
1 money money.php
2 gold gold.php
3 .
. .
. .
800 .
I have 2 pages...
product_item.php
<div class="button">
View
</div>`
when you click view the product info is pass to product.php
in here i have
if (isset($_GET['pid'])) {
depending on what product the user clicked on the URL might look like something below but the 44 will change to whatever id
http://www.example.x10.mx/money.php?pid=44
the problem with this, is that money.php have a different layout to the other pages and if I change 44 to 68, the product info will show on the page but the layout will not look good.
My question
what is the best way for me to stop users from being able to change the url.
I want to encrypt all my pid in the url so it will look something like
http://www.example.x10.mx//money.php?sel=the product name here or 4 letters or anything
I just want to take away pid from the url.
Please help me. If you dont understand my question please ask in the comment and try and say what you think you understand.
Edited to show my fetch function
$php = "php/";
$apages = "account/";
$bpages = "booking/";
$gpages = "general/";
$ppages = "product/";
// Global functions
function fetchdir($dir)
{
$protocol = $GLOBALS['protocol'];
$host = $GLOBALS['host'];
($dir == $GLOBALS['apages'] || $dir == $GLOBALS['bpages'] || $dir == $GLOBALS['ppages'] || $dir == $GLOBALS['gpages'] ? $branch = $GLOBALS['pagebranch'] : $branch = $GLOBALS['branch']);
echo $protocol.$host.$branch.$dir;
}
Thanks
p.s. I dont know if this can be done in .htaccess but i think it can be done in php
Some clarification:
I have a url which looks like this
www.example.com/account/product.php?pid=1
the problem with this is that someone can change 1 or any number and if they is a pid in the database with that number it will get the items information and display on the page. Which I don't want to happen because not all product are meant to be display in some pages.
In the papge which i show all my available product. I simple uses a SELECT statement and then echo what I need in some div.
In that page I have a view button.
$stmt = $conn->prepare("SELECT * FROM Product WHERE Type = 'shoes'");
$stmt->execute();
$i = 0;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$id = ($row['pid']);
$product_page ($row['dir_page']);
<div class="button" >
<a href = "<?php fetchdir($apages) ?><?echo $product_page?ProdID=<?php echo $id>" > View</a >
</div >
}
Depending on the page that information is getting sent to when you click on view I use Get method
<?php
if (isset($_GET['pid'])) {
// Connect to the MySQL database
dbconnect();
$id = preg_replace('#[^0-9]#i', '', $_GET['pid']);
}
If you notice in my select statement used type to show only the product which type is shoes. I have other types as well, which as their other pages. Now the problem is if i change the pid to any page that doesn't have a type of shoes or if an in the other pages and enter a pid which type is shoes or anything, the information from that page will still render. Which I don't want to happen.
My question
how can i stop users from changing that pid and even if they change it. they will still be on the same page?
The problem isn't having the PID in the URL, it is having the template name in the URL.
Store the template name in the database (you are doing this already), and use that to determine what HTML to wrap the data in instead of putting it (money.php) in the URL.
Move your templates out of the web root (they shouldn't be hit by users directly), have a single index.php and then include() the template based on the data in the database.
You cannot prevent someone from changing the URL or from requesting arbitrary URLs. Your server (i.e. your app) has to decide how to respond to an invalid request. If you don't want to display certain things publicly, flag them as such in your database, test for that flag and simply refuse to output anything if that flag is hit.
Make the server respond negatively if something doesn't fit your conditions; don't expect the user to behave correctly.
Assuming that PID is a autoincrement value, you can still obfuscate it. Add another column in the table that contains a randomly-generated key (using uniqid or some derivative). Then use that key in your URL. You'll get something like: www.example.com/account/product.php?pid=II8GypI6H93Ij. This doesn't guarantee that someone won't find it, but it's good enough in most instances.
Check for allowance in the Database
Depending on your level of programming skills, in the database you could add a field or a relational table that relates the ID of the pages to allowed page templates (I'm guessing you're talking about templates.)
Then in the code you can make it so the page checks this database to see if the page contents are allowed to show. Something like:
$query1 = "SELECT * FROM Product WHERE Type = 'shoes' and allowedTemplate='1'";
This way you won't have to hardcode everything into the code itself. On the backend (if there is a CMS) then you could have checkboxes indicating the relationships to the templates and prefill them by default.
You'll need to make the site so something with that stuff though.
Your other option
You could use clean urls (which used to be better for SEO) to show real words instead of the IDs. Then you can use .htaccess tricks to convert the URIs to their ID counterparts with a dynamic RewriteMap.

PHP Link Click counter

I want to write simple counter for links/tags. So I have tags and random displayed them to the website
$zmienna = "SELECT name, link FROM tag_content ORDER BY RAND() LIMIT 4";
$result2 = mysql_query($zmienna);
echo $result2;
while($row=mysql_fetch_array($result2)){
echo "<a href='http://www.simplelink.xx/tag/".$row['link']."'>".$row['name']."</a><br>";
}
And now I want to count how many users clicked tags. I created another row named "wys" and tried to write SQL stuff
$wtf = "UPDATE tag_content SET wys=wys+1 WHERE id=2";
$result3=mysql_query($wtf);
As u can see it only works for tag id = 2. And now the problem: how to make it work for all tags?
For example: I have 4 tags with different id. How to make counter "read" the actual clicked tag and make it add "1" to the "wys"?
Thx for help and let me know if u need more information (like code etc.)
As the link field is unique, you can simply use it as an identifier instead of id.
$wtf = "UPDATE tag_content SET wys=wys+1 WHERE link='".$something."";
where $something is a last part of page URL (you should parse it). Of course you also need to check this variable before you use it, because you got it from client side and it could have code for SQL-injection.
You need a way to get the id of all links. Either provide it as a query parameter for the link, or use parse out the name and url from the clicked link and make a relevant SELECT to get the id to loop over.
Use jquery :eq() selector to find out the exact link and then make an ajax request for updating the count

Displaying name instead of ID PHP MySQL

I need something simple; I have page where a user clicks an author to see the books associated with that author. On my page displaying the list of books for the author, I want a simple HTML title saying: 'The books for: AUTHORNAME'
I can get the page to display author ID but not the name. When the user clicks the link in the previous page of the author, it looks likes this:
<?php echo $row['authorname']?>
And then on the 'viewauthorbooks.php?author_id=23' I have declared this at the start:
$author_id = $_GET['author_id'];
$authorname = $_GET['authorname'];
And finally, 'The books for: AUTHORNAME, where it says AUTHORNAME, I have this:
echo $authorname
(With PHP tags, buts its not letting me put them in!) And this doesnt show anything, however if I change it to author_id, it displays the correct author ID that has been clicked, but its not exactly user friendly!! Can anyone help me out!
You could pull the author_id from the query string as you did using $_GET but beware you will need to validate what is coming through by the query. I hope you can see that without validation how bad of a security hole this is.
I am at work at the moment, but this is a quick example that should give you what you need without sanitizing your query.
$id = intval($_GET['author_id']);
// of course, perform more validation checks
// just don't assume its safe.
$sql = "SELECT authorname FROM authors_tb WHERE author_id=" . $id;
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo "The books for: " . $row['authorname'];
}
The reason why your approach wasn't working was because you utilize the $_GET URL parameter passing for author_name where you weren't supplying the parameters in the URL, just the author_id.
You don't send it in the query string, thus you can't get it from the $_GET array.
Just request it from the database using id.
An important note: Always use htmlspacialchars() when you display the data, coming from the client side.
This is because you do not define the author name in your get.
You should make the following your url:
<?php echo $row['authorname']?>
Or rather select the data from the database again, on the new page, using the ID you retrieved from the URI.
Author name won't be in $_GET. As your code stands, you only use it as the link title. It is no where in the address. Try this instead:
<?php echo $row['authorname']?>
It would be better to re-request it from the database using the author_id though.
EDIT:
To explain the problem in more detail. You have two pages, the new.php page and the viewauthorbooks.php page. You're sending users from the new page to the view page using the link you posted, right?
The problem with that is, your link assigns one variable in get. Here's the query string it would generate:
viewauthorbooks.php?author_id=13
What that will do is send the user to viewauthorbooks and place the value '13' in the $_GET variable: $_GET['author_id']. That is why the author_id is there and displays on viewauthorbooks. However, authorname is never passed to viewauthorbooks, it isn't in $_GET['authorname'] because you never set $_GET['authorname']. If you want it to be in $_GET, then you need your query string to look like this:
viewauthorbooks.php?author_id=13&authorname=bob
You can accomplish that using the new HTML code for the link I posted above. Look at it closely, there's a key difference from the one you have now.
However, it is generally discouraged to pass data through GET, because the query string is displayed to the user and it leaves you open to injection attacks. A better way to do this would be to use the author_id you are already passing to viewauthorbooks.php to retrieve the authorname from the database again. You can use the same code you used on the new.php page.

Categories