PHP Header adding multiple times - php
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");
Related
Trying to echo a specific variable from a specific row
So I am attempting to; -send a HTTP request from another source to the php file, within that http request it will contain something like; http://mywebsite.com/postServer.php/type=cmd&game=5342252 and what is should be doing is taking the post "game" and comparing it with the table to find witch row contains 5342252 in the column "gid". However its not working. Now if I remove $game = $_POST["game"] and just put 5342252 were $game is it will work just fine... So im very confused as to why it wont work with $_POST <?php $type = $_POST["type"]; $game = $_POST["game"]; if(type == "cmd") { $con = new mysqli("localhost","***","***","***"); if(mysqli_connect_errno()){ echo(mysqli_connect_error()); } $data = $con->query("SELECT * FROM onlineservers WHERE gid =".$game); while($row = $data->fetch_array()){ echo json_encode(array('command' => $row[cmd])); } } ?>
Note: First you must understand how to pass the variables in the URL with parameters. You have been missing the basic knowledge of how to pass the variables as parameters in the URL. Rules: First Parameter to be given with ? mark alone with value Second Parameter to be given with & symbol along with values. You can add any number of parameter provide the first one has to be with the ? symbol otherwise the code will not work. Example: http:// domain.com?first_param=1&second_param=2 Brief Explanations on URL Parameters. http://domain.net/page.php?id=1254 Why is there a question mark after the page name? The answer is that the characters after the question mark are an HTTP query string. An HTTP query string can contain both variables and their values. In the example above, the HTTP query string contains a variable named "id", with the value "1254". Here is another example: http://domain.net/page.php?name=Joe Again, you have a variable ("name") with a value ("Joe"). How to get the variable with PHP? Let's say you have a PHP page named people.php. Now you can call this page using the following URL: people.php?name=Joe With PHP, you will be able to get the value of the variable 'name' like this: <?php echo $_REQUEST['name']; // Result the Output as Joe echo $_GET['name']; // Result the Output as Joe ?> Let's try it in an example: <html> <head> <title>Query string</title> </head> <body> <?php // The value of the variable name is found echo "<h1>Hello " . $_GET["name"] . "</h1>"; // The value of the variable name is found echo "<h1>Hello " . $_REQUEST["name"] . "</h1>"; ?> </body> </html> Several variables in the same URL: You are not limited to pass only one variable in a URL. By separating the variables with &, multiple variables can be passed: people.php?name=Joe&age=24 This URL contains two variables: name and age. In the same way as above, you can get the variables like this: $_GET["name"] $_GET["age"] Let's add the extra variable to the example: <html> <head> <title>Query string </title> </head> <body> <?php // The value of the variable name is found echo "<h1>Hello " . $_GET["name"] . "</h1>"; // The value of the variable age is found echo "<h1>You are " . $_GET["age"] . " years old </h1>"; ?> </body> </html> Solution for Your Code 1.) Your URL should be like this as i have stated below. http://mywebsite.com/postServer.php/?type=cmd&game=5342252 Then alone you can retrieve the data from the URL separately 2.) In order to get the data from the URL you have to use $_GET OR $_REQUEST. But you have used $_POST which is totally a blunder It should be $type = $_REQUEST["type"]; $game = $_REQUEST["game"]; 3.) If statement seems to a error in your code. You have to replace it as this: if($type == "cmd") {} But you have done like this if(type == "cmd") {} whoch leads to fatal error. 4.) While selecting the statements you have to check for the count of the query executed since if the count is ZERO and you execute the while or foreach you may be facing error. Hence the Entire code will look like as follows: <?php $type = $_REQUEST["type"]; $game = $_REQUEST["game"]; if($type == "cmd") { $con = new mysqli("localhost","***","***","***"); if(mysqli_connect_errno()){ echo(mysqli_connect_error()); } $data = $con->query("SELECT * FROM onlineservers WHERE gid =".$game); $count = $data->num_rows; if($count==0) { // perform the failure action } else { while($row = $data->fetch_array()){ echo json_encode(array('command' => $row[cmd])); } } } ?> After you have done all the checks that i have mentioned above you have to ensure the note below in order to check your code works or not. Note: You first put echo to the Select Statement and then break the execution by putting the exit; and you copy the statement that is echoed and place it in SQL of the DB and then check whether any error occurs in insertion. If no error occurs remove the echo and delete the exit;
Change the $_POST["..."] for $_GET["..."]. Each variable that you pass in URL is obtained through the $_GET method. Example: If you do http://some.com/anything.php?var=test if you do $_GET["var"] you will get "test".
Try this : <?php $type = $_GET["type"]; $game = $_GET["game"]; if($type == "cmd") { $con = new mysqli("localhost","***","***","***"); if(mysqli_connect_errno()){ echo(mysqli_connect_error()); } $data = $con->query("SELECT * FROM onlineservers WHERE gid =".$game); while($row = $data->fetch_array()){ echo json_encode(array('command' => $row[cmd])); } } ?> You are not Posting the data, but receiving the data and hence $_GET is required. And also your url shoud be like this: http://mywebsite.com/postServer.php?type=cmd&game=5342252
Replace Value of Variable in Query
currently i have page1.php being entered into the URL bar with the variable status and a string in the URL like this http://example.com/page1.php?status=red. When the user clicks enter, it redirects to page2.php and generates more variables and adds another &status= at the end of the url like this http://example.com/page2.php?status=red&varone=1&vartwo=2&status=green Instead of having 2 status variables in the URL, i would like to remove the 1st 1 completely so it is just left with &status=green at the end. Here is the code I have for the header redirect: $query = $_SERVER["QUERY_STRING"]; header("Location: page2.php" . $query . "&status=" . $currentstatus); I would rather remove the first ?status= if possible, since i do want &status= at the very end of the url
If you want to remove first occurrence of status from query string then better to remove it from the previous URL.
$query = $_SERVER["QUERY_STRING"]; $new_query = str_replace($_REQUEST['status'], $currentstatus, $query); // New query with $currentstatus as status value header("Location: page2.php?" . $new_query);
try if status is the only parameter: $query= str_replace("status=".$_REQUEST["status"],"", $query); or if there are more following: $query= str_replace("status=".$_REQUEST["status"]."&","", $query);
preg_replace option : (note, this will not work if the parameter doesn't yet exist) $query = $_SERVER["QUERY_STRING"]; $query= preg_replace("/status=".$_REQUEST["status"]."(&)?/","status=$currentstatus$1", $query); header("Location: page2.php" . $query); parse_str option : (this will work even if the parameter does not yet exist) parse_str($_SERVER['QUERY_STRING'], $query); $query['status'] = $currentstatus; header("Location: page2.php" . http_build_query($query_string));
user parse_str and http_build_query. try below solution: $query_string = 'status=red&varone=1&vartwo=2'; $current_status = 'newstatus'; //parse current query string parse_str($query_string, $q_arr); //replace new status $q_arr['status'] = $current_status; //generate new query string $new_query_string = http_build_query($q_arr); output status=newstatus&varone=1&vartwo=2
No need to treat the query string like a string. You get the variables in PHP as a nice array, so use it! $_GET["status"] = $currentstatus; $query = http_build_query($_GET); header("Location: page2.php?$query");
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'");
Get certain part of url and use a WHERE clause
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 . '"';
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)