Use each row as a get variable for include? - php

I'm working on a notification system and I want to use a kind of platform I've built for viewing the profiles with the ID's found in the database 'friendships' (which keeps track of the sender, recipient and date of a friendship request)
I've been trying to find a way to include this profile module (which uses a $_GET variable to fetch user information), for every row, and I need a way to set a variable for each row and then immediately include that module using the ID, but when I try this, only one appears instead of the 4 requests I have.
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='item friend'>";
$_GET['user'] = $row['sender_id'];
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/profile/module.php";
include_once($path);
echo "</div>";
}
I am aware that setting a variable like this is wrong, but I don't have a clue about how I would go about doing this.
UPDATE: After applying Gautum Rai's code, the correct about of divs are showing, but they appear empty.
This is the HTML that generates once I use the original code (which echoes the info of one person).
<div class="item friend">
<div class="profile">
<img class="pic" title="Taswell: Omikron Player" style="background-image: url("/img/badges/omikron.png") !important;" src="/uploads/profile19.jpg?" 2147213591="">
<p class="username">MyNameIsKnuckles<img class="medal" src="/img/medals/dragonfly.png" title="Queen Of The Hive"></p><br>
<p class="bio playing">nothin. just waiting for the next omikron build.</p>
</div>
Note: I already asked something similar to this, but I got comments telling me to join the variables or not use a while loop to fetch assoc. Please provide a relevant answer, I would really appreciate that.

You are susing include_once which is explicit including the file once, and your filename is always the same. Try only using include.

use file_get_contents() instead of include_once,
your code should be as :
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='item friend'>";
$_GET['user'] = $row['sender_id'];
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/profile/module.php";
file_get_contents($path); // want to print contents just echo it
echo "</div>";
}

There is an awful lot wrong here.
With the exception of $_SESSION, you should never write to superglobals.
You are calling include_once multiple times within a loop - this is wrong. I suspect you really want the content of the incldued file to be processed for each loop iteration - while include (or require) would suffice, this is also wrong. You are making very innefficient use of resources (and probably not separating your application logic and html). A much more correct way to solve the problem would be to define a function in your include file and call that with $row['sender_id'] as an argument.

Related

Is there a way to execute required php file once per session?

I am new to php and have just written a basic index.php that will display family tree information for an individual based on input id.
The index.php includes a file called "xml-people-list.php" which loads the information from the family tree and creates a sorted list of people.
My problem is that every time you click on a person to display their details, the included php is reloaded which causes the read from file and creation of sorted list to happen again.
Is there a way to only run this code once per session to avoid multiple loads?
I tried to look at session variables but wasn't sure if they would help or how to use them in this case or if there is another way?
Contents of "xml-people-list.php:
<?php require 'xml-load-person.php';
if (file_exists('people.xml'))
{
$people = simplexml_load_file('people.xml');
foreach ($people->person as $person)
{
$person_list[(string)$person['ID']] = strtoupper($person->FamilyName) . ", " . $person->GivenNames;
}
asort($person_list);
}
else
{
exit('Failed to open people.xml.');
}
?>
Thanks for any help!
Yes, you could use session variables. If you wanted to only parse the list once per visitor, and then "cache" the result into a session variable, you could do something like this (for a simple example):
if (!empty($_SESSION['person_list'])) {
// Here we fetch and decode the the ready list from a session variable, if it's defined:
$person_list = json_decode($_SESSION['person_list']);
}
// Otherwise we load it:
else {
require 'xml-load-person.php';
if (file_exists('people.xml'))
{
$people = simplexml_load_file('people.xml');
foreach ($people->person as $person)
{
$person_list[(string)$person['ID']] = strtoupper($person->FamilyName) . ", " . $person->GivenNames;
}
asort($person_list);
// Here we assign the ready list to a session variable (as a JSON string):
$person_list = json_encode($person_list);
$_SESSION['person_list'] = $person_list;
// Here we revert the JSON-encoded (originally SimpleXML) object into a stdClass object.
$person_list = json_decode($person_list);
}
else
{
exit('Failed to open people.xml.');
}
}
You will need to call session_start() in your file (either this one, or any other file including it, but importantly before any output is sent to the browser). Homework: Read up on sessions in PHP.
Update: Since SimpleXML objects can't be serialized, and since adding an object to $_SESSION causes serialization, I've updated the answer to json_encode/decode the object. Yes there's a bit of processing, but that'd be the case with the default serialization as well, and json_en/decode is fairly light-weight. Certainly heaps lighter than parsing XML on each page load!
Be aware that the returned object will be a stdClass object, not a SimpleXML object. I'm assuming it won't be a problem in your use case.
Maybe try require_once() function
1) First of all, try to see if your buttons are anchor tags then be sure that the href attribute is directing to # example: <a href="#">
2) try to use include_once instead of requiring
3) if you tried this and these couple solutions didn't work for you you can send the id of a person using the global $_GET variable
//this should be you URL http://localhost/projectname/index.php?person_id=1
// your href of each person should appoint to their URL
// <a href="index.php?person_id=1">
you can use this $_GET['person_id'] and store it into a variable so it will give you the id of person.

