Pass value from href link to detail page - php

I have a table that shows all the users. I'd like to put a link around the usernames so when you click on a username it takes you to their profile page.
How do I put the username into a href link and pass it to the detail page?
This is all I have at the minute:
if ($allPlayers > 0 ) {
while ($allPlayersItem = mysqli_fetch_assoc($playersQuery)) {
echo "<a href='detailpage.php'>".$allPlayersItem['gamertag']."</a>";
echo "<br>";
}
}

You can add the player's gamertag to a query parameter for example:
echo "<a href='detailpage.php?player={$allPlayersItem['gamertag']}'>".$allPlayersItem['gamertag']."</a>";
Then in detailpage.php you can write:
$player = $_GET['player'] ?? '';
if ($player != '') {
// display player details...
}
Note that if the gamertag value may contain special characters then you should urlencode the value before using it as a parameter i.e.
echo "<a href='detailpage.php?player=" . urlencode($allPlayersItem['gamertag']) . "'>".$allPlayersItem['gamertag']."</a>";

First of all, I suggest you to split the responsability of getting the data from the DB and the rendering the data. The most common approach for that it could be following the MVC pattern.
Something like:
# Controller/PlayerController
final class PlayerController
{
public function index(): Response
{
$players = [/* list of players to display. From the DB, for example*/];
return $this->render('player/index.[blade|twig|php]', $players);
}
}
# Views/player/index.php
<?php foreach ($players as $player): ?>
<a href='detailpage.php'>" . <?= $player['gamertag']?> . "</a><br>"
<?php endforeach ?>
I recommend you to research and learn more about this topic using google, for exmaple.

Related

Passing unknown link variables to a new page

I have a link, an offer page and a destination page. I need to carry the variables from the original link and input them into the links on the offer page.
original link
www.example.com/offerpage.php?offer=1&aff_id=var1&aff_sub=var2
Where you see var1 and var2, those could be any number.
I'm assuming I could do something like this (this is a total guess, just want to make sure I do it correctly).
<?php
if(array_key_exists('aff_id', $_GET)){
$aff_id = $_GET;
}
else {
$aff_id = '1';
}
?>
Then the links on the offer page would be
www.offer.com/index.php?offer=1&aff_id=<?php echo $aff_id; ?>&aff_sub=<?php echo $aff_sub; ?>
and whats the correct format for doing multiples?
This should probably do what you want:
if (!array_key_exists('aff_id', $_GET)) {
$_GET['aff_id'] = 1;
}
echo http_build_query($_GET);
If the query string is offerpage.php?offer=1&aff_id=var1&aff_sub=var2then the output will be:
offer=1&aff_id=var1&aff_sub=var2
And, if the query string doesn't contain aff_id, i.e. offerpage.php?offer=1&aff_sub=var2 then the output will be:
offer=1&aff_sub=var2&aff_id=1

HREF to call a PHP function and pass a variable?

Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4

CodeIgniter: Is there a string contains function?

