Removing article with ID from URL - php

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).

Related

Pass value from href link to detail page

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.

Updating URL for parsing XML in PHP

I am trying to figure out how to update an URL that I am using to parse the XML (using simplexml_load_file()).
There is a button that has a $productid that is assigned to it by the user when they add their shortcode [show_cart_button productid=#].
//code for the button input that gets called
function print_add_cart_button($productid, $atts = array()) {
//some other form code for the button
$replacement .= '<input type="hidden" name"cart_product" value"' . $productid . '"/>';
return $replacement;
}
This is the function I am using to display and call the product information:
function show_shopping_cart_handler($atts) {
if (isset($_POST['cart_product'])) {
$id = "&PRODUCTID=" . $_POST['cart_product'];
// uses the input name from the button
}
$url = "https://secure.bmtmicro.com/cart?CID=2/WP" . $id;
$xml = simplexml_load_file($url) or die("error.");
foreach ($xml->producttable->row as $product) {
$output .= '<span>' . $product->productname . '</span>';
}
return $output;
}
The way the URL will work properly is to have a &PRODUCTID=(product#) added to the end of the URL. For example, if you click two different buttons, the URL should look like this: https://secure.bmtmicro.com/cart?CID=2/WP&PRODUCTID=1&PRODUCTID=2 (obviously 1 and 2 will need to display the buttons $productid number).
As you should be able to see from my code above, every time a button gets clicked, it just rewrites the URL and displays that one product, instead of adding a new one to the list. I tried to set the simplexml_load_file() into a foreach(), but that would not display any products when the button was clicked. Does anyone know a way I could get that URL to update/work properly?
Everytime
if (isset($_POST['cart_product'])) {
$id = "&PRODUCTID=" . $_POST['cart_product'];
// uses the input name from the button
}
Is called, it's overwriting $id. You need to get any existing values for the url.
You'll have to get all of the current values ($_GET['cart_productions']), throw them into an array, grab the new post, add it to the array and add all of them to them the url using http_build_query().

Quiz Approach in Codeigniter Gone wrong

Following this Question, im also creating an quiz approach in Codeigniter. here is the snippet of my code.
Controller :
function quiz(){
$this->load->model('belajar_model');
$data['data']=$this->belajar_model->quiz();
$this->load->view('quiz',$data);
}
function getQuiz($id){
$this->load->model('belajar_model');
$data['data']=$this->belajar_model->getQuiz($id);
$this->load->view('quiz',$data);
$this->load->model('belajar_model');
$data['data']=$this->belajar_model->quiz();
if($this->input->post()){
$jawab = $this->belajar_model->getQuiz($id);
$soal = $this->belajar_model->getQuiz($id);
if($jawab['benar']==$this->input->post('jawab')){
}
$data['jawab'] = $soal;
$data['next'] = $id+1;
$this->load->view('quiz', $data);
}
else{
$jawab = $this->belajar_model->getQuiz(1);
$data['soal'] = $soal;
$data['next'] = 2;
$this->load->view('quiz', $data);
}
}
and here is the model :
function quiz(){
//$this->db->where('id = 1');
$query = $this->db-> get('kuis');
return $query->result_array();
}
function getQuiz($data){
$this->db->where('id',$data);
$query = $this->db-> get('kuis');
return $query->result_array();
}
and here is the snippet of the view (my friend did the view) :
<h3>Pilihlah salah satu jawaban yang benar!</h3>
<?php foreach ($data as $list){
echo"<p>".$list['soal']."</p>";
echo"<table>
<tr><td><label><input type='radio' name='jawab' value='a'>".$list['ansA']."</label></td></tr>
<tr><td><label><input type='radio' name='jawab' value='b'>".$list['ansB']."</label></td></tr>
<tr><td><label><input type='radio' name='jawab' value='c'>".$list['ansC']."</label></td></tr>
<tr><td><label><input type='radio' name='jawab' value='d'>".$list['ansD']."</label></td></tr>
";
}?>
<tr><td><button type='submit' >Submit</button><td></tr><table>
after trying to implement it, with some modification make it work on the page, the page is jumbled like this, it's jumbled because the question and the answer is not displayed correctly. it also didn't receive the inputs from the quiz and there are some errors displayed.
my question is : where did it go wrong? is it from the view or either the models/controller not right? FYI, some of the attributes are written on my native language(Indonesian) to fulfill my studies, to make the code understandable to both my friend and my lecturer.
thanks for answering! it'll means a lot for me to get the webpage work because it's my final project and i didn't adapt enough (yet) in php and codeigniter.
Before going further, you should first clean your code to make sure you don't have any unforseable side effects:
In your getQuiz() method in your controller, you load your model two times and you also render the view twice. Once at the beginning and once after you checked the presence of $this->input->post().
PS for the mods: I know this is more comment material, but I can't comment yet.

How do I take MySQL data i have pulled with PHP and use it in another page without creating millions of pages

So i have a exercise site in the making and at the moment there are hundreds of exercises displayed. I dont have a problem pulling the data from the MySQL database. My issue is being able to view each exercise on a separate page. At the moment all of the exercises are pulled in using this function:
//Category 1 is biceps
$cat = 1;
//$category is used for the case statement, to allow the form to submit and refresh to the case statement that it is on, for each instance of the function.
$category = 'biceps';
show_exercise($cat, $category);
here is the function itself:
//Show exercises based on exercise category
function show_exercise($cat, $category)
{
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$query = "SELECT * FROM exercises WHERE cat_id='$cat' ";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result))
{
$output[] = '<div class="item">
<h2>'. $row['name'] .'</h2>
<img src="'. $row['image'] .'" alt="'. $row['name'] .'" />
<input class="button" type="submit" name="add" value="add" />
<input class="button" type="submit" name="view" value="view"/>
</div>';
}
echo join('', $output);
}
now this just pulls all of my different exercises onto one page as an array. I want to be able to select and view each individual exercise but i don't know how. One way would be to create a page for every exercise, but i have hundreds. The buttons in the code above aren't being used, but the idea is that when someone clicks the 'view' button, they are taken to a separate page of the exercise where they can read more detail. All of the data that has been used in the code above from the database can be used on the individual exercise pages.
My pages are managed with a switch statement, i thought i'd mention this as it might change the answer. Here is the switch statement i'm using:
// Validate what page to show:
if(isset($_GET['p']))
{
$p = $_GET['p'];
}
elseif(isset($_POST['p']))
{
// Forms
$p = $_POST['p'];
}
else
{
$p = NULL;
}
// Determine what page to display:
switch ($p)
{
case 'contact' :
$page = 'contact.php';
$page_title = 'Contact Us';
break;
case 'exercises' :
$page = 'exercises.php';
$page_title = 'Exercises';
break;
case 'routines' :
$page = 'routines.php';
$page_title = 'Your Routines';
break;
case 'arms' :
$page = 'arms.php';
$page_title = 'arms routine';
break;
}
this statement goes on with more pages. I dont know if im making this sound harder than what it is. I'll be ready to comment if there are any questions.
I want to be able to select and view each individual exercise but i don't know how. One way would be to create a page for every exercise, but i have hundreds.
What do you mean by "page"?
Anyway, you actually don't need more than one PHP script because it can pass query string parameters to itself. But it is usually easier to maintain if you distribute it over several pages. It looks like you're already doing this. Good.
For example you can add a parameter called "itemid" that is only used when you access the "view" page.
If the view-page is implemented in another script (I'll call this "page script") that is included from your mother-script, I recommend that all your "page scripts" implement the same function called i.e. generate_page($query_string) that is called with the query-string from the mother-script. If you used OOP, each page could be a class implementing the same interface. But I'm trying to suggest something similar to what you're already doing.
So something like this for your mother-page:
<?php
$pagename = $_GET["page"];
$allowed_pages = ["view", "contact"];
if (!in_array($pagename,$allowed_pages)) exit("Invalid page!");
require($page . ".php");
generate_page($_GET);
?>
view.php
<?php
function generate_page($arguments) {
if (!isset($arguments["item"])) exit("Item needs to be specified!");
// Do SQL query and view THIS item. (remember to guard against SQL injection!)
// you can do this by using a different WHERE clause
}
?>
Now view can show what it wants. The other pages don't have to use the $arguments parameter if they don't want to.
You could change your link to something like <a href="index.php?p=view&item={$row['itemid']}">.

Single dynamic values submitted through one form

I am using Jquery UI Selectable. The user has the option to dynamically add new list items to the original setup.
I would like to include a 'clear' button that will give the user the ability to clear each individual item they created by clicking on an X input submit (img).
HTML (php)
if ($this->session->userdata('inactivefilter') == true) {
$inactivefilter = $this->session->userdata('inactivefilter');
$i=0;
foreach ($inactivefilter as $filter)
{
$filterdash = implode('-', explode(' ', $filter));
echo "<li class='ui-state-default' id='$filterdash'>$filter</li>";
echo "<div id=clear>
<form method='POST' action='".base_url()."main/clear_filter'>
<input type='image' name='filtervalue' value='$i' src='".base_url()."img/board/icons/clear.png'></input>
</form>
</div>";
$i++;
}
}
This is where the list is created. specifically the clear_filter action form.
Clear_filter currently 'attempts' to grab the value of '$i' but I don't know how to pass that correctly.
here is the controller:
public function clear_filter()
{
$i = $_POST['filtervalue'];
$this->thread_model->clear_filter($i);
}
I'll omit the clear_filter model due to its irrelevance to the problem.
Essentially, I just need $i to be picked up based on whatever value is clicked on in the dynamic form on the actual page.
Any help would be appreciated!
Well, it seems like I just had things a bit backwards.
The code was more or less correct.
For Codeigniter, you catch the passed input value=$i by using the name ="filtervalue"
Change the controller code to :
$i = $this->input->post('filtervalue');
and $i is set to whatever value was clicked on.

Categories