I have 2 php pages. 1st php page is the following:
<?php
//code...
if(isset($_POST['value'])== true && empty($_POST['value']) == false){
echo"<a href='search_form_all_2.php'>See more results for </a>";
} ?>
the second page is the "search_form_all_2.php".
<?php
$value = mysql_real_escape_string($_POST['value']);
$name_and_surname = explode(" ", "$value ");
$name = $name_and_surname[0];
$surname = $name_and_surname[1];
$query = mysql_query(" SELECT `name`, `surname`, `email`, `user_id` FROM users
WHERE (surname LIKE '$name%' AND name LIKE '$surname%') OR (surname LIKE
'$surname%' AND name LIKE '$name%') ");
while($run = mysql_fetch_array($query)){
$surname = $run['surname'];
$name = $run['name'];
echo"$surname $name ";
}
?>
I want to make the $value in "search_form_all_2.php" to get the value of the first page that I have in if(isset($_POST['value'])== true && empty($_POST['value']) == false) of 1st page. How can I do this because when running "search_form_all_2.php" I get an erros message:Notice: Undefined index: value
You need to use GET in this case. POST values are only send when a form is submited.
if(isset($_POST['value'])== true && empty($_POST['value']) == false){
echo "<a href='search_form_all_2.php?value=".urlencode($_POST['value'])."'>See more results for </a>";
then on second page you retrieve the GET value
$value = mysql_real_escape_string($_GET['value']);
Be careful, GET values are visible to the user. They are part of a URL. Don't send confidential information.
Another way is to save the value in a COOKIE or in SESSION variable.
setcookie("TestCookie", $_POST['value']);
$value = $_COOKIE["TestCookie"];
BTW empty() always returns boolean value and it already checks if the variable is set, so you only need:
if(!empty($_POST['value'])
In your 1st page, you can pass an argument in the url... example:
echo "<a href='search_form_all_2.php?s=".urlencode($_POST['value'])."'>See more results for </a>";
Then, in your 2nd page, you can call the argument... example:
$value = mysql_real_escape_string($_GET['value']);
PS: You shouldn't be using mysql_* functions. Instead learn mysqli at the very least or PDO.
On search_form_all_2.php you can't access the data value because when you click a link, it is a GET request, not a POST request. I suggest you look up the differences.
However, if you use this to spit out the link:
echo"<a href='search_form_all_2.php?more={$_POST['value']}'>See more results for </a>";
You can then retrieve it with $_GET or $_REQUEST (if you want to be able to use GET or POST) on page 2:
$value = mysql_real_escape_string($_REQUEST['value']);
Related
i have a question regarding passing a php variable in the $_POST knowing that i named my buttons using the same variable because i want the buttons to have unique names.
while($row = mysql_fetch_array($query)){
$friend_id = $row['friend_id'];
$result = mysql_query("SELECT username FROM users WHERE user_id = '$friend_id'");
if (mysql_num_rows($result) > 0) {
$friendname = mysql_result($result,0,"username");
$friendname = sanitize($friendname);
echo '<input type = "submit" id='. $friend_id .' name ='.$friend_id.' class = "member" value ='. $friendname.' /><br>';
}
here where i am trying to pass it but it is not working
print_r($_POST);
if(isset($_POST['name'])){
$signers = mysql_query("SELECT friend_id FROM friends WHERE user_id = $session_user_id ");
$count = mysql_num_rows($signers);
if($count == 0){
echo "<p>you need to add team members</p>";
}
else{
while($row = mysql_fetch_array($signers)){
$signer_id .= $row['friend_id'];
}
echo '<p>'.$signer_id . '</p>';
}
$request = mysql_query("INSERT INTO requests VALUES ('','$user_id','$fid','$fname','$signer_id')");
}
else {
echo '<p> not working </p>';
}
both of those sections are in the same php page
You're not passing a variable around, you're passing a value so this line -
if(isset($_POST["'$friend_id'"])=== true){
needs to be changed to this -
if(isset($_POST['name'])){
The name attribute (along with the value) of each input is what is passed in a POST. You're just checking to see if the name parameter has a value, if it does then you can act on it with other code.
In addition please stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO.
The condition in the second piece of code should be without quotes:
if (isset($_POST[$friend_id])) {...
The part === true isn't necessary in this case, I've removed it.
You should look into predefining any variables you intend to use.
function input_post ($value, $default) {
return isset($_POST[$value]) ? $_POST['value'] : false;
}
Then use the post as so, this would prevent any not set errors
$friend_id = input_post('friend_id');
if ($friend_id) {
// If friend_id is set, do this
}
else {
// If friend_id is false or unset
}
I have a HTML form that i am using to search a database, the form method is GET:
<form method="get" action="">
Then my SQL Query selects from a database using the $_GET values
i run the SQL, then have this function - (http://pastebin.com/J3RL3MxC) - that i run underneath the query
So in total, it looks like:
$sql="SELECT * FROM customer ORDER BY company";
$i=0;
$array = ShowRecords($sql, "customer");
foreach($array["results"] as $ret) {
}
and i echo my results in the foreach loop
this is working fine, however when navigating through the pages that the function creates i loose the $_GET values so i also loose what i have searched for
how can i keep the $_GET values but keep in mind that the $_GET["pagenum"] needs to be removed/changed so the page will change
I have already added this code:
$query_string = '?';
foreach($_GET as $q => $k) {
if($q == 'id' or $q == 'pagenum') {
//
} else {
if($q != '') {
$query_string = '&'.$q.'='.$k;
}
}
}
at the top of my function to try to do what is needed ($_GET["id"] also needs to be removed) but its not keeping the values
What is the best way to keep all $_GET values except the specified ones?
P.S: I know i should be using PDO which i will be as soon as i have this issue sorted, i will then change my code to use PDO
Use http_build_query to build your query string instead of doing it manually:
http://php.net/manual/en/function.http-build-query.php
I would just store all of the request vars in an array and updated it as needed. When ready to output any links just use http_build_query to generate the query string
$request = $_GET;
unset($request['id']);
$request['pagenum'] = 2;
//etc
$query_string = '?' . http_build_query($request);
$id = isset($_GET["id"]) ? $_GET["id"] : NULL;
$pagenum = isset($_GET["pagenum"]) ? $_GET["pagenum"] : NULL;
if($id) {
}
if($pagenum) {
}
I have a webpage with a button on it. When the button it clicked it sends a request to a page with this code on it
$userName = "tdscott";
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$divID = explode('?', $url);
$id = 0;
$id = explode('#',$divID[1])[1];
$func = $divID[2];
$find = mysqli_fetch_array(mysqli_query($con,"SELECT likes FROM status WHERE id='$id'"))['likes'];
if ($func == "addLike")
{
$promoted = $userName . "-";
mysqli_query($con, "UPDATE status SET promotedBy = CONCAT(promotedBy,'$promoted') WHERE id='$id'");
$find++;
mysqli_query($con,"UPDATE status SET likes = '$find' WHERE id='$id'");
echo $find;
}//end if addLike
elseif($func === "removeLike")
{
echo "ERROR";
}//end if removeLike
elseif ($func === "getLikes")
{
echo $find;
}//end if getLikes
mysqli_close($con);
I left of the database connection information. But for some reason when this is called it produces inaccurate results. For example... Sometimes it will put multiple instances of $promoted in the promotedBy field in my table and sometimes it will update other rows in the table that the id does not equal the current $id. I am wondering if somehow it is getting the $id variable mixed up from when I submitted it with a different value before. Is there a way to reset the variables before I call it each time?
Please note: In the if statement, we are only looking at the addLike portion. I included the other just in case it was causing the problem.
unset($id);
Sorry should have done more research.
Please I need your help with my script. I'm puting a link to old news articles in a sidebar and making it clickable. The page it's coming from (header.php) has the GET id in the URL, so the page receiving it also checks for the value of the GET. It displays fine when I click the old news article in the sidebar.
The problem I'm having is that, whenever I want to view the current article on the the About.php page I get Undefined Index id
Please how can I solve this issue, so that my script works well for displaying old articles and also the current news article.
Thanks
about.php
<?php
$id = $_GET['id'];
$past = mysql_query( "SELECT * FROM about WHERE about_id = '".$id."'") or die(mysql_error());
$row = mysql_fetch_array($past);
echo "<h2>";
echo $row1['about_head'];
echo "</h2>";
echo "<p>";
echo $row1['about_content'];
echo "</p>";
?>
Header
<?php
$past = mysql_query("SELECT * FROM about") or die(mysql_error());
while($row = mysql_fetch_array($past))
echo " $row[about_head].<br/>";
?>
When you have this code:
$id = $_GET['id'];
you are retriving an item called "id" from the array called $_GET (which holds all GET parameters). However when this parameter "id" is not present, PHP emits a warning. To get rid of it, replace the line with:
$id = "";
if (isset($_GET["id"])) $id = $_GET["id"];
or shortly:
$id = isset($_GET["id"]) ? $_GET["id"] : "";
which first asks whether the parameter is present, and if it's not, gives an empty string. If you expect the $id variable to be an integer, you might instead want to use zero instead of an empty string:
$id = isset($_GET["id"]) ? (int)$_GET["id"] : 0;
this also casts the passed parameter to "int", so you have a guarantee that it is not a string (possibly containing malicious data).
Something like this should work:
if( array_key_exists( 'id', $_GET ) )
{
//do your code in here
}
else
{
//fallback to scenario in which $_GET['id'] isn't set in the url
}
I am currently using column header's as links that when clicked will sort the results by the column name by adding a get variable to the url. Here is an example:
<a href="
<?php
// Sorts by order id. If already sorted by order id, then it will change the link to sort descending
if(!isset($_GET['sortby']) || $_GET['sortby'] != 'order_id'){
echo $_SERVER['SCRIPT_NAME'] . '?sortby=order_id'; //example: tracker.php?sortby=order_id
} elseif(isset($_GET['sortby']) || $_GET['sortby'] == 'order_id'){
echo $_SERVER['SCRIPT_NAME'] . '?sortby=order_id_desc'; //example: tracker.php?sortby=order_id_desc
}?>
">Order ID</a>
I also have a form where users can enter pick a category from a selectbox and then enter a searchterm. I am using if statements and switch statements to check if the $_GET['sortby'] variable and the $_POST['search_submit'] variable is set and if so, to run a certain sql statement based on the value of the GET variable.
There are 4 different scenarios.
1. Default: If neither sort nor search is set. This one works fine:
if(!isset($_GET['sortby']) && !isset($_POST['search_submit'])){ //Default, If no sort or search is set
$sql = 'SELECT *
FROM orders
ORDER BY order_id DESC';
}
2. If the search is set but the sort is not. This one works fine:
if(isset($_POST['search_submit'])) {
$search_string = ' WHERE ' . $_POST['searchby'] . '= "' . $_POST['search_input'] . '" ';
}
if(!isset($_GET['sortby']) && isset($_POST['search_submit']) ){ //If the search is set but no sort
$sql = "SELECT *
FROM orders"
. $search_string .
"ORDER BY order_id DESC";
}
3. If the sort is set, but the search is not. This one works fine:
if(isset($_GET['sortby']) && !isset($_POST['search_submit'])) { //If the sort is set but no search
switch ($_GET['sortby']) {
case "order_id":
$sql = "SELECT *
FROM orders
ORDER BY order_id ASC";
break;
case "order_id_desc":
$sql = "SELECT *
FROM orders
ORDER BY order_id DESC";
break;
}
}
4. If the search AND sort is set. All 3 of the above if statements work, but the last one is giving me problems.
if(isset($_GET['sortby']) && isset($_POST['search_submit'])) { //If the sort AND search is set
switch ($_GET['sortby']) {
case "order_id":
$sql = "SELECT *
FROM orders"
. $search_string .
"ORDER BY order_id ASC";
break;
case "order_id_desc":
$sql = "SELECT *
FROM orders"
. $search_string .
"ORDER BY order_id DESC";
break;
}
}
What happens is that you can search, but as soon as you click on one of the column headers and it reloads the page with the new GET variable, it will get rid of the current POST variable, thereby showing all results again. I tried to load the current POST variable into a session after the $_POST['search_submit'] isset and then make the last if statement check to see if the session variable is set, but what happens then is that the session is always set and if i try to go back to the homepage, it will keep those search results.
Perhaps I need to destroy the session somewhere? Perhaps there is an overall better approach I could be taking to combining sort and search features?
I would recommend changing the search form from a method="POST" to method="GET" and use just GET for all your requests. If you cannot change your POST requests, you are going to need to POST each request (including sorting), which will require javascript attached to your sort links.
The benefit to using GET is that your users can bookmark specific searches since all the data would be contained in the Query string.
EDIT: Retaining the search strings in subsequent requests:
I would abstract out your sorting code to something like this:
<?php
function write_sortable_header_link( $column_id, $column_name ){
if( ( isset($_GET['sortby']) && $_GET['sortby'] != $column_id ) || !isset($_GET['sortby']) )
$query = "?sortby=$column_id";
else
$query = '?sortby='.$column_id.'_desc';
if( isset($_GET['searchsubmit']) ){
$query .= '&searchsubmit=1';
$query .= '&searchby=' . urlencode( isset($_GET['searchby']) ? $_GET['searchby'] : '' );
$query .= '&search_input=' . urlencode( isset($_GET['search_input']) ? $_GET['search_input'] : '' );
}
$href = $_SERVER['SCRIPT_NAME'] . $query;
echo "<a href='$href'>$column_name</a>";
}
?>
You would then call it like this:
<?php write_sortable_header_link( 'order_id', 'Order Id' ); ?>
It would make sure your sorting URL's contain the correct query string arguments for persistence.
Try to use $_GET only, involving $_POST seems unnecessary.
Not an answer to your question, but just my 0.2
In your situation I usually do the sorting client side in the web browser using javascript. It prevents essentially the same query being run over and over again with only different ORDER BY parameters.
With jquery there are even some very nice plugins that make it pretty easy.
example: http://tablesorter.com/docs/
This is the code I ended up using to make the link rewrite with the sort and search get variables as suggested by dcneiner. I took out the urlencode, the switched & to the '&' sign and made the inline if statement read as just the get variable, since the only way those get variables can be set is if the search_submit is set since they're part of the same form. I also added the '{' and '}' back into the if and else statements. I'm guessing you're using a slightly different way of doing PHP? Do you see anything wrong or unsecure about the changes I made? I wasn't too sure why you did it your way. But thanks again.
function write_sortable_header_link( $column_id, $column_name ){ //Function that creates a link with the search query if needed
if( ($_GET['sortby'] != $column_id) || !isset($_GET['sortby']) ) { //If the GET variable is not the column id of this button or if the GET sortby variable has not been set
$query = "?sortby=$column_id"; //then add this to the end of the url
} else {
$query = '?sortby='.$column_id.'_desc'; //otherwise if the GET variable is the column id of this button, then add the descending code to the end of the variable
}
if(isset($_GET['search_submit']) ){ //If the GET variable search_submit is in the url
$query .= '&search_submit=1'; //then add this to the end of the url string
$query .= '&searchby=' . $_GET['searchby']; //add whatever is currently in the GET searchby to the end of the url string
$query .= '&search_input=' . $_GET['search_input']; //add whatever is currently in the GET search_input to the end of the url string
}
$href = $_SERVER['SCRIPT_NAME'] . $query; //this is the href part of the link
echo "<a href='$href'>$column_name</a>"; //this creates the actual link
}