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
Related
I have a function to process info from a database. This is called multiple times in a page. And I don't want to query the database every time. So I put the query outside. If I do that, the function doesn't work. I know this can be done because, there was a similar question somewhere in SO. But that addressed a different situation. I don't know what is wrong here. Any help will be greatly appreciated.
If I put all this code into a separate test file including the conn file and query, it works. But in my main page, where I have the functions.php included first, then conn.php and then the query and then the display code called by js fadein event, the $result refuses to work inside the function
EDIT : This code has been cleaned up as per comments received (globals replaced with variables passed to the function and variable names rationalised)
function total($item,$result,$val){
global $totRate;
while($getRates=$result->fetch_assoc()){
$gotItem= strtolower(preg_replace('/[^(\x20-\x7F)]*/',"",$getRates['item']));
$gotItem=str_replace(array("_"," ","/"),"",$gotItem);
if($item==$gotItem){
$rate= $getRates['rate'];
$totRate=$val*$rate;
return $totRate;
}
}
}
The Result Call PHP file
$query = "SELECT * FROM rates ORDER BY item";
$result = $orderdb->query($query)
if (isset($_POST[$itemname]) && !empty($_POST[$itemname])) {
$val=$_POST[$itemname];
total($itemname);
echo $totprate;
} else {
echo "0";
}
I am writing this with the assumption that your SQL is working but are having problems displaying what you want - this may help. The code below saves your $result variable from your query and then passes it into the total function as a second parameter. Previously you were returning $totprate from total but you were not saving it anywhere - it is now saved to the $totprate variable.
Note: I cannot see $orderdb anywhere in your code, I'm assuming you have that in your file and that it is working.
function total($item, $result){
global $val;
global $pid;
global $pitem;
global $prate;
global $totprate;
global $gotitem;
global $getratess;
// global variable for $result removed so it doesn't overwrite variable passed to function
while($getratess=$result->fetch_assoc()){
$gotitem= strtolower(preg_replace('/[^(\x20-\x7F)]*/',"",$getratess['item']));
$gotitem=str_replace(array("_"," ","/"),"",$gotitem);
if ($item==$gotitem) {
$pid=$getratess['id'];
$pitem= $getratess['item'];
$prate= $getratess['rate'];
$totprate=$val*$prate;
return $totprate;
}
}
}
$query = "SELECT * FROM rates ORDER BY item";
$result = $orderdb->query($query);
if (isset($_POST[$itemname]) && !empty($_POST[$itemname])) {
$val=$_POST[$itemname];
$totprate = total($val, $result); // pass itemname as first parameter and result array as second parameter and save it to the $totprate variable
echo $totprate;
} else {
echo "0";
}
Let me know if this helps.
I'm new in programming and especially with php and MySQL. I have to create dynamic web site for homework. My problem is with the function below. I want it to return int value of tag by given tag name (string). But in my case the function returns every time '1'. Can anyone help me to solve this problem, thanks.
public function getTagIdByName(string $tagName) : int
{
$statement = self::$db->prepare("SELECT tags.id FROM tags WHERE tags.name = ? ");
$statement->bind_param("s", $tagName);
$result = $statement->execute();
return $result;
}
The problem is that you're returning the result of execute(), but that function doesn't actually give you your query result. You need to fetch results after making sure the execution was successful.
//don't forget to error-check before using query results
$statement->execute() or die($statement->error);
$result = $statement->get_result(); //retrieve results for processing
if(!$result->num_rows) return null;//if the id was not found in the DB
else return $result->fetch_assoc()['id'];
You can achieve easily with
$data = $result->fetch_assoc();
return $data['id']; // you can change with which you want to return with field name
And whichever you can use your returned values.
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");
Today I have looked all over the internet for a good answer. I almost got the answer from this site but that solution didn't work.
Here is what I need to do:
In the database there is a token stored that is going to be used for qr codes. I have already made something to generate the qr code when hardcoded:
$token_qr = "a86ad6352e939eea67da45b8731c3a8d62dcas1r";
$url_qr = some url;
$qr_code = array(
"token" => $token_qr,
"url" => $url_qr
); // end array
$qr_code_encoded = json_encode($qr_code, JSON_UNESCAPED_SLASHES);
$smarty->assign('qr_code_encoded', base64_encode($qr_code_encoded));
The base64 string is put in a url so the qr image can be generated.
Now I need to make it dynamically, the url is always the same but the token is always different. In the model where all the database statements are present I made this:
Class Webservices {
public function GetToken($token) {
$pdo = Database::Get();
$query = "SELECT `site__webservice`.* FROM `site__webservice` WHERE `token` = :token"; // SQL select statement
$params = array(":token" => $token); // bind params
$result = $pdo->Select($query, $params); // run query
// fetch token
if($result) {
$row = PDO::FETCH_ASSOC($result);
return $row[$token];
} else {
return false;
}
}
}
With this function I try to get the token from the database and store this in the $token_qr variable which stand in the controller. To call this I use this:
$webservices = new Webservices();
$token_qr = $webservices->GetToken($token);
The output of this function is now always false. Is there something wrong with my statement or is it in the loop that I created?
Maybe it is something really easy but I can't see the problem and find a solution for it. Thanks in advance for the response!
You need fetch the result before return, use fetch() or fetchAll(). Seems Select() works likes pdo execute() so it's return PDOStatment, fetch it to get the results.
if($result) {
$row = $result->fetchAll(PDO::FETCH_ASSOC);
return $row;
hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>