How to read a blob in Base64 using PHP and MySQL?

I am a newb with 6 months experience, self-taught via StackEx/books/etc. Created a pretty decent website with login/register and storing some info via mySQL. I have been through every single BLOB post here and I have some decent output.
I think I, like most newbs, know enough to be dangerous, don't have the greatest foundation laid out so when it gets to serious understanding of built-in functions, arrays and passing arguments we can lose the flow and I basically think I have dug a hole by using includes to call some navbar so that I can't just use a header to output the damn image as I echo the user name after login so it has already outputted lines and it will be a monster to undo. Three levels of nav, unauthenticated, authenticated and admin.
The database connection and write to/read from is OK. I can store the BLOB and I can even read it back and store the array in a variable and then debug see the binary but I can't get it to display on an HTML page.
Here is the fun:
$stmt = $dbc2->query("SELECT * FROM equip1");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = $row['equipname1'];
$desc = $row['equipdesc1'];
$img = $row['equipimg1'];
}
<div class="col-lg-12">
<h1><?php echo $name ?></h1>
<p><?php echo $desc ?></p>
<pre>
<?php print_r($img); ?>
</pre>
<?php echo "<img src='data:image/jpeg;base64," . base64_encode( $img ) . "' />"; ?>
</div>
$dbc2 connects
equip1 table is two simple varchar cols, one BLOB col.
$name and $desc echo out ok, the $img displays broken link.
I check the array via pre code and is matching, per what is stored in dB during upload.
From what I have read and gone through, seems like you can't do this at same time unless via data URI which I have done but still broken link. Not making sense to me at all. I try the header and of course output already started but I can see also outputs the binary.
Here is screenshot of the URI method:
Since both methods "seem" to get into and out of the dB but do not display I'm going round in circles. Please help me out to display the image on an html page. I would like to echo it anywhere and then I can just style the page after that. Thanks!
Try Like this
<?php echo '<img src="data:image/png;base64,'.base64_encode($img).'">';?>
Uhh NEVER MIND. Never thought reading someones answer would make for "fresheyes". I noticed I was encoding but I already encoded it when I stored it. Mea culpa. DOH! :)

XML as an alternative to if else