Form on Page:
<div>
<?php echo form_open('add/player');
echo form_label('First Name','playerFirstName');
echo form_input('playerFirstName','test');
echo "<br />";
echo form_label('Last Name','playerLastName');
echo form_input('playerLastName','test');
echo "<br />";
echo form_submit('addPlayer','Add Player');
echo form_close(); ?>
</div>
Called Controller:
class Add extends CI_Controller
{
public function index()
{
$this->load->view('header');
$this->load->view('add');
$this->load->view('footer');
}
public function Player()
{
if(strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
{
if(basename($_SERVER['HTTP_REFERER']) == basename($_SERVER['PHP_SELF']))
{
$this->load->model('players');
$returnMessage = $this->players->add_player($this->input->post('playerFirstName'), $this->input-post('playerLastName'));
}
}
$this->load->view('header');
$this->load->view('addplayer');
$this->load->view('footer');
}
}
I'm a very green novice when it comes to PHP, CodeIgniter and MySQL (or web coding in general), so if you see any suggestions, please don't hesitate to make them (though the credit will be given to the one who answers my question, not makes my code work the best). However, as to my question, is there a way to see if a string is within another string? My $returnMessage, if successful will have the word successfully in it. What I want to do is if the player is not added, I want to reload the values from the form and put them back. Here's where it gets tricky.
The names are saved in table people_names. In the players table, I save the nameid that is associated with that name in the people_names table. In my add_player function, I check to see if the names are in the table, if they aren't I add them, then I add the player to the players table with the appropriate ids. Because of this, I'm not sure form_validation would be able to be used or not. If it were, please let me know.
So what I want to do is check the $returnMessage and if it doesn't contain successfully, then I want to add the values back to the fields. However, I'm not finding a function where I can see if a string is inside of another string. I see string compares and substring functions, but no string contains. Any ideas? Thanks.
Use native PHP's strpos: http://php.net/manual/en/function.strpos.php
Cheers
http://php.net/manual/en/function.strpos.php
if (strpos($returnMessage,'successfully') !== false) {
echo 'true';
}

Removing article with ID from URL

Im building this blogg site and finally got everything considering uploading multiple pictures to one news article done.
Now my second step is to remove an article with following pictures to it.
Everything is set in the database so all i need is an ID from the news article.
When i press remove button on a article it shows the ID up in the URL... Im wondering how to get the specifik ID int from the URL and IF there is an smarter approach. It must be OOP and objectoriented apporach.
Code looks like this:
This is the looping out each article and notice $current_id that i put into a button to show in the url when its pressed
public function doOutputArticles($newsList, $pictureList)
{
$result = '';
foreach($newsList as $news)
{
$result .= '<ul>';
$current_id = $news->dbNewsID;
$result .= '<li class="bloggNewsHeader">'.$news->dbHeader.'</li>';
$result .= '<li class="bloggNews">'.$news->dbNews.'</li>';
$result .= '<li class="bloggNewsDate">'.$news->dbNewsDate.'</li>';
foreach($pictureList as $pic)
{
if($pic->dbNewsID == $current_id)
{
$result .= '<li class="bloggNewsPicID">'.$pic->dbPictureID.'</li>';
$result .= '<img class="bloggNewsPic" src="./images/'.$pic->dbPicture.'"alt="some_text">';
}
}
$result .= "
<form id='' method='get'>
<input type='hidden' name='$current_id'/>
<input type='submit' name='removeArticle' value='Ta bort inlägg' />
</form>";
$result .= '</ul>';
}
return "<div id='filesLoaded'>". $result ."</div>";
}
`
After this is done, i press a button to remove specific article and then the ID shows in the URL, now this method is meant to GET the specific INT/NUMBER ID in the URL but HOW?
public function GetSelectedID()
{
$ID = $_GET[self::$articleId];
echo $ID;
if(is_null($ID) || empty($ID))
{
return null;
}
else
{
echo $ID;
return $ID;
}
}
`
Kind regards /Haris
You don't really need a form, a simple link would do and be clearer. You should be using a different endpoint for deletion rather than looking for "removeArticle". This would be more OO since it would pave the path towards creating a specific Action Controller for each function rather than having one sprawling endpoint full of conditionals. Then you can have a consistent parameter (ideally within the URL path) of something like "articleId" that you are extracting from the URL. You'd also ideally want to redirect to the listing page upon completion to keep functionality focused in each method and also as a practice to avoid double posting issues (though this example is idempotent so it wouldn't be overly important).

php pagination using class

hello everyone plz help me out with this script.
I am calling my pages in this way in main page
if(isset($_GET['page'])=='view_user' && $_GET['page']=='view_user')include("user/crud_user.php");
i have user class in which i am doing pagination
$self = $_SERVER['PHP_SELF'];
if($this->openPage<=0) {
$next = 2;
}
else {
$next = $this->openPage+1;
}
$prev = $this->openPage-1;
$last = $this->pages;
if($this->openPage > 1) {
echo "<a href=$self?page=1>First</a>&nbsp ";
echo "<a href=$self?page=$prev>Prev</a>&nbsp ";
}
The url of the page which is using this class is lie this
admin.php?page=view_user
Now i can get pagination no according to the records but when i click on no it rather take me to admin.php?page=3 because of self . I want to stick to that page for showing the result . I tried in this way also $self="admin.php?page=view_user";but no luck . please help me out
To use one variable for serving two different purposes is quite unusual idea.
Let me suggest you to use 2 different variables, one to designate included page and another to point to the actual page in pagination.
Hope this helps.
do
if(isset($_GET['page']) && $_GET['page'] == 'view_user')
{
include("user/crud_user.php");
exit;
}
because of many reasons.
for pagination try the following: http://www.catchmyfame.com/2007/07/28/finally-the-simple-pagination-class/

Categories