Replace Value of Variable in Query - php
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");
Related
Remove character at the end of url
1) I have url like this : http://example.com/post.php?id=1234 And inside : my article 2) but for this url http://example.com/post.php?1234somewords It's also work, i see my article 3) and for this url http://example.com/post.php?somewords I have good 404 page error Question is : how could i have 404 error for the 2) url ? (alternative question : how could i redirect "1234somewords" to "1234" ?) php mysql query inside post.php is : require_once('conn_sql.php'); $post = $_GET['post']; $nQuery = mysqli_query($conn, "SELECT * FROM `post` WHERE post_id = '$post'"); $res = mysqli_fetch_array($nQuery); It seems that the query "post=1234somewords" works, and this is not what i want. however, if i search "post=1234somewords" in phpmyadmin, this not works, and this is what i want ! What is the problem with my code ?
this happen because mysql use the beginning part of the string as a valid id .. (this i related to the implic data conversion performed by mysql) you should check if your parameter are valid number before perform the query you could try removing the not numeric value from the string $result = preg_replace("/[^0-9]/", "", $_GET['post']; ); if (is_numeric( $result)) { $nQuery = mysqli_query($conn, "SELECT * FROM `post` WHERE post_id = '$post'"); $res = mysqli_fetch_array($nQuery); } else { ...... }
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");
Catch parameter from URL, pass parameter to a function, execute that function
I have seen a case where for example a URL like this http://example.com/?edit=39 straight away opens a page where you can edit only the article/post which has ID = 39. I have read a lot about calling a function via URL but I have never met the case where you can catch parameter from the URL, pass the parameter into the function and then execute the function. Using URL http://example.com/?edit=39 as example, how do I use a function to identify 39 as the ID and retrieve a post from the database which has ID = 39.
For example your URL is test.php?edit=39 if (isset($_GET['edit'])) {// it will catch the 39 $id= $_GET['edit']; $return_value=funciton_name($id);// passing parameter to the function echo $return_value;// it will display the return vlaue. } //execute that function and return the value function funciton_name($id){ $result1 = "SELECT * FROM tablename WHERE id=".$id; return $result1; }
Use parse_url() and parse_str() functions. For example $parts = parse_url($url); parse_str($parts['query'], $query); echo $query['email']; If you want to get the $url dynamically have a look at this below question: Get the full URL in PHP
Gets results only when empty
I have this sql statement that returns rows from a customer table. The user has the option for searching with what ever they want to type in. I had this working, until I tried to protect against sql injecting by using bindValue. Now I can't get any results to return unless the user leaves the textbox blank. Below is my code. Model function searchMyCusts($field, $query){ $data = null; $msg = null; $status = null; $sth = $this->db->prepare("SELECT ".CustomerFields::ID.",".CustomerFields::FirstName.",".CustomerFields::LastName.",".CustomerFields::PhoneNumber." FROM ".CustomerFields::TableName." WHERE '$field' LIKE :query"); $sth->bindValue(':query', $query); if ($sth->execute()){ $status = "success"; $msg = "Customer entry successfully altered"; $data = $this->smartFetchAll($sth); }else{ $status = "error"; $msg = "An error occurred. :".$sth->errorInfo()[2]; } $jsonData = json_encode($this->buildResponseArray($status, $msg, $data)); return $jsonData; } In the prepare line at the end I have the values being passed in. Like I said this was working until I attempted to bindValue the query variable. I would appreciate any insight you may have. Thanks in advance! Regards
I don't know how could it work before but first of all you need to change " WHERE '$field' LIKE :query" to " WHERE $field LIKE :query" or " WHERE `$field` LIKE :query" You can't use quotes around a column name because it becomes just a literal string which you compare with :query pattern. The query will work but you'll have no rows returned. Either nothing or back ticks. Secondly $query should contain all necessary wildcard symbols prior to prepare. E.g. $query = "%new%"; It's not clear whether it's the case from your code
PHP check a string for something and if there save to variable
I am getting my URL from my site and trying to save a certain field to a variable $link = "$_SERVER[REQUEST_URI]"; // example of $link = "/index.php?option=com_course&id=1&Itemid=104" if(strpos($actual_link,'id=') !== false){ $id = // the number after id= in the string } basically im checking if id= exists within the string and if it does to save the number of the id to $id. so the outcome of the example of $link listed above would be for $id = 1
If the URL from the site is passing variables you can just use GET? $id = $_GET["id"];
First of all, you want the first line to be $link = $_SERVER['REQUEST_URI'];. But for requesting data like that, from an request to your own server, there's a reserved global variable: $_GET (http://php.net/manual/en/reserved.variables.get.php) It'd work like this: $id = $_GET['id'];