create html pages dynamically with proper url - javascript

I want to dynamically create webpages using a php script(for example : category.php) which takes on variable 'category' and do a mysql query to get data from the server and create a webpage.
category.php
< ? php
include_once("php_includes/db_conx.php");
$sql = "SELECT * FROM PRODUCTS WHERE CATEGORY = 'CLOTHING' ";
$result = $db_conx->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
/*GENERATE SOME WEBPAGE*/
}
}
? >
So when a user clicks a link "/category/clothing " it should pick the variable value (category = 'clothing' ) from this link and dynamically generate a webpage with the address "www.example.com/category/clothing" instead of something like "www.example.com/category/?category=clothing"
What i want to avoid is a url having '?' and '='
So I want to achieve 2 things:
A single php file generating pages dynamically by taking values from links like "/category/clothing"
Url of the new webpage should be simple and proper "www.example.com/category/clothing" (of course it should be same as the link clicked ) and not like "www.example.com/category/?category=clothing"
Can someone write a example php or js script which can achieve this or point me in the right direction(in case its very simple)

PHP can't do this by itself. You are going to need an .htaccess apache module called mod rewrite. Here is a tutorial how to make pretty urls.
http://code.tutsplus.com/tutorials/using-htaccess-files-for-pretty-urls--net-6049

Related

PHP - remove parameters from URL but still pass to another page

I have a php website. The first page contains a list of products and I'm currently passing the ID (picked up from mysql database) for the product within the URL to the items page i.e. localhost/item.php?4
I don't want to show any parameters in the URL so have investigated another option which is using a session.
The issue with this is that the link to each of my items is in a while loop retrieving ID and product name from the database so I'm having issues making the session mirror the ID when an item/link has been clicked.
Here's a snippet of my code (I've removed the session code):
$stmt = $con->prepare("SELECT pid, product_name FROM persons where deleted = ? order by order_age desc");
$stmt->bind_param("i", $del);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr><td>';
$phn = $row["pid"];
echo "<span><a class='storage' href='item.php'>" . $rows["product_name"] . "</a></span>";
}
echo "</td></tr>";
}
I guess I have two questions:
Is it possible to achieve what I need to do
What is the correct way of achieving this
Thanks in advance,
Pete
Options, briefly
You could first load /item.php?id=4 then redirect to /item-hidden.php & use $_SERVER['HTTP_REFERER'] & parse_url & process the GET portion of the referrer url.
You could also use session for this. Set the session variables when the page loads to the long-url, then redirect to the short url, load the session & clear the session.
If you just want to shorten the url, then you could use uniqid() And put the unique id in the url & save the paramaters to a session variable with that unique id.
You could use a pre-made url shortener.
You could roll your own url shortener using a reference file that holds an array or a database.
There are surely other creative solutions that I haven't thought of
My thoughts:
Hiding the url altogether will make for a poor user experience - inability to bookmark, using the back-button will be funky, hard to share an item on social media or a blog
Shortening the url is nice but not necessary
Depending on the options you're working with, you might be able to create shorthands that are more friendly to look at in the url bar or db-references for sets of options that are extremely common
What you're trying to do seems like a great learning project - learn about sessions, http_referer, databasing & whatnot. I think by doing what you're wanting, you'll learn that you don't really like how it feels - or you might come up with a clever way to make your URLs prettier & make the UX really nice.

fetch column from sql data base into html pull down menu using php

I am quite new to java script and i am struggling with the following.
I am using php 7 and trying to call data from sql database, the data is a table, but i want to select one column from that table and put it into a pull down menu in html.
So, I used mysqli prepare function as follows. I have two question, the first: can this run inside the same php where another sql query was open. the second is how to use what is returned (the column in that case) and put it into a pull down menu the user can choose from in html.
what I tried is to put that code inside the code as I saw in another post. but the data cannot be populated.
EDIT:
The database is oracle so i cannot use mysqli, i used instead the following code
but i am getting only the first number in the column and not displaying it in the pull down menu, how can i use foreach to loop over all retrieved numbersand use that in the pull down menu?. I am confused, where to include the select statement for html pull down menu
<td>
<?php
require_once("..//ora_db");
// Create connection
$oracle_db = new ora_database("abc");
// Check connection
$sql = "SELECT * FROM cvbh";
$cursor = $oracle_db->execute_sql($sql);
$counter=0;
while (OCIFetchInto ($cursor,$row))
{
$number= $row[1];
# echo "<select><option value="number">$number</option></select>";
$counter ++;
}
print_r($number);
?>
<select><option value="number">number</option></select>
</td>
First of all there is no need for javascript here.
Answer to your first question: Yes you can run multiple query's on the same page.
Answer to your second question: You can easily generate html code based on your for loop by doing something like this
<select>
foreach ($stmt->get_result() as $row)
{
echo "<option> $row['Column'] </option>";
}
</select>

