Show Posts from Only One User - php

hello I have this table in my database called posts:
1-id 2-poster 3-Title 4-date 5-hour 6-imagem 7-desc
then I created a post:
id - 1 poster - Gary Title- What is the concept of machine learning?
date - 2021/05/19 hour - 4:32 PM imagem
-https://www.iberdrola.com/wcorp/gc/prod/pt_BR/comunicacion/machine_learning_mult_1_res/machine_learning_746x419.jpg
desc-Machine learning (in English, machine learning) is a method of
data analysis that automates the construction of analytical models. It
is a branch of artificial intelligence based on the idea that systems
can learn from data, identify patterns and make decisions with minimal
human intervention.
then I created a php file called Index.html that does an encoding in Pdo:
<?php
include_once 'con.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<?php
$result_msg_cont = "SELECT * FROM posts ORDER BY id Desc";
$resultado_msg_cont = $conn->prepare($result_msg_cont);
$resultado_msg_cont->execute();
while ($row_msg_cont = $resultado_msg_cont->fetch(PDO::FETCH_ASSOC)) {
$post_id = $row_msg_cont['poster'];
$Post_Title = $row_msg_cont['Title'];
$data = $row_msg_cont['date'];
$hora = $row_msg_cont['hour'];
$desc = $row_msg_cont['desc'];
$imagem = $row_msg_cont['imagem'];
echo "<br><p> Posted in " . $data . " at " . $hora."</p><br>";
echo "<h2> $Post_Title</h2><br>";
echo "<img src='" .$imagem. "' class='img_posts'><br>";
echo " <br><h4 class='posts_desc'> " . $desc . "</h4><br>";
echo "poster: " . $post_id. "<br><br><hr>";
}
?>
</body>
</html>
the result was great because it really displays the Posts, but I only wanted to display the posts of just one example user:
I just want to show Gary posts, if in case another user with another
name example Fred if Fred posts something the post doesn't appear in
index.php
is there any way to do this?

Short Answer :
You will need to use where clause in query.
e.g.
$result_msg_cont = "SELECT * FROM posts where poster= 'Gary' ORDER BY id Desc";
Long Answer :
Add poster_unique_id column in your posts table.
create one more database table named users with columns like id, unique_id, name, user_status, showhide. Use unique random string for unique_id column for each poster details.
Now display names of users (posters) with link to them with GET value.
e.g.
<?php echo $userdata['name']:?>
// HERE USER NAME AND UNIQUEID IS FETCHED FROM users TABLE
Then in your above current code, add
$poster = $_GET['poster'];
// then use query like
$result_msg_cont = "SELECT * FROM posts where poster_unique_id = '$poster' ORDER BY id Desc";
** Data sanitization etc not considered in this example.
I didn't get your this line - then I created a php file called Index.html
is it index.php or index.html ??

Related

PHP dynamically defined variable (to use in a while loop with two conditions)