My site has a large number of products in the database. I want to add a product sheet for each product but the database has no set "slot" for it. So I was thinking of writing a php code into the template which checks the part number and use this to load the correct url for the product sheet as a link. For Example
<?php
if (strpos($product_sku,'KE15000/12') !== false) {
$factsheetimage_urlZ='/images/FactsheetBTN.png';
$factsheetweblink_url="images/factSheetKE15000/12.pdf";
} else if (strpos($product_sku,'KE2000/12') !== false) {
$factsheetimage_urlZ='/images/FactsheetBTN.png';
$factsheetweblink_url="images/factSheetKE20000/12.pdf";
} else {
$factsheetimage_urlZ='/images/blank.png';
}
?>
<div>
<a href="<?php echo $factsheetweblink_url;?>">
<img src="<?php echo $factsheetimage_urlZ;?>"></a>
</div>
At moment I'm using if else statements (I'm pretty new to PHP) and I was wondering if there's a way to check the $product_SKU against an XML document to auto load the correct link rather than doing around 300 if else statements. ($product_SKU is the unique product code loaded on each page)
There are a few ways to go about it.
If the $factsheetweblink_url can be generated base on the $product_sku in some programatic way, that would probably be my first preference. eg. $factsheetweblink_url = "images/factSheet{$product_sku}.pdf";
Secondly, adding this column to the database would be a the best option if possible.
Otherwise, the lookup table you mention is certainly possible, XML is one option. If you're writing it by hand, or it needs to be written by a non-technical person would be some considerations for choosing a format. If it's just you, I'd probably use a simpler format (even a plain PHP array).
A simple example of this type of mapping as a PHP array might look like:
sku_url_map.php:
<?php
return [
'KE15000/12' => 'images/factSheetKE15000/12.pdf',
'KE20000/12' => 'images/factSheetKE20000/12.pdf',
];
product_page.php:
<?php
$sku_url_map = require 'sku_url_map.php';
// ...
if (isset($sku_url_map[$product_sku])) {
$factsheetweblink_url = $sku_url_map[$product_sku];
}
of course, more complex structures can be used if it's more that a simple 1:1 mapping.

delete a row from my sql table