Passing information to JS File from Module File in Drupal 7

In one of my webpage I print one button multiple times and all have different logId. I want that when user click then there will JQuery into the picture and there should be no server side post-back. Since a unique log id is associated with every button so I pass the information to JS file from *.Module as below when the button is clicked:-
*.module File -- PHP File
$thm_button .= '<input type="button" class="clsPrevious" id="btnPrev_'.$user->uid.'_'.$logid;>';
*.js File
$('.clsPrevious', context).click(function (event) {
var previousLog=this.id.split('_');
//Retrieve log Id and Process the log id using AJAX call
}
This is working fine here but I feel there is security concern as everyone can view the log id of the button in HTML source.
Are there any ways in Drupal/PHP/HTML to pass the sensitive information to JS without showing in HTML Viewer.
You can pass values from PHP to Javascript with "Drupal.settings".
Read more about it here.
You can create a input button which looks something like this.
$thm_button .= '<input type="button" class="clsPrevious" data-myModule=" . $key . ">;
where $key is a random/serial variable but is unique per Log ID.
Create a mapping array of key value pair and pass to javasript using drupal_add_js()
<?php
drupal_add_js(array('myModule' => array('_YOUR_CUSTOM_KEY_1_' => '_LOG_ID_1_')), 'setting');
?>
And now modify your click function to,
$('.clsPrevious', context).click(function (event) {
var key = $(this).attr("data-myModule");
// Now a this point you have the lookup table in Drupal.settings.myModule
// use the "key" variable to find the LOG ID
}

How to add product to cart in WooCommerce using JavaScript

Is it possible to add a product to cart with a new price using JavaScript? I have been working on a little script that calculates the price of the product. I would really like to write a function like this:
function addToCart(productID, productPrice) {
//add the product to cart with JavaScript
}
Any help or pointers would be deeply appreciated.
So far I have written 4 main files:
functions.js - calculates and shows the current price based on options the customer chooses (this works fine)
ajaxSubmit.js - jQuery ajax to send the variables to my PHP files (sends successfully)
post.php - file where the variables are sent
simple.php - the single product PHP file which displays the product
I have been able to send the variable from the JavaScript function to my product but I don't know how to add the product to cart.
My post.php looks like this:
EDIT: The following code works now and adds the product with the id 747
<?php
require('../../../../../../wp-load.php');
global $woocommerce;
$woocommerce->cart->add_to_cart(747);
sleep(3);
if (empty($_POST['ammount'])) {
$return['error'] = true;
$return['msg'] = 'You didnt select the amount.';
}
else {
$return['error'] = false;
$final_amount = $_POST['ammount'] * 10;
$return['msg'] = 'Youve chosen: ' . $final_amount . '.';
}
echo json_encode($return);
?>
I have found out that you can add a product into the cart using the following code in PHP:
global $woocommerce;
$woocommerce->cart->add_to_cart($product_id);
Then I tried adding these 2 lines into my post.php and it didn't work and also the form stopped working. If I add this into my simple.php (which basically displays the product) it works fine.
My question is: How can I add a product into the cart using this setup?
To add a product using AJAX I had to include the wp-load.php into my post.php file. That way I could access to the woocommerce variable and later add the product. Look above for the code fix.

Google Places API concatenate search string with MySQL response

I'm trying to create a Google Places URL that can be reused and concatenated with a response from my database.. Not getting this to work and have been trying for a couple of days with no luck! If I echo out the both strings, from PHP on to my web page and copy&paste it, both addresses generate the same Google Places result, but when I print the JSON decoded response I get UNKNOW_ERROR from Google..
This is what I have been trying to use. The first and the second $googlePlacesAPI contains the exact same URL, just that one is concatenated and the other is "hard coded".
$googlePlacesAPI = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" .
$BarName. "+" . $BarCity . "&sensor=false&types=bar|night_club&key=" . $mySuperSecretKey;
$googlePlacesAPI = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" .
$BarName. "+" ."Göteborg". "&sensor=false&types=bar|night_club&key=" . $mySuperSecretKey;
To get the value of $BarCity I use this piece of code (before creating the $googlePlacesAPI variable):
$row = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM City WHERE ID = $CityID"));
mysqli_close($con);
$BarCity = $row['CityName'];
EDIT:
This is how I decode the answer:
$placesSearch = json_decode(file_get_contents($googlePlacesAPI));
You probably want to close the connection after you're done with $row:
$row = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM City WHERE ID = $CityID"));
$BarCity = $row['CityName'];
mysqli_close($con);
See a sample of mysqli_fetch_array usage at http://nl3.php.net/mysqli_fetch_array#example-1728

Categories