Get certain part of url and use a WHERE clause - php

How do I get a certain part of the url?
Example: bithumor.co/posts/12345
How do I get the "12345" part so it can be put in the WHERE clause of the mysql(i) query and SELECT the post from the database where id = 12345 (when on the webpage: bithumor.co/posts/12345)
Example:
SELECT post_ id FROM post WHERE id = ["12345" part of url]
I already have bithumor.co/posts?id=12345 sorta thing

Firstly you could use a rewrite in your htaccess to form a get request to your PHP script then just access the id as you would any GET parameter.
RewriteRule ^posts/([0-9]+)$ posts.php?id=$1 [NC,L]
Or if you want to do it from pure PHP that is a choice too.
$tokens = explode("/", $_SERVER[REQUEST_URI]);
$number = $tokens[count($tokens) - 1];
$query = 'SELECT post_ id FROM post WHERE id = "' . $number . '"';

Related

PHP Header adding multiple times

I have this query:
$get_ids = "SELECT unique_id FROM products GROUP BY unique_id LIMIT 10";
$id_results = mysql_query($get_ids);
while($id_row = mysql_fetch_array($id_results))
{
extract($id_row);
$all_prods_link[] = $id_row['unique_id'];
}
This will create an array of integers. For each item in the array, I append this to a string, following by a comma:
foreach($all_prods_link as $all_prods)
{
$query_string .= $all_prods.',';
}
The result is like: 1,2,3,4,5,6, which is working as intended.
The problem I am having is I am trying to add this to the end of the current URI, and then redirect to this URI eg:
$link = $_SERVER['REQUEST_URI'] . '&product_options=' . $query_string;
The $link variable looks good:
sales_reports.php?date_from=05%2F11%2F2017&date_to=05%2F12%2F2017&pay_status=Paid&submitfilter=Go&prodtype=all&report_type=productreports&product_options=1,2,3,4,5,6,7,8,9,10,
This is exactly what I want, however when I then try to redirect to this link, eg:
header("Location: $link");
The actual URI I end up with has the $query_string, appended to it multiple times, like so:
sales_reports.php?date_from=05%2F11%2F2017&date_to=05%2F12%2F2017&pay_status=Paid&submitfilter=Go&prodtype=all&report_type=productreports&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,&product_options=1,2,3,4,5,6,7,8,9,10,
As you can see, "&product_options" appears multiple times, followed by the list of integers!
Can the header() function be used this way? or am I doing something horribly wrong!
This is because of multiple redirect each time you load the page, php will append product_options rather than replacing it.
<?php
// Parse all request components
$request = parse_url($_SERVER['REQUEST_URI']);
// Parse incoming query sting to array
parse_str($request['query'], $queryArray);
// replace or add product_options
$queryArray['product_options'] = $query_string;
// rebuild the query
$newQueryString = http_build_query($queryArray);
$link = $request['path']. '?' . $newQueryString;
header("Location: $link");

SQL injection id name contains '&'

in my php code i am passing an id for the php to get the info from the sql server.
it seems to work fine but whenever i have an '&' in the name, it doesn't work any more
$doc_info = array();
$id = "ID not set";
if(isset($_GET['document_id'])) {
$id = $_GET['document_id'];
$id = str_replace('___', '&', $id);
$doc_info = get_document_info($id);
$doc_info['dummy'] = " ";
}
example of an id that works "2017_test id"
http://localhost/php/single-entry.php?document_id=2017_test%20id
here I get the info right.
example of an id that doesn't work "2017_e&i EDV"
http://localhost/php/single-entry.php?document_id=2017_e&i%20EDV
here I get PHP WARNING: Undefined index. although the data is in DB.
I am passing the id to another function that get an array of the info stored in the DB with this ID .
in first example I get the data, but if the name has '&' i get Undefined index
You can use the following:
urlencode($document_id) - while sending the request to your php script
And as pointed on in comment section, $_GET["document_id"] would give
you already decoded value
And use the decoded value instead in your PHP script.

PHP Retrieving Data From MySQL After Modifying URL Parameter