I'm still new to php and working my way around it but i'm stuck at the following piece:
code for deleting a row in my table
i have a link directing towards this piece of my script. i run through the first half just fine but when i press on submit and try to execute my delete query it won't go to my second if statement let alone get to the delete query.
$pgd is the page id
my hunch is there is problem with the action in the form i'm building after my while statement
forgive me for the wierd formatting of my msg but its 2am and very tired, i promise to format my questions in the future better! any help is appreciated
edit: ok other then the obvious mistake of missing method=post #.#;
edit:
hey everyone,
first of all, i'd like to thank everyone for their response.
i just started coding in php last weekend so forgive my messy codes. the code is still running locally and my main goal was to finish the functions and then work on securing my code.
now back to the issue, i'm sorry if i was vague about my problem. i'll try to reiterate it.
my issue isn´t selecting an item i want to delete, the issue is that it won´t get to the 2nd if statement.
Re-edit:
this time with my current code:
if($_GET['delete'] == "y")
{
//content hier verwijderen
$sqlcont1="SELECT * FROM content where id ='".$_GET['id']."'";
echo $sqlcont1;
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while($rowcont1= mysql_fetch_array($resultcont1)){
echo '<form class="niceforms" action="?pg='.$pgd.'&delete=y&remove=y&id='.$_GET['id'].'" method="post">';
echo '<h1>'.$rowcont1['Titel'].'</h1>';
echo '<p>'.$rowcont1['Content'].'</p>';
echo '<input type="submit" value="Delete article">';
echo '</form>';
}
if($_GET['remove']=="y"){
echo 'rararara';
$id=$_GET['id'];
$sqlrem="DELETE FROM content WHERE id="$id;
echo $sqlrem;
mysql_query($sqlrem);
}
}
echoing $sqlrem gives me the following now:
DELETE FROM content WHERE id=8
that being my current code, i get in to the second IF statement but now to get it to delete!
#everyone:
ok maybe thinking out loud or following my steps worked but the code works, i know its very messy and it needs fine tuning. i'd like to thank everyone for their help and feedback. i'm liking this and you'll probably see me alot more often with nubby questions and messy codes with no escapes :(
First of all, you have SQL injection vulnerability in your script. Anyone can add some string that will be attached to your query, possibly altering it in a way that can make almost anything with the data from your database.
Escape your values with one of anti-SQL-injection methods. Read more for example on php.net/manual/en/function.mysql-query.php
To the point...
Your deletion code will be executed only if you invoke URL with two params (remove and delete set to y. That means your URL should look similar to something.php?delete=y&remove=y. Maybe you just did not spot it.
Please give details about any errors that occured and tell me whether the above mentioned solution helped.
mysql_fetch_array() returns an array
your while statement acts as an if, and does not iterate thru the array returned as you think it does
you need something like
$all_rows = mysql_fetch_array($result);
foreach ($all_rows as $row) {
$sql = "delete from table where id = " . $row['id'];
}
It looks to me like you're mixing two forms together here: you're wanting to see if you went to the delete row form (the first few lines), and you're trying to present the delete row form (the while loop.) I would break these two things apart. Have a page that simply displays your forms for row deletes, and another page that processes those requests. And another page that brings you to the delete rows page.
For now, just echo all the values you're expecting to receive in $_GET[] and see if they are what you expect them to be.
You have a lot of problems in that script alone, so just to make things easier (considering you uploaded a pic), put an
echo $sqlrem;
in your second if statement, see if the query is displayed. If not, it means it doesn't even get to that part of code, if it gets displayed, copy it and run it in phpmyadmin. That should output a more coherent error message. Tell us what that is and we'll work it through.
I also noticed that your DELETE SQL query might have an issue. If your $pgd' id is a integer, you shouldn't include the ' single quote, that is for string only.
**Correction**
$sqlrem = "DELETE FROM content WHERE id = " . controw1['id'];
EDIT
Anyway, just to help out everyone, I typed out his code for easier viewing.
I think his error is $rowcont1['Tilel'] --> that might caused PHP to have an error because that column doesn't exist. I assumed, it should be `Title' causing an typo error.
if(_$GET['delete'] == "y") {
$sqlcont1 = "SELECT * FROM content where id ='" . $_GET['id'] . "'";
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while ($rowcont1 = mysql_fetch_array($resultcont1)) {
echo '<form class = "niceforms" action = "?pg=' .$pgd . '&delete=y&remove=y">';
echo '<h1>' . $rowcont1['Title'] . '<h1>'; // <-- error here
echo '<p>' . $rowcont1['Content'] . '</p>';
echo '<input type = "submit" value = "Delete article">';
echo '</form>';
}
if ($_GET['remove'] == "y"){
$sqlrem = "DELETE FROM content WHERE id = " . $rowcont1['id'];
mysql_query ($sqlrem);
}
}

Fetch database information on a new page without using new documents

I'm working on a page where I've listed some entries from a database. Although, because the width of the page is too small to fit more on it (I'm one of those people that wants it to look good on all resolutions), I'm basically only going to be able to fit one row of text on the main page.
So, I've thought of one simple idea - which is to link these database entries to a new page which would contain the information about an entry. The problem is that I actually don't know how to go about doing this. What I can't figure out is how I use the PHP code to link to a new page without using any new documents, but rather just gets information from the database onto a new page. This is probably really basic stuff, but I really can't figure this out. And my explanation was probably a bit complicated.
Here is an example of what I basically want to accomplish:
http://vgmdb.net/db/collection.php?do=browse&ltr=A&field=&perpage=30
They are not using new documents for every user, they are taking it from the database. Which is exactly what I want to do. Again, this is probably a really simple process, but I'm so new to SQL and PHP coding, so go easy on me, heh.
Thanks!
<?php
// if it is a user page requested
if ($_GET['page'] == 'user') {
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// db call to display user WHERE id = $_GET['id']
$t = mysql_fetch_assoc( SELECT_QUERY );
echo '<h1>' . $t['title'] . '</h1>';
echo '<p>' . $t['text'] . '</p>';
} else {
echo "There isn't such a user".
}
}
// normal page logic goes here
else {
// list entries with links to them
while ($t = mysql_fetch_assoc( SELECT_QUERY )) {
echo '<a href="/index.php?page=user&id='. $t['id'] .'">';
echo $t['title'] . '</a><br />';
}
}
?>
And your links should look like: /index.php?page=user&id=56
Note: You can place your whole user page logic into a new file, like user.php, and include it from the index.php, if it turns out that it it a user page request.
Nisto, it sounds like you have some PHP output issues to contend with first. But the link you included had some code in addition to just a query that allows it to be sorted alphabetically, etc.
This could help you accomplish that task:
www.datatables.net
In a nutshell, you use PHP to dynamically build a table in proper table format. Then you apply datatables via Jquery which will automatically style, sort, filter, and order the table according to the instructions you give it. That's how they get so much data into the screen and page it without reloading the page.
Good luck.
Are you referring to creating pagination links? E.g.:
If so, then try Pagination - what it is and how to do it for a good walkthrough of how to paginate database table rows using PHP.

Categories