I thought I would simplify my question and start with trying to solve one problem at a time instead of two. The -1 rating tells me I was not clear enough, so I will try again. My original post is quoted below.
With the following code I can display data from my table that meets the condition that the category is Scenics:
<?php
$category = $_GET['category'] ?? 'Scenics';
$sql = "SELECT * FROM photo_library ";
$sql .= "WHERE category='" . $category . "' ORDER BY id ASC";
$image_set = mysqli_query($db, $sql);
$image_set_desc = mysqli_query($db, $sql);
?>
What I want to do is have dynamically set. Instead of $category = $_GET['category'] ?? 'Scenics';, is there a way not set the way it is above? I would like it be set by whatever it finds in the 'category' column of my SQL table so that later I can say while category is Scenics and sub_category is Coastal, display just that info (so I will need to do something similar for sub_category).
EDIT: The term I was looking for was array. I want $sub_category to be an array based on what is found in the sub_category column of my SQL table.
I am also aware of the risk of using $_GET, but this would be on a protected site where you only get access if you are a member, and you are only a member if you apply and are manually approved for access. And there is no user input in the protected part of the site. It is strictly a resource site for downloading graphics and images.
I am playing around with having an image gallery be generated using
PHP and My SQL instead of coding everything in HTML on the page. I've
created a test table that has multiple columns, and a working page
where all the info gets pulled in and displayed.
The two main values that will be used to separate image entires from
each other are 'category' and 'sub_category'. The page that is working
only uses the category and works great.
<?php
$category = $_GET['category'] ?? 'Agroforestry';
$sql = "SELECT * FROM photo_library ";
$sql .= "WHERE category='" . $category . "' ORDER BY id ASC";
$image_set = mysqli_query($db, $sql);
$image_set_desc = mysqli_query($db, $sql);
?>
$image_set pulls in the info for the actual image, and $image_set_desc
does the work for the links and file size. This is the pulling in of
the thumbnail:
<?php while($subject = mysqli_fetch_assoc($image_set)) { ?>
<li><a href="<?php echo h($subject['jpg_location']); ?>" title="<?php echo h($subject['title']); ?>" data-title="<?php echo
h($subject['id']); ?>">" src="#" alt="" aria-describedby="">
<?php while($subject_desc = mysqli_fetch_assoc($image_set_desc)) { ?>
<p id="<?php echo h($subject_desc['id']); ?>"><b>Filename:</b> <?php echo h($subject_desc['filename']); ?><br>
<a class="btn btn-default btn-xs mrgn-tp-sm" role="button" href="<?php echo h($subject_desc['tif_location']); ?>">TIFF <span
class="wb-inv">image download () ">JPG image
download ()
The problem is on the next page I am testing this on, there are a lot
more pictures and they are broken up into multiple sub-categories. I
only want to display pictures with certain sub-categories under their
respective headings.
I am very new to PHP, and do not know how to set something like
$sub_category to whatever it finds in that column. I cannot use
$sub_category = $_GET['sub_category'] ?? 'Coastal';
because the sub-category needs to be pulled from the SQL table. I
don't know what I am doing so while
$sub_category = isset($_GET['sub_category']);
doesn't break anything, it also doesn't seem to work. If that somehow
works, then
<?php while(($subject = mysqli_fetch_assoc($image_set)) && ($sub_category == 'Coastal')){ ?>
is not because nothing is generated on the page. I'm not sure if my
problem is with defining $sub_category, the while loop, or both.
First off even if your site is restricted to a subset of users your still leaving room for many attacks which could lead to attackers being able to mess with your database structure and even worse obtain sensitive data.
Regarding your problem please have a look at normalization. Currently every picture has a set category written in the category field which leads to your current confusion/problem because you now want to gather categories from every picture within your database.
If you were to normalize the category field to a separate table and link them via a foreign key you could then firstly query all categories and then group the images by the categories after looping trough.
Here's a bit of non optimized pseudo code that should give you an idea as to what I mean:
$categorizedImages = [];
$catSql = "SELECT * FROM categories";
$categories = mysqli_query($db, $sql);
foreach($categories as $category) {
$imageSql = "SELECT * FROM photo_library WHERE category='" . $category['id'] . "' ORDER BY id ASC";
// I cant recall if the access from mysqli_query is via array or ->
$categorizedImages[$category['id']] = mysqli_query($db, $imageSql);
}
var_dump($categorizedImages); exit;

Can't display table contents that contain URL's from database

I'm a student using NetBeans to create very basic webpage(s) using HTML, PHP and SQLite. So far, everything is fine. The problem I have is that images aren't displayed on the moviedetails.php page. Everything else including the titles, ratings and description for each table entry works fine. (I am retrieving rows from a database table.) Here is my code:
(This is very new to me, so if it's a simple mistake, sorry for wasting your time :/)
Index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$pdo = new PDO('sqlite:movies.db'); //Import SQLite database "movies.db" to a Var
$query = $pdo->query("SELECT * FROM movie");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
//For each id number in db, echo a hyperlink containing that ID's title and
echo '' . htmlentities($row['title']) . '';
echo '<br>';
}
?>
</body>
moviedetails.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$pdo = new PDO('sqlite:movies.db'); //Using movies.db
$query = $pdo->prepare("SELECT * FROM movie WHERE id=:id"); //Prepare this statement
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); //GET INPUT from Variable 'id' and FILTER anything which isn't a number
$query->bindParam(':id', $id, PDO::PARAM_INT); //Bind :name 'id' to a $id variable
$query->execute(); //Execute the prepared statement
$row = $query->fetch(PDO::FETCH_ASSOC); //Fetch next row of results
//var_dump($row);
//display title, description and rating
echo '<h1>'.htmlentities($row['title']).'</h1>'; //Echo 'Title' from db into a heading
echo ''; //Echo 'image from db into a link
echo '<p>'.htmlentities($row['description']).'</p>'; //Echo 'description' from db to paragraph
echo '<p>Rating: '. htmlentities($row['rating']).'</p>'; //Echo 'rating' from db to paragraph
?>
</body>
Here is my database in an image, as this is the easiest way to show you:
http://i.cubeupload.com/TBI5Fv.png
Here is one of the webpages that should diplay a link. However, it contains only the other table fields:
http://i.cubeupload.com/1tcfsU.png
The strange thing is, it doesn't give me any errors, so I don't know where I'm going wrong.
Hope someone can help :)
Your <a> tag is empty, so it's invisible.
echo '';
You should put some content that will be displayed as a link like this:
echo 'THIS IS LINK TO IMAGE';
If you want to display the image itself instead of a link, you should use <img> tag like this:
echo '<img src="'.htmlentities($row['image']).'"/>';

Creating a (simple) flash game website with rating system

He guys,
For school I need to make a website where you can play flash games,
rate games by leaving reactions in a text form and a vote system which uses a number system (i.e. 1 = extremely bad and 10 = very good.).
Right now what I want to do is this:
Have an index page for each category of games where users can click on a games name and be directed to another page where the script loads the game.
So far I've written this code for the index (master) page.
<!DOCTYPE html>
<?php
include("dbconnect.php");
?>
<html>
<head>
<meta charset="UTF-8">
<title>Master page</title>
</head>
<body>
<?php
//Place all data from this mySQL query in $result.
$result = mysql_query("SELECT * FROM gamesDB");
//While a row of data exists, put that row in $data as an associative array.
while($data = mysql_fetch_assoc($result)) {
//Echo a link to all the games in the MySQL database.
echo "<a href='detail.php?id=" . $data['ID'] . "'>";
//Echo the games name in the url.
echo $data['Spel'];
//Echo the closing tags
echo "</a>";
echo "<br />";
}
?>
</body>
</html>
And this is for the game (detail) page.
<!DOCTYPE html>
<?php
include("dbconnect.php");
?>
<html>
<head>
<meta charset="UTF-8">
<title>Detail page</title>
</head>
<body>
<?php
//Place all data out of the database, with the ID number retrieved out of the url into $result.
$result = mysql_query("SELECT * FROM gamesDB WHERE id = '" . $_GET['id'] . "'");
//While a row of data exists, put that row in $data as an associative array.
while($data = mysql_fetch_assoc($result)) {
//Retrieve the files name from the database and place it in the <embed> tags as src="...".
echo "<embed width='800' height='512' src='" . $data['file'] . "' type='application/x-shockwave-flash'></embed>";
//Echo the games name
echo "Spel: " . $data['Spel'] . "<br />";
//Echo the points (not yet functional)
echo "Punten: " . $data['Punten'] . "<br />";
//Echo all reactions from users regarding this game.
echo "Reacties: " . $data['Reactie'] . "<br />";
}
?>
</body>
</html>
When I click on the link in the masterpage I get redirected to the detail page but unfortunately, the game does not load.
In my MySQL DB I added the file name to the first row with ID 1. I thought, when I inquire for the filename in the tags it would load the game but it says (when I right click the box in which the game should display) "Movie not loaded...".
Can anybody help me get this to work ? Is my thinking way off perhaps, or am I headed in the right direction.
Since it is an assignment for school, there is no need to worry about any SQL injection vulnerabilities.
Thanks!
I actually forgot to put an entry into the file column.
Now that the problem I had with "<embed>" has been resolved, I would like to focus on how to add user comments to my 'comments' column, and have each comment displayed. I'd like to find the code myself as much as possible so you could just react to my question with pointers instead of writing the complete code I would be very grateful.

PHP and secure forms

I am doing an exercise from the book PHP & MYSQL in easy steps. It involves an HTML form to update a row in a database then various PHP scripts to check the the input data for HTML code and make it into a secure format. However, the code just does not work the way the book says. I went to the publisher's website and downloaded the code example, but no joy.
Instead of a form with the name of the row below it, instead I get the form, then below that "No valid new name submitted". Then below that the current name of row in the table which I want to change. When I try to enter and submit data into the form it makes no difference. It displays exactly the same page. The code is below.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ensuring security
</title>
</head>
<body>
<form action="secure.php" method="POST">
<p>New Name : <input type="text" name="name">
<input type="submit"></p></form>
<?php
require('../connect_db.php');
if (!empty($POST['name']) && !is_numeric($_POST['name'])) {
$name = $POST['name'];
$name = mysqli_real_escape_string($dbc, $name);
$name = strip_tags($name);
$q = 'UPDATE towels SET name "' . $name . '" WHERE id= 1';
mysqli_query($dbc, $q);
} else {
echo 'No valid new name submitted';
}
$q = 'SELECT * FROM towels WHERE id = 1 ';
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
echo "<p>Name : $row[1] </p>";
}
mysqli_close($dbc);
I'd appreciate any ideas on this. I have spent about 3 hours and been on the publishers website, but I am still at square one.
There is no superglobal array $POST so you have to change $POST['name'] to $_POST['name'].
PHP can't see that array so it evaluates !empty($POST['name']) as false and never executes code with update query.
And, like #BartFriederichs said, buy better book. I don't think you'll learn something valuable from current one.

