Im trying to build a feeds application in php in which im using a simple table with 2 columns..one for name and one for the respective feeds...my feed is appearing properly but there is some problem with the name heres the code...
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT id, feed, feeddate FROM feeds ORDER BY feeddate DESC LIMIT 20");
while($row = mysql_fetch_array($sql))
{
$name = $row["name"];
$uid = $row["userid"];
$ufeed = $row["feed"];
$feeddate = $row["feeddate"];
$feeds .= '
<table width="90%" align="center" cellpadding="4" bgcolor="#A6D2FF">
<tr>
<td width="7%" bgcolor="#FFFFFF">' . $name . '<br />
</td>
<td width="93%" bgcolor="#D9ECFF"> <span style="font-size:10px; font-weight:bold; color:#A6A6A6;">' . $feeddate . '</span><br />
' . $ufeed . '</td>
</tr>
</table>';
}?>
<?php print "$feeds"; ?>
here the $name thing is simply not displaying as a link!please help..
You are selecting only three columns:
SELECT id, feed, feeddate
"name" is not among them, so it will be always empty.
$row["name"] is not set, because you did not include the name column in the select expression of the database query. Consequently, the statement
$name = $row["name"];
sets $name to null. The same holds for $uid and $row["userid"].
Your sql query should be
$sql = mysql_query("SELECT name, id, feed, feeddate FROM feeds ORDER BY feeddate DESC LIMIT 20");
Also, you have $uid = $row["userid"];. I believe it should be $uid = $row["id"]; as you have id in sql query. You have to change either of them.
If you have id use above query, else use below query.
$sql = mysql_query("SELECT name, userid, feed, feeddate FROM feeds ORDER BY feeddate DESC LIMIT 20");
You are selecting 3 columns id,feed,feed date.But you are printing name,id,feed,feed date. Please select name column also. It will display proper output.
Related
I am trying to individually print out each line from my SQL database in PHP. I am trying to do this so each line that is retrieved, it can act like a link which will direct the user to another page. For example, the current SQL query will output the Category names from the database Category, i would like it to output all the values from that table but have it so each one has a different redirect link to another page which clicked on.
$query = "SELECT CATEGORY_NAME
FROM CATEGORIES ORDER BY CATEGORY_ID ASC";
$results = #mysqli_query ($conn, $query);
$numrows = mysqli_num_rows($results);
if ($results) {
if ($numrows >0) {
echo '
<table>
<tr>
<td><strong>Categories</stong></td>
</tr>';
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '<tr>
<td>' . $row['CATEGORY_NAME'] . '</td>
</tr>
';
}
mysqli_free_result ($results);
Such as,
Category
__________
PS4
XBOX
i can click on PS4 and it would take me to another page, i know how to do this with a href and then print out the row in sql however, i'm not sure how do print out each row individually without printing them out using $row['CATEGORY_NAME'].
Thank you for any help
You could just store the link to which it needs to be redirected in a new column CATEGORY_URL along with the CATEGORY_NAME and then print it out like so:
$query = "SELECT CATEGORY_NAME, CATEGORY_URL FROM CATEGORIES ORDER BY CATEGORY_ID ASC";
$results = mysqli_query($conn, $query);
$numrows = mysqli_num_rows($results);
if ($numrows > 0) {
echo '
<table>
<tr>
<td><strong>Categories</stong></td>
</tr>';
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '
<tr>
<td>
'.$row['CATEGORY_NAME'].'
</td>
</tr>';
}
mysqli_free_result ($results);
} else {
// no results found
}
OR if you just want to pass it as a url parameter, you just need to modify if like so:
'.$row['CATEGORY_NAME'].'
OR
'.$row['CATEGORY_NAME'].'
Something like? (I'm not 100% sure if I understand your question)
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '<tr>
<td><a href="somelink.php?cat=' . $row['CATEGORY_NAME'] . '">' .
$row['CATEGORY_NAME'] . '</a></td>
</tr> ';
}
UPDATE
If a category is named playstation, playstation.php would be linked to...
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '<tr>
<td><a href="' . $row['CATEGORY_NAME'] . '.php">' .
$row['CATEGORY_NAME'] . '</a></td>
</tr> ';
}
Though above would work a wild guess is that you're looking for something completely different. The thing you are looking for is essentially a way to present information for playstation, a way to present information about PS4 etc depending on what user clicks on!? In that case you should do something like this instead:
//Include ID of category in your sql-statement
$query = "SELECT ID, CATEGORY_NAME
FROM CATEGORIES ORDER BY CATEGORY_ID ASC";
....
....
while ($row = mysqli_fetch_array($results, MYSQLI_ASSOC)) {
echo '<tr>
<td><a href="presentinfo.php?id=' . $row['ID'] . '">' .
$row['CATEGORY_NAME'] . '</a></td>
</tr> ';
}
and create presentinfo.php file where you fetch information about the category, based on the id given in the url. (e.g.select from categories id={id given in url})
This is going to be a confusing one.. I'll try to explain it and provide as much information as possible. Basically, what I have is a website where people can upload the amount of kills they get in a game. What I'd like to do, is display people's combined, confirmed kills on a leaderboard.. This is proving harder than I expected (LOL).
Here's what my database looks like:
submission is the unique id of the entry.
usergt is the user's gamertag.
image is not important.
userkilled is the person they have killed.
status is the status of the confirmation of the kill.
conftotal is the total kills that we confirmed from the image (eg. entry 5 recorded 24 kills).
submitted is simply a unix timestamp of the submission date and time.
Here's my PHP on the page itself:
<?php
function getKills($gamertag) {
$conn = new mysqli("localhost", "rpsanet_seals", "k_,2N2Xbu}mr", "rpsanet_seals");
if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);}
$sql = "SELECT conftotal FROM kills WHERE usergt='" . $gamertag . "'";
$result = $conn->query($sql);
$ctotalklls = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$ctotalklls = $ctotalklls + $row["conftotal"];
}
} else {
$ctotalklls = 0;
}
return $ctotalklls;
$conn->close();
}
?>
<div class="mykills_content">
<table class="mykills_table">
<tr>
<th class="mk_first">Avatar</th>
<th>Gamertag</th>
<th>Latest Victim</th>
<th class="mk_last">Total Kills</th>
</tr>
<?php
$conn = new mysqli("localhost", "rpsanet_seals", "k_,2N2Xbu}mr", "rpsanet_seals");
if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);}
$sql = "SELECT *, COUNT(*) AS magnitude
FROM kills
WHERE status='confirmed'
GROUP BY usergt
ORDER BY magnitude ASC
LIMIT 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '
<tr>
<td class="mykills_submission" data-submission="' . $row["submission"] . '">
<div class="mykills_avatar">
<img src="https://avatar-ssl.xboxlive.com/avatar/' . $row["usergt"] . '/avatarpic-l.png" class="mykills_victim_avatar" draggable="false" />
</div>
</td>
<td>
' . $row["usergt"] . '
</td>
<td>
' . $row["userkilled"] . '
</td>
<td>
' . getKills($row["usergt"]) . '
</td>
</tr>
';
}
echo '</table>';
} else {
echo '</table><div class="fw-nokills">You have not submitted any kills yet.</div>';
}
$conn->close();
?>
</div>
</div>
and this is what it looks like on the page:
I have no idea what I've done wrong or how to fix it. As you can see, the order is incorrect. It should go CheapApples12, then KILLER C00KIE X, then ancrobbo97.
If anything else is not clear, or any other info is needed, just comment and I'll get that to anyone as soon as I can..
I appreciate any help in advance :)
IMPORTANT INFO: The "Total Kills" that are being shown in the screenshot above are being generated from the getKills() function, not the database query result.
Try this simple one liner use sum(conftotal) and use order by sum(conftotal)
SELECT *,sum(conftotal) as totalkills FROM kills WHERE status='confirmed' GROUP BY usergt ORDER BY totalkills desc
SELECT x.avatar, x.gamertag, x.magnitude AS magnitude FROM
( SELECT avatar,gamertag, COUNT(*) AS magnitude
FROM kills
WHERE status='confirmed'
GROUP BY usergt
LIMIT 5
) AS x
ORDER BY magnitude ASC
I can't test what I wrote, but I think you can get the logic out of it.
Using subqueries is slower, but they are quite powerfull.
As I understand you want a descending order to be displayed based on the TotalKills count, please try using the following query.
"SELECT *, COUNT(ref_column_name) AS magnitude
FROM kills
WHERE status='confirmed'
GROUP BY usergt
ORDER BY magnitude desc"
Currently, my plan is to add a gender icon next to the username. The problem is that even if there are more than 1 table record in the table, it shows only 1 row and some records suddenly gone. This is how it looks like:
The code I am using:
$pdo = new PDO('connection');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt1 = $pdo->prepare("SELECT id, user_id, user, bid, date
FROM auction_bids ORDER BY date DESC");
$stmt2 = $pdo->prepare("SELECT user_id, user, bid, date
FROM auction_bids ORDER BY date DESC LIMIT 30");
$stmt11 = $pdo->prepare("SELECT pol FROM tb_users WHERE id = :user_id");
$stmt2->execute();
$r1 = $stmt1->fetch(PDO::FETCH_ASSOC);
$stmt11->execute(array(':user_id' => $r1['user_id']));
$id1 = $r1['id'];
echo '<table>';
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC) && $r2 = $stmt11- >fetch(PDO::FETCH_ASSOC)) {
echo '<tr>
<td>' . $id1 . '</td>
<td><img height="16" width="16" alt="gender icon" src
="../images/' . ($r2['pol'] == 1 ? 'male.png' : 'female.png') . '" />
' . $r1['user'] . '</td>
<td class="border-right">' . $r10['level'] . '</td>
<td>' . $r1['bid'] . ' FA</td>
<td><img height="16" width="16" alt="calendar" src
="../images/calendar.png" />
' . date($dateFormatBids, strtotime($r1['date'])) . '</td>
</tr>
';
$id1--;
}
echo '<table>
Using while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {..} loop without $r2, it is working (except that the gender color is the same, for test it should be red, for Lukas, should be blue):
If there is something that you need, please say. I am quite new to PHP and PDO.
from the line: $stmt11->execute(array(':user_id' => $r1['user_id'])); you are getting a single record so the while loop prints single row.
Write the query like:
$stmt2 = $pdo->prepare("SELECT tu.pol, user_id, user, bid, date
FROM auction_bids ab left join tb_users tu on ab.user_id = tu.id
ORDER BY date DESC LIMIT 30");
now :
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC){
//rest of the code should work... user $r1['pol'] instead of $r2
}
Check that link to understand while loop :
http://www.w3schools.com/js/js_loop_while.asp
The problem you have condition should TRUE, and you ($r1 && $r2) = TRUE only when both Variable are TRUE, $r2 first time it's TRUE both second time will get FALSE.
You should loop for only $r1 and call $r1 inside the loop.
I have a custom web store and it was made with php. It gets all my products from certain categories that are stored in a mySQL database, and displays them in tables for my customers. The programming looks like it is meant to sort them by date added, but that doesn't work. I have messed with it several times trying different variables with no help. Is there something wrong with the syntax here?
This is the code for the actual list (above the on the page):
$dynamicList = "";
$sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC LIMIT 5");
$productCount = mysql_num_rows($sql); // count the output amount
if(isset($_GET['category'])) {
$category = $_GET['category'];
$sql = mysql_query("SELECT * FROM products WHERE category = '$category'");
$num_rows = mysql_num_rows($sql);
if($num_rows > 0) {
while($row = mysql_fetch_array($sql)) {
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$dynamicList .= '<table width="65%" border="15" cellspacing="0" cellpadding="6" align="center">
<tr>
<td width="17%" valign="top"><img style="border:#000000 1px solid;" src="inventory_images/' . $id . '.jpg" alt="' . $product_name . '" width="155" height="155" border="1" /></td>
<td width="83%" valign="center">' . $product_name . '<br />
$' . $price . '<br />
<img src="style/detailssm.png" border="0" alt="Tube Bender"></td>
</tr>
</table>';
}
}
}
mysql_close();
?>
My product database has all the attributes listed in the code above, and they are all filled out (like product_name, date_added, category, etc). I would really like to be able to get the sort by date to work, or add a new column like "display order" and then I just number them all and be done with it. But I can't just replace the variable since the current one doesn't work anyway : (
Let me know if you guys have any ideas. Thank you!
You have 2 sql statements in your sample code. The first has an ORDER BY clause, but doesn't appear to be used anywhere.
The second SQL statement has no ORDER BY clause, and that's the one you use to build your dynamicList table.
I think that the second query just to have the "order by", try this...
<?php
$dynamicList = "";
$sql = mysql_query("SELECT * FROM products ORDER BY date_added DESC LIMIT 5");
$productCount = mysql_num_rows($sql); // count the output amount
if(isset($_GET['category'])) {
$category = $_GET['category'];
$sql = mysql_query("SELECT * FROM products WHERE category = '$category' ORDER BY date_added DESC ");
$num_rows = mysql_num_rows($sql);
...
?>
I have a MySQL database called "bookfeather" with several tables that contain list books. Under each table, each book has a given number of votes. The PHP code below allows the user to enter in a book title ($entry), and then returns the total number of votes that book has in all tables ($sum).
How could I use PHP to make a 2-column, 25-row table that lists the 25 books in the database with the highest value for $sum (in descending order)?
Thanks in advance,
John
mysql_connect("mysqlv10", "username", "password") or die(mysql_error());
mysql_select_db("bookfeather") or die(mysql_error());
// We preform a bit of filtering
$entry = strip_tags($entry);
$entry = trim ($entry);
$entry = mysql_real_escape_string($entry);
$result = mysql_query("SHOW TABLES FROM bookfeather")
or die(mysql_error());
$table_list = array();
while(list($table)= mysql_fetch_row($result))
{
$sqlA = "SELECT COUNT(*) FROM `$table` WHERE `site` LIKE '$entry'";
$resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
list($isThere) = mysql_fetch_row($resA);
$isThere = intval($isThere);
if ($isThere)
{
$table_list[] = $table;
}
}
//$r=mysql_query("SELECT * , votes_up - votes_down AS effective_vote FROM `$table[0]` ORDER BY effective_vote DESC");
if(mysql_num_rows($resA)>0){
foreach ($table_list as $table) {
$sql = "SELECT votes_up FROM `$table` WHERE `site` LIKE '$entry'";
$sql1 = mysql_query($sql) or die("$sql:".mysql_error());
while ($row = mysql_fetch_assoc($sql1)) {
$votes[$table] = $row['votes_up'];
$sum += $row['votes_up'];
//echo $table . ': "' . $row['votes_up'] . " for $entry from $table\"<br />";
}
}
}
else{
print "<p class=\"topic2\">the book \"$entry\" has not been added to any category</p>\n";
}
//within your loop over the DB rows
//$votes[$table] = $row['votes_up'];
//afterwards
if($sum>0){
print "<table class=\"navbarb\">\n";
print "<tr>";
print "<td class='sitenameb'>".'<a type="amzn" category="books" class="links2b">'.$entry.'</a>'."</td>";
print "</tr>\n";
print "</table>\n";
//echo "<p class=\"topic3\">".''.$entry.''. "</p>\n";
echo "<p class=\"topic4\">". number_format($sum) . ' votes in total.'."</p>\n";
Try something like this. All of this hasn't been tested so please add comments for changes. I'll work with you to get the code right.
// After getting your array of tables formated like
$tableArray = array("`tableA`", "`tableB`", "`tableC`");
// create a table statement
$tableStatement = implode(", ", $tableArray);
// create a join statement
$joinStatement = "";
for ($i = 1; $i < count($tableArray); $i++) {
if ($joinStatement != "")
$joinStatement .= " AND ";
$joinStatement .= $tableArray[0] . ".site = " . $tableArray[$i] . ".site"
}
$firstTable = $tableArray[0];
$sql = "SELECT SUM(votes_up) FROM " . $tableStatement . " WHERE " . $joinStatement . " AND " . $firstTable . ".site LIKE '" . $entry . "' GROUP BY " . $firstTable . ".site ORDER BY SUM(votes_up) DESC";
Edit --------
I now realize that the query above won't work perfectly because votes_up will be ambiguous. Also because you probably want to be doing joins that grab records that are only in one table. I think the concept is the right direction even though the query may not be perfect.
You can do something like
$selectStatement = "SUM(tableA.votes_up) + SUM(tableB.votes_up) as total_votes_up"
I did something like this recently. In your database, you'll have to rename each field to a corresponding book name.php like (TaleofTwoCities.php). Now on your page that will display the vote results, you'll need to include some php files that will drive the database query on each load. I called mine "engine1.php" and "engine2.php." These will do all your sorting for you.
$query1 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 0,1"));
$query2 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 1,1"));
$query3 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 2,1"));
and so on.. then..
$num1 = "$query1[0]";
$num2 = "$query2[0]";
$num3 = "$query3[0]";
That part sorts your listings by the number of votes from highest to lowest, with url, in your case, being the name of the books(remember you want it to end in .php - you'll see why in a second), and counter being the field that logs your votes.
Make your second engine.php file and add something like this:
$vquery1 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book1.php'"));
$vquery2 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book2.php'"));
$vnum1 = "$vquery1[0]";
$vnum2 = "$vquery2[0]";
and so on... Until you get to 25 for both this and engine 1.
Now, in your results page, after you put in the require_once(engine.php) and require_once(engine2.php) at the start of your body, start an HTML table. You only want two columns, so it'll be something like..
<table border=1 cellspacing=0 cellpadding=0>
<tr>
<?php include $num1; ?>
</tr>
<tr>
<?php include $num2; ?>
</tr>
And so on... By naming your field with "book1.php" and including the engines, $num1 will change to a different .php file depending on votes from high to low. Now all you have to do is make small php files for each book like so - no headers or anything because you're inserting it into the middle of html code already:
<td style="width:650px;"><center><img src="images/book1.jpg" alt="" border="none"
/></a></center></td>
<td style="width:150px;">Votes: <?php echo $vnum1;?></td>
And there you have it. A code that will dynamically give you results from high to low depending on the number of votes each book has.