MYSQL retrieve data from two tables - php

I am trying to make a small discussion system where people can login and post a discussion. On the homepage I want to show the discussions.
First I retrieve the data for the discussions (topic, category, username, etc) from the table 'discussions'and order them by 'date_time'.
I put these values in div's that are working just how I want it. The problem I am having now is to show the avatar of the user. The avatars are stored in a table 'users' under the column 'avatar'.
So I need to retrieve the value from the column 'avatar' in the table 'users' where 'username' matches the username of the discussion.
This is the code that I have now but it's not working. I have tried different things but I am not very familiar yet with PHP so I don't really know how to go from here.
Thanks in advance!
$result = mysql_query("SELECT
topic,
category,
date_time,
username,
SUBSTRING(discussion, 1, 80) AS discussion
FROM discussions
ORDER BY date_time DESC");
while($record = mysql_fetch_array($result))
{
?>
<div class="discusscolumn">
<div>
<p><? echo $record['category'] . ": <b>" . $record['topic'] . "</b>"?></p>
</div>
<div>
<?php
$discussion_username=$record['username'];
$getavatar = mysql_query("SELECT avatar, username FROM users WHERE username='$discussion_username' ");
$avatarrecord = mysql_fetch_array($getavatar);
echo'<span class="smallpic"><img src="user/'.$record['username'].'/'.$getavatar['avatar'].'"></span>';
?>
</div>
<div>
<p>Posted by <? echo "<a href='user.php?u=".$record['username']."'>".$record['username'] ?> </a></p>
</div>
<div>
<p><br><? echo $record['discussion'] ?>&nbsp...</p>
</div>
<div>
<p><? echo $record['date_time'] ?></p>
</div>
<div>Discuss</div>
</div>
<?php } ?>
PS: I know I am working with mysql instead of mysqli and that I'm mixing HTML and PHP code but I just want the basics to work now.

Please check your img source(src), that you have passed as user/username/avatar instead of passing like this please put url like http://www.w3schools.com/images/w3schools_green.jpg so that you will be getting out. But in your case you need to have all your user image in some other global storage area for eg.Amazon s3 bucket, and you need to get string from database construct like above url and append that in img src inside input tag

Related

var_dump shows data but echo says Undefined index - At a loss

I've got two queries going on, one is working fine... Echos all the right column values. The second one shows all the data var_dump but keeps showing Undefined Index. I don't understand what I've done wrong.
I tried to make an array to define the index via the suggestion of a developer but that gave me zero results
$navpage = array();
$navpage['splash_id']='';
etc but that results in the empty space obviously... I don't know why this was the solution I was led to.
Error code says : Notice: Undefined index: splash_id in...
I know there are so many questions like this and most of them are talking about email forms they are working on, while I am just trying to output data from the database.
Here is my query file arts.php
<?php
require 'scripts/start.php';
$pages = $db->query("SELECT article_id, department, title, article_link, shortdesc, img_meta, live FROM content WHERE department='Arts' AND live='Yes'
")->fetchAll(PDO::FETCH_ASSOC);
$navpage = $db->query("SELECT splash_id, page, live, big_message, img1, text1, link1, expdate FROM splash WHERE page='arts' AND live='Yes'
")->fetchAll(PDO::FETCH_ASSOC);
require VIEW_ROOT . '/artpages.php';
?>
The page where I echo things like column - text1
<?php require VIEW_ROOT . '/department/arts_header.php';
?>
<div id="major">
<div id="so" class="mainimage">
<div class="mainimage"><img src="cms_img/header/<?php echo $navpage['img1']?>" class="splashimage"></div>
</div>
<div id="contentbox">
<div id="middle"><div id="articleheadline" class="titlefont"><?php echo $navpage['text1']?></div>
<?php if (empty($pages)): ?>
<p class="textfont">Sorry, there are no articles on this page.</p>
<?php else: ?>
<?php foreach($pages as $page): ?>
<div class="article_container">
<div class="article_promo"><img src="cms_img/<?php echo escape($page['img_meta']) ?>"class="promofit"></div>
<div class="article_title"><span class="article_title_font"><?php echo $page['title']?></span></div>
<div class="article_desc"><span class="article_desc_font"><?php echo $page['shortdesc']?></span></div>
</div><?php endforeach; ?>
<?php endif; ?>
</div></div></div></div>
<?php
require VIEW_ROOT . '/templates/footer.php';
?>
I expect echos of $navpage to fill in like $page does.
Fetch all get a multiple array result so you need to use foreach loop like you did in $pages or use the following code below to fetch only a single array.
$dbh = new PDO("SELECT article_id, department, title, article_link, shortdesc, img_meta, live FROM content WHERE department='Arts' AND live='Yes'");
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1");
$stmt->execute();
$navpage= $stmt->fetch();
Because you use ->fetchAll(PDO::FETCH_ASSOC). Its return array of item navpage
So you must to code $navpage[0]['img1'] and $navpage[0]['text1']
Notice check !empty($navpage) before use $navpage[0]

MySQL only returning one value

Been trying to figure out what's wrong for nearly two hours now.
I have made a wall post feature for my website, posts should be displayed on the profile wall, however instead of all of the posts being displayed, only 1 is. I have no idea what is wrong with my code, I can't find any issues.
The $profile_username variable has been defined in previous code and works. Even if I just type the name of the profile in it still only returns one post.
//----------submit wall post----------//
$getwallposts = mysql_query("SELECT * FROM `wallposts` WHERE `postedto`='$profile_username' ORDER BY `postid`");
//check if any rows are returned
while($wallposts = mysql_fetch_assoc($getwallposts)) {
$postid = $wallposts['postid'];
$postedby_username = $wallposts['postedby'];
$wallpostdate = $wallposts['dateposted'];
$wallpost = $wallposts['post'];
$querypostedby_info = mysql_query("SELECT * FROM `users` WHERE `username`='$postedby_username'");
//get the info above
if (mysql_num_rows($querypostedby_info) > 0) {
$getpostedby_info = mysql_fetch_assoc($querypostedby_info);
$postedby_id = $getpostedby_info['id'];
$postedby_profilepicture = $getpostedby_info['profilepicture'];
}
//lets keep the line breaks
$wallpost=nl2br($wallpost);
//display the posts
$wallpoststicker =
"
<div id='wallpost-container'>
<div id='wallpost-header'>
<img src='$postedby_profilepicture'><div id='wallpost-header-by'><a href='/profile.php?id=$postedby_id'>$postedby_username</a> said:</div>
<div id='wallpost-date'>• $wallpostdate</div>
</div>
<div id='wallpost-content'>
$wallpost
</div>
</div>
";
}
Also, I know that mysql is deprecated; my version of PHP can handle mysql queries fine though.
Where to do you echo you're output?
If it is after the While you will only get the last result that is stored in the variable.
Output within the while loop.
I can see a couple of issues with that code. First, what it seems to be your problem:
$wallpoststicker =
"
<div id='wallpost-container'>
<div id='wallpost-header'>
<img src='$postedby_profilepicture'><div id='wallpost-header-by'><a href='/profile.php?id=$postedby_id'>$postedby_username</a> said:</div>
<div id='wallpost-date'>• $wallpostdate</div>
</div>
<div id='wallpost-content'>
$wallpost
</div>
</div>
";
This code overrides the $wallpoststicker variable on every loop. That's why you only print one result at the very end.
But secondly, you're doing a query within a loop, which is potentially very inefficient. Have you thought on doing a LEFT JOIN between "wallposts" and "users" so you have all the data you need before you start your loop?

How to extract field of data from SQL

I am a hobbyist programmer and stuck with php and sql
I have a website where I hope to allow different users to list their domains and websites for sale. I have an SQL database with the fields: id, domain and price. Now I added a column of data where "namer" is the field name.
I am trying to extract the field "namer" so it appears on the website but it won't work.
The problem starts at // PROBLEM AREA in the code and after that div it's okay.
<div class="domain_list_item_main_linear" style="font-family: 'Open Sans', Arial; width:98%;">
<div style="width:33%;float:left;">
<a href="<?php /*?><?php echo ConfigPeer::GetValue('website_folder'); ?>
<?php echo $domain->getCleanName(); ?><?php */?>https://www.afternic.com/domain/<?php echo urlencode($domain); ?>" class="moLPdomain" target="_blank">
<?php echo html_entity_decode($domain->getDivTipNameLinear(), ENT_QUOTES); ?></a>
<?php if(!$domain->getIsSold()): ?>
</div>
<div class="moLPprice" style="width:22%;float:left;margin-left:0px;">
<?php
// PROBLEM AREA
$eventid = $_GET['id'];
$namer = $_GET['namer'];
$result = mysql_query("SELECT $namer FROM `domain` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$namer];
?> </div>
The problem is where you are using $namer.
The section after SELECT should contain the name of a column which contains the data you are trying to extract. Looking at your code, $namer isn't the name of the column, but some data that you are trying to match.
So the structure of the SQL should be like this:
SELECT column_name FROM table_name WHERE a_column_name = a_val;
I suggest you take a look at SQL SELECT statements, w3school's is a good place to start:
http://www.w3schools.com/php/php_mysql_select.asp
Edit:
You're SQL should look like this:
SELECT namer FROM domain WHERE id = $eventid;
If you want to get the 'namer' of the domain with that ID.
You're variable $namer must be storing any of the following words for your query to run:
id
domain
price

How to Link PHP Sub Categories(Pages) Dynamically

I have There PHP File getting Data From MySQL Database called:
clubs.php
club.php
player.php
the clubs.php list all clubs from tbleclubs table and it looks like:
clubs.php
$database = new Database();
$res = $Db->query("SELECT * FROM tblclubs");
foreach ($res as $dataRow): ?>
<span><?php echo $dataRow['id']; ?></span>
<span><a hrer=""><?php echo $dataRow['name']; ?> </a></span>
<?php endforeach; ?>
and club.php listing all players in a club from tblclub table
club.php
$database = new Database();
$res = $Db->query("SELECT * FROM tblpclub");
foreach ($res as $dataRow): ?>
<span><?php echo $dataRow['id']; ?></span>
<span><a hrer=""><?php echo $dataRow['name']; ?> </a></span>
<?php endforeach; ?>
and finally the player.php is from tbleplayer:
player.php
$database = new Database();
$res = $Db->query("SELECT * FROM tblplayers");
foreach ($res as $dataRow): ?>
<span><?php echo $dataRow['id']; ?></span>
<span><a hrer=""><?php echo $dataRow['name']; ?> </a></span>
<?php endforeach; ?>
I have set up a Foreign Key(FK) for tblclub as clubs_id and for tblplayers as club_id.
Now, my question is, how can I dynamically navigate to each selected item in next page like:
clubs->club->player
Thanks
First of all you have some errors in your HTML (it should href and not hrer for links)
Secondly, using a select * type of query is bad form; you should generally be choosing specific keys from your table, and not just all of them. You will also need to be link your tables if you want this to work properly; it's difficult to tell what specific rows you have in your tables; some structure would be helpful.
That said you would need to structure your queries something like this. For example to get a list of players a specific club:
SELECT p.playerid, p.name,
FROM tblplayers p, tblclub c
WHERE p.club_id = c.club_id
this query will get a list of all players on a specific club.
As for linking you would could modify your links to be something like this. To link to a specific player in a specific club, this would be the link on club.php to player.php:
<?php echo $dataRow['name']; ?>
Then to get the info you could just get the playerid from the URL by using a GET variable, like this: $playerid = $_GET['playerid']
and then get your information from the query, to do what you like. You can use the data in any way you like from there.
This is just a start, but you should be able to extrapolate from this for the rest of your questions. Hope this helps.
Ok, you are now rendering static lists.
To make the navigation dynamic you would basically need 3 things:
create links with ids
fetch this id from the URL
and query the db using the WHERE statement to select that specific id
You have already started with links: <a hrer="">, but it's href.
clubs.php - would render the overview of all clubs with links to each club
Place this in your foreach to construct the links by attaching the ids.
foreach ($res as $dataRow) {
$id = $dataRow['id'];
$name = $dataRow['name'];
$link = 'club.php?id=' . $id;
echo '<span>' . $id . '</span>';
echo '<span>' . $name. '</span>';
}
Now you can click for instance club.php?id=2.
But club.php would need to handle the incoming id, right?
club.php - renders the list of players with links to each player
You basically repeat the pattern from above, but with a different anchor base, this time it's player.php. You should get a list with player.php?id=x links.
How to handle the id in each of the scripts?
The id is incoming via $_GET.
You can use var_dump($_GET['id']) to see the value. Use a variable, like so $id = $_GET['id'].
(Later, when everything works: do not forget to secure and escape the incoming data properly.)
Then use $id in your database query:
SELECT * FROM tblplayers WHERE player_id = ' . $id;

View page based on a record

I'm new to PHP and pardon me for asking this very basic question. What I want to do is to display or view a page based on a specific record. For example, I have a home.php page which lists records of lessons. And when I click on a specific record, it will go a page named lesson.php . I have to view the relevant information/data from my dB of that specific lesson. I tried to use GET but I think it's not going to meet the requirement of my system.
This is what I've tried so far:
$qry1stQuarter = $conn->prepare("SELECT l.lesson_title FROM tbllessons as l
JOIN tblstudents as s
ON l.grade_level = s.grade_level
WHERE quarter_code = '1st'
AND s.grade_level=:grade_level");
$qry1stQuarter->execute(array(':grade_level' => $grade_level));
<div id="tabs-2">
<div id="accordion">
<h3><strong>Yunit 1</strong></h3>
<div>
<?php
for($i=0; $row = $qry1stQuarter->fetch(); $i++){
$lesson_title = $row['lesson_title'];
?>
<div id = "lessons">
<?php
echo "<a href = 'lesson_view.php'>$lesson_title </a>";?>
</div>
<?php
} // end of for loop
?>
</div> <!-- end of Yunit 1 -->
What is the best way to do this? Your help is pretty much appreciated. Thanks.
In your database, I assume you have an ID column. A typical way to do what you are asking is to use that ID as a GET parameter on a link, and then include that in your WHERE clause in your SQL statement.
Eg:
echo "<a href='lesson_view.php?id=$lesson_id'>$lesson_title</a>";?>
And then on your lesson_view.php page, your SQL has something like this:
SELECT * FROM tbllessons WHERE id = mysql_real_escape_string($_GET['id'])

Categories