I'm building a webpage that retrives data depending on a URL parameter.
There are two possible parameters.
1: id which is retrieved using $_GET['id']
2: name which is retrieved using $_GET['name']
When I am retrieving data using the id parameter it works like a charm since id is always a numerical value and never alphabetical text.
But when attempting to retrieve data using the name parameter I get no results.
The name parameter is checking the database for an article with the articles title being the parameter.
For example the name parameter in a URL would look like so:
http://example.com/safetyarticles/view.php?name=9-clues-to-solving-this-parameter-issue
And in the database the articles name would be: 9 Clues To Solving This Parameter Issue
I've already written some lines to remove the dashes in my url parameter to spaces and then capitalize each word to match the article name, but I'm not getting any results.
This is the code I have written:
$conn = getConnected("safetyArticles");
if(isset($_GET['id'])) {
$articleID = $_GET['id'];
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_id = $articleID");
$article = mysqli_fetch_array($articleQuery);
}
else if(isset($_GET['name'])) {
$articleName = $_GET['name'];
$articleName = preg_replace("/[\-]/", " ", $articleName); // Replace dashes in URL parameter with spaces
$articleName = ucwords($articleName); // Uppercase first letter of each word of URL parameter
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = $articleName");
$article = mysqli_fetch_array($articleQuery);
}
To my knowledge replacing the dashes with spaces and capitalizing each word should make the article_name in the database and $articleName match.
I did add a line of echo $articleName just to see what the output was and the result was 9 Clues To Solving The Mystery Of The Pilot Car which matches the title in the database but the results are not being pulled.
I copied this directly out of the database just to show that the titles are indeed the same: 9 Clues To Solving The Mystery Of The Pilot Car.
I'm at a loss since everything is matching up as it should.
you need '' around the variables in the query:eg '$articleName':
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = '$articleName'");
$articleName in your query needs to be quoted like this : '$articleName'. eg
$articleQuery = mysqli_query($conn, "SELECT * FROM currentArticles WHERE article_name = '$articleName'");

Loading a record with the primary key in the url?

is it possible to use GET or something like this to load a record into a form ?.
E.g I have for formA where it has a foreach list of all the clients in the DB , at the end of each row I have a link which is called 'edit' , this link goes to formB.php and is set out like this >>
sitename.com/FormB.php?token=<?php echo $ID ?>
This gives you an url that looks like the following :
http://www.sitename.com/formB.php?token=25
The link above would for example load the record with ID 25 into the second form.
I am not sure how to handle the link in the second form though, can you echo GET ID in the second form, or would it have to be GET token ?.
In PHP, there's the predefined $_GET variable. This is basically an array holding all GET paremeters:
// url = index.php?foo=bar&hello=world
echo $_GET['foo']; // bar
echo $_GET['hello']; // world
So, considering your url and query:
$query = 'SELECT * FROM `table` WHERE `token`=' . $_GET['token'];
To avoid security exploits, we need to use the function mysql_real_escape_string around the user-defined parameter when using strings. When using other types such as numbers you can just parse it to a number.
// if token is a number
$query = 'SELECT * FROM `table` WHERE `token`=' . intval($_GET['token']);
// if token is a string
$query = 'SELECT * FROM `table` WHERE `token`=' . mysql_real_escape_string($_GET['token']);
You can access your GET-Parameter with the $_GET-array. To see whats in there you can use:
print_r($_GET);
In the second case you would have to use $_GET['token'] as the parameter is named token.
Note: If you are passing the parameter into a SQL-Query make sure it is secured. In this case with intval(). SQL-Injections are bad.

Rewrite url with id and title (php)

How to rewrite url (what to do) so that instead:
http://www.example.com/article.php?id=123
it says:
http://www.example.com/articles/123/article_title_read_from_database
using php and mysql
Thanks.
When the example article.php well page is accessed with the GET of id=123, the php code to retrieve the number is
$my_id = $_GET['id']
, in this case, that would produce 123.
Then you can redirect the page using
header('Location: http://example.com/articles/$id/other stuff');
I'll leave the MySQL stuff for someone else, but a simple tutorial will give you alot of info on that.
To process request and redirect to new url:
// get id of record from URL
$id = (int) $_GET['id'];
// suppose connection to database is established already
$result = mysql_query("SELECT `title` FROM `articles` WHERE `id` = $id");
if (!$result) {
// there is no such an article
// you can redirect to some other page, or show some error message
} else {
$row = mysql_fetch_assoc($result);
$title = $row['title'];
$urlPart = generateURL($title);
header('location:/articles/$id/$urlPart');
exit;
}
you'll need generateURL function, that take string input and replace all unusable characters with _. (For example if you have title "What's going on?" it will replace ', ? and whitespaces to something like "what_s_going_on"). You can use str_replace or preg_replace to achieve this.
If you want to generate new URL on multiple places, you can insert URL form of title directly into database as another column title_url and then just select it and use it instead of title:
SELECT `title_url` FROM `articles` WHERE `id` = $id
There is no way you can do this kind of rewriting in .htaccess as you can't connect to database server from within this file. (Or at least I don't know such a solution)

Categories