MySQL only returning one value - php

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?

Related

Displaying a varying element within a PHP loop

I have a blog with 3 posts per page, and I'd like to show a single advert above each post.
The posts are selected from a MySQL table using PHP, and I can get the posts to echo out propely, but is there a way of showing different adverts within the loop?
Here is my code, and an example of what I'm trying to achieve:
$ad_1 = "Advert 1";
$ad_2 = "Advert 2";
$ad_3 = "Advert 3";
$posts .= "
<div class=\"postDivide\"></div>
<div class=\"advert\"> $ad_1 then $ad_2 then $ad_3 </div> // Here Is The Problem
<div class=\"postDivide\"></div>
<div class=\"post\">
// Post Content
</div>
";
echo $posts;
Is there a correct way of showing each advert?

Database not receiving correct data [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to fill 3 different tables in my database.
Sale table which has the following rows:
sale_id
fk_sale_user
fk_payment_id
sale_date
Print_for_sale which has:
print_for_sale_id
fk_sale_id
price_print_for_sale
Print_has_size_has_print_for_sale
print_has_size_has_print_for_sale_id
fk_print_has_size_id
fk_print_for_sale_id
Here is a screenshot of my database in mysql workbench so you can situate.
I'm trying to make the "buying" action.
This is my markup and php code:
printdetail.php
<?php
$id= $_GET['print_id'];
$printdetails = getprintdetailsById($con, $id);
$line = mysql_fetch_assoc($printdetails);
$selectsize =" select * from size";
$result=mysql_query($selectsize);
?>
<div>
<img width="800px;"src="<?php echo $line['print_img']?>"/>
</div>
<div>
<span> <?php echo $line['print_title']?> </span>
<form action="addprints.php" method="post">
<ul>
<?php while ($line = mysql_fetch_assoc($result)) { ?>
<li> <input type="checkbox" name="sizes[]" value="<?php echo $line['size_id']?>">
<?php echo $line['size_name']." Price: ".$line['size_price']."€ "?>
</li>
<?php } ?>
<input type="submit" value="Add to Cart" >
</ul>
<input type="hidden" name="print_id" value="<?php echo $id; ?>" />
</form>
</div>
addprints.php
<?php
session_start();
$user_id = $_SESSION['user_id'];
print_r($_POST);
$id_print= $_POST['print_id'];
include('database.php');
$bought_sizes=$_POST['sizes'];
$number_of_bought_sizes= count($bought_sizes);
//header('location:index.php?area=printstore');
$sqlinsertsale = "insert into sale
(fk_sale_user,
fk_payment_id)
values(".$user_id.", 2)";
mysql_query($sqlinsertsale);
for($i=0; $i< $number_of_bought_sizes; $i++){
$selectsize = "select *
from size";
$resultsize = mysql_query($selectsize);
while($linesize = mysql_fetch_assoc($resultsize))
{ $size_price = $linesize["size_price"]; }
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
while($linesale = mysql_fetch_assoc($resultsale))
{ $sale_id = $linesale["sale_id"]; }
$sqlinsertprintforsale = "insert into print_for_sale
(fk_sale_id,
price_print_for_sale)
values(".$sale_id.", ".$size_price.")";
mysql_query($sqlinsertprintforsale);
$selectprinthassize = "select *
from print_has_size";
$resultprinthassize = mysql_query($selectprinthassize);
while($lineprinthassize = mysql_fetch_assoc($resultprinthassize))
{ $print_has_size_id = $lineprinthassize["print_has_size_id"]; }
$selectprintforsale = "select *
from print_for_sale";
$resultprintforsale = mysql_query($selectprintforsale);
while($lineprintforsale = mysql_fetch_assoc($resultprintforsale))
{ $print_for_sale_id = $lineprintforsale["print_for_sale_id"]; }
$sqlinserthashas = "insert into print_has_size_has_print_for_sale
(fk_print_has_size_id,
fk_print_for_sale_id)
values(".$print_has_size_id.", ".$print_for_sale_id.")";
mysql_query($sqlinserthashas);
}
?>
I am very new to php and mysql so I'm sorry if this is a dumb or bad question. I can't figure out what I'm doing wrong...
The table Sale is being updated correctly in phpmyadmin. Everything is working. User ID is OK and payment ID is OK too. (I haven't done the payments part yet so I just used a number to test.)
The table Print_for_sale is updating the correct sale ID (fk_sale_id), however the price_print_for_sale is always the same, no matter what print I choose. It's always 150 when sometimes it should be 65 ou 25.
(The print price is defined in the size table. So far I have 3 different sizes, so different prices.)
The table Print_has_size_has_print_for_sale is updating the correct print_for_sale ID, but the fk_print_has_size_id is always number 12 (which is the last from that list) and it has nothing to do with my choices on the form. I believe this is what is making the price come out wrong. If it's always the same combination of prints and size (print_has_size), then it's always going to have the same price... Why is this happening?
Can someone please help me?
Here are some screenshots of phpmyadmin:
Edit: This is the function I used:
<?php
function getprintdetailsById($con, $print_id){
$question = "select * from print where print_id=".$print_id;
$result = mysql_query($question, $con);
return $result;
}
?>
This is a lot of info.. I guess we can start debugging. Let's begin with your while loops. Inside your for loop, the first line select * from size, this should return an array, then you are iterating this array with your while loop, but you are assigning them to just one variable. This will overwrite the data result of the last iteration. Is this what you want?... to be continued.
You don't want that to be overwritten.. so what you need to do for that while loop is assign it to an array, like this:
while ($linesize = mysql_fetch_assoc($resultsize)) {
$size_price[] = $linesize["size_price"];
}
so, once you have the $size_price[] with all the desired sizes, we move on.. your code now runs select * from sale where you want all the sale_ids from. So just like above, assign it to an array, we'll say $sale_ids[]
Now you are trying to run a query that inserts data to the print_for_sale table, but the data comes from the two different arrays you created above.. this is will not work, and if so, you would need to come up with crazy loops and iteration like you already have tried.
To fix it, you first need to look at your tables, assign them unique ids, and link them through indexes, once you do that, you need to use the JOIN SQL command on your queries to get the matched data together.
I would look into separating your code as well. this will help you reuse it. You should look into an MVC framework. Ever heard of Codeigniter? its very easy to learn and powerful for applications.
Hope this helps.
Your code could use work, but I think that your problem is a misplaced bracket at the end. It should be:
while($lineprinthassize = mysql_fetch_assoc($resultprinthassize))
{
$print_has_size_id = $lineprinthassize["print_has_size_id"];
$selectprintforsale = "select *
from print_for_sale";
$resultprintforsale = mysql_query($selectprintforsale);
while($lineprintforsale = mysql_fetch_assoc($resultprintforsale))
{
$print_for_sale_id = $lineprintforsale["print_for_sale_id"];
$sqlinserthashas = "insert into print_has_size_has_print_for_sale
(fk_print_has_size_id,
fk_print_for_sale_id)
values(".$print_has_size_id.", ".$print_for_sale_id.")";
mysql_query($sqlinserthashas);
}
}
The replace code should be in the loop. In your original code, you looped through all the values, ending with the last one, and then used it.

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'])

jQuery UI Sortable and updating a mysql database

I am doing something wrong and it's driving me nuts because I can't figure it out.
Using jQuery ui sortable to sort the divs on my page. The sorting part works kinda but it does not update the database.
The only thing I can think of is the clear within page, but if I put this on the div it acts not as fluent.
PHP
<div id="page">
<div id="listItem_'.$id.'" class="a bunch of random classes">
<div class="handle"></div>
</div>
<div id="listItem_'.$id.'" class="this one has some other classes">
<div class="handle"></div>
</div>
<div class="clear"></div>
<div id="listItem_'.$id.'" class="a bunch of some other">
<div class="handle"></div>
</div>
</div>
Javascript
$(document).ready(function(){
$("#page").sortable({
handle : '.handle',
update : function () {
var order = $('#page').sortable('serialize');
$(document).load("sort.php?"+order);
}
});
});
sort.php
<?php
session_start();
require('connect.php');
if($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_SESSION['USERNAME'])){
$i=1;
foreach ($_GET['listItem'] as $position => $item){
$sql = "UPDATE table SET position = ".$i." WHERE id = ".$item;
$res = mysql_query($sql);
$i++;
}
}
?>
Start debugging by placing var_dump('got here'); (or one of the variables) in your PHP script. Use the console in Firebug (which is an add-on) in Firefox to view the output. Step through until you find the spot where it's failing.
should $i be replaced with $position:
$sql = "UPDATE table SET position = ".$i." WHERE id = ".$item;
$sql = "UPDATE table SET position = ".$position." WHERE id = ".$item;
in any case ... if it doesnt update the database presumably you get an error?
and, i assume your table isnt actually called 'table' otherwise you should probably backtick it..

How to split mySQL information to show in HTML columns

I am trying to figure out a way to split mySQL rows into HTML columns. I'm sorry if there is an easier way to ask this, but I can't wrap my head around it.
I have read through very many suggestions though none of them fit what I am looking for.
I understand it is very easy to just float the information left and allow it to stack by itself. My problem is that I am showing information in a "card" form with two different sized cards and I would like them all to stack without gaps vertically.
For the purpose of showing this, I've given every card a number from 1-3. Every card numbered 1 should fit in the first column, and so on. example here
Normal floating left gives me something like this:
|1|2|3|
|4|5|6|
|7|8|9|
This is the correct way to display the information, but it leaves gaps where large cards are next to small ones like in the example.
if I use a foreach loop in the php with a table or divs, I get something like this:
|1|2|3|
-------
|4|5|6|
-------
|7|8|9|
Unfortunately, this is pretty much the same outcome. The larger cards push down the row leaving a large gap where a smaller card is.
I also understand that after the first visibile row, the most recent divs could potentially be pushed farther down in one column rather than another. for example, if column 1 has 6 'featured' or large cards, it would take 12 cards to fill the space beside it. I'm not worried about this.
The basic, stripped down code that I have right now is this:
<div class="container">
<?PHP
$qry_questions = mysql_query("SELECT STATEMENT**");
$count = 0;
while($row = mysql_fetch_array($qry_questions)){
$count++;
/*GATHER INFORMATION*/
?>
<div class="HTML-formatting-here-with-php-echos">
</div>
<?PHP
}
?>
</div>
Now I'm just trying to figure out if I can make a statement in php that basically says:
"if $count == 1, append this information into column 1, if $count == 2, append this into col 2, etc."
Is there any type of function that I can do to split this information like this and append the information without completely building a whole new row?
p.s. I've tried array_chunk() without the proper outcome.
EDIT: Here is the while loop
<div id="collective">
<div class="container">
<?PHP
//FIND THE QUESTIONS ASKED AND INFORMATION ON THEM
$qry_questions = mysql_query("SELECT * FROM mbr_qa_questions ORDER BY q_votes DESC" /* LIMIT 0, 10"*/); //LIMIT 0, 20 - 20 being how many to show at a time
$num_rows = mysql_num_rows($qry_questions);
$max_col = 3;
$count = 0;
//START THE LOOPING
while($q_row = mysql_fetch_array($qry_questions)){
$q_id = $q_row['q_id'];
$q_votes = $q_row['q_votes'];
$q_answers = $q_row['q_answers'];
$q_title = $q_row['q_title'];
$q_description = $q_row['q_description'];
$q_tags = $q_row['q_tags'];
$q_user_id = $q_row['user_id'];
$q_created = $q_row['q_created'];
$q_modified = $q_row['q_modified'];
$q_featured = $q_row['q_featured'];
if($q_featured == 0){
$q_status = "normal";
} else {
$q_status = "featured";
}
//GET THE USERS USERNAME
$qry_username = mysql_query("SELECT user_name FROM mbr_user_name WHERE user_id = '$q_user_id'");
$q_user_name = mysql_result($qry_username, 0);
//FIND THE USERS POINTS
$qry_points = mysql_query("SELECT point_amount FROM mbr_qa_points WHERE user_id = '$q_user_id'");
$q_user_points = mysql_result($qry_points, 0);
//FIND OUT IF YOU FLAGGED IT
$qry_flagged = mysql_query("SELECT * FROM mbr_qa_flagged WHERE q_id = '$q_id' AND user_id = '$user_id'");
$flagged = mysql_num_rows($qry_flagged);
if($flagged >= 1){
$flaggedDiv = "<div class='q_flagged'> </div>";
} else {
$flaggedDiv = "<div class='flagInnapropriate'> </div>";
}
//FIND HOW MANY ANSWERS
$qry_answers = mysql_query("SELECT * FROM mbr_answers WHERE q_id = '$q_id'");
$q_answers = mysql_num_rows($qry_answers);
//FIND HOW MANY VOTES
$qry_votes = mysql_query("SELECT * FROM mbr_votes WHERE q_id = '$q_id'");
$q_votes = mysql_num_rows($qry_votes);
//GIVE EACH ENTRY A COLUMN NUMBER
$count++;
if($count >= 4){
$count = 1;
}
<div class="card <?= $q_status ?>">
<div class="top">
<div class="tag">
<div class="title">Votes</div>
<div class="votes">
<div class="number">
<?= $q_votes ?>
</div>
</div>
<div class="plus">+</div>
</div>
<div class="question">
<p><?= $count/* . $q_title*/ ?></p>
</div>
</div>
<div class="middle">
<div class="elapsed">
<?PHP
$time_since = $q_created;
$time_now = time();
$timeElapsed = $time_now - $time_since;
?>
Asked <?= elapsedTime($time_since) ?> ago by
</div>
<a class="profile" href="./profile.php?profile_name=<?= $q_user_name ?>">
<div class="avatar">
<img src="pieces/avatars/avatar.php?profile_id=<?= $q_user_id ?>&size=xsmall" />
</div>
<div class="userName">
<?= $q_user_name ?>
</div>
<div class="points">
<?= $q_user_points ?>pts
</div>
</a>
</div>
<div class="bottom">
<div class="answer">
<div class="title">
Answers
</div>
<div class="numAnswers">
<?= $q_answers ?>
</div>
<div class="answersText">
Answers
</div>
</div>
<div class="bestAnswer">
<div class="title">
Best Answer
</div>
<div class="description">
<p>Need to get highest rated answer here</p>
</div>
</div>
</div>
</div>
}
?>
</div>
</div>
The included newAnswerLayout.php is just the html formatting of each card.
ANOTHER EDIT:
I believe I just need to make three mySQL queries that select every nth row. Yes, the IDs on the rows are unique, but there is a possibility that some rows will be moved to another table which will leave gaps.
What I'm thinking now is to query the table, pull every third row, place that in column 1 and so forth, starting at the first entry.
EDIT 3:
What I am looking for is to do a SQL query that grabs all of the information on every third row, starting on row 1, then I need to do another query of every third row, starting on row 2, then the same for row 3.
use float:left; in your file
http://beta.mybattlereport.com/styles/global.css
line 82
class container
EDIT :
first: those cards with numbers 1,2,3 they all have same class card normal so if you apply changes to one card it will aplly changes to all cards
solution : try using table instead of divs.
second : your cards are ordered like that
card1 card2 card3 featured card , card1 card2 card3 featured card
solution : this can also be fixed by table and you order them
1 column will be for card1
2 column will be for card2
3column will be for card3
and then you can use other table under this for featured cards or a div.
EDIT2>
your problem is in the sql to get those cards generated by number of cards and featured
you should order them first by featured and then by votes
try this
$qry_questions = mysql_query("SELECT * FROM mbr_qa_questions ORDER BY q_featured ,q_votes DESC" /* LIMIT 0, 10"*/);
the numbers 1 and 2 and 3 you are just giving numbers to each card . so i dont see any purpose from those numbers why you are making them.

Categories