PHP - How to Create Dynamic URLs?

I've scoured the web for a tutorial about this simple task, but to no avail. And so I turn to you helpful comrades. Here's what I need to do:
I have a MySQL database with an Events table. I need to create a PHP web page with a list of the Event titles, and each title must be a link to the full details of the Event. But I want to avoid having to create a static page for each event, primarily because I don't want the data entry volunteer to have to create these new pages. (Yes, I realize that static pages are more SEO friendly, but I need to forego that in this case for the sake of efficiency.)
I've seen PHP url syntax with something like this:
pagename.php?id=20
but I don't know how to make it work.
Any and all help greatly appreciated.
Thanks!
Kip
This is basic php. You would simply query the DB for the event details before the page headers are written and write the html accordingly.
The first thing I would ask you is if you know how to connect to your database. From there, you query based on the $_GET['id'] value and use the results to populate your html.
Not to be rude, but the question itself suggests you're new to PHP, right? So in order to provide a solution that works we might want to know just how far you got.
Also, you can rewrite your dynamic urls to appear like static ones using apache's mod_rewrite. It's probably a novice level thing if you're interested in "pretty" url's.
MODIFIED ANSWER:
In your loop you would use the id from the query result (assuming your primary key is id)...
while($field = mysql_fetch_array($result)) {
echo "<p class='date'>";
echo $field['month']." ".$field['day'].", ".$field['year'];
echo "</p>";
echo "<h3>";
echo ''.$field['event_name'].'';
echo "</h3>";
}
Then on somepage.php you would use the get var id to pull the relevant info...
$result = mysql_query("SELECT * FROM `calendar` WHERE `id` = '".mysql_real_escape_string($_GET['id'])."');
don't forget to look into mysql_real_escape_string() for cleaning entries.
It's wise to take extra care when you are using $_GETvariables, because them can be easily altered by a malicious user.
Following with the example, you could do:
$foo = (int)$_GET['id'];
So we are forcing here the cast of the variable to a integer so we are sure about the nature of the data, this is commonly used to avoid SQL injections.
lets say you have the php file test.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("db", $conn);
$id = $_GET['id'];
$sql = "select * from table where id = $id";
$result = mysql_query($sql, $conn);
if ($result){
$row = mysql_fetch_row($result);
$title = $row[0];
$content = $row[1];
}
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $title ?></h1>
<p><?php echo $content ?></p>
</body>
</html>
a dynamic page would be something like that..
Here is the pertinent code for extracting a list of events in November from a table named calendar, with each event having a link to a page called event.php and with the event's id field appended to the end of the url:
$result = mysql_query("SELECT * FROM calendar WHERE sort_month='11'");
while($row = mysql_fetch_array($result))
{echo
"<a href='event.php?id=".$row['id']."'>".$row['event_name']."</a>"
;}
And here is the pertinent code on the event.php page. Note the row numbers in brackets depends on the placement of such in your table, remembering that the first row (field) would have the number 0 inside the brackets:
$id = $_GET['id'];
$sql = "select * from calendar where id = $id";
$result = mysql_query($sql, $con);
if ($result){
$row = mysql_fetch_row($result);
$title = $row[12];
$content = $row[7];
}
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $title ?></h1>
<p><?php echo $content ?></p>
</body>
</html>
This works for me, thanks to the help from those above.
$foo=$_GET['id'];
in your example $foo would = 20

Categories