PHP/MYSQL: Pulling information from database - php

I have done a little bit of research on this, but currently I'm stuck.
My situation:
My database has a serverName, and serverBanner for each entry. When I do this following code:
function listBanner() {
include("mysql.php");
$votes = "serverVotes";
$results = mysql_query("SELECT * FROM toplist ORDER BY $votes ASC");
while($row = mysql_fetch_array($results)){
echo " " . "<img src=" . $row['serverBanner'] . " height=60 width=460 />";
}
}
If you noticed, it is pulling all the info from toplist table. I need to pull all the info from toplist table, but make it so that I can put each on if them in a table row. Right now if I did that, it would put each banner in the same table row.
Also, how would I go about implementing this into a table?

Do you mean:
<?php
echo "<tr>";
while($row = mysql_fetch_array($results)){
echo "<td>" . $row['serverName'] . "</td>";
echo "<td>" . "<img src=" . $row['serverBanner'] . " height=60 width=460 />"."</td>";
}
echo "</tr>"
?>

Related

How do I echo a div using SQL table row ID as ID for the div?

I have this PHP code, which fetches data from my SQL database called "comments".
This code prints out every comment in the table:
<?php
$sql = "SELECT id,name,email,number,text FROM comments";
$result = $conn->query($sql);
if($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<strong>ID:</strong><br> " . $row["id"] . "<br>";
echo "<strong>Navn:</strong><br> " . $row["name"] . "<br>";
echo "<strong>Email:</strong><br> " . $row["email"] . "<br>";
echo "<strong>Nummer:</strong><br> " . $row["number"] . "<br>";
echo "<strong>Melding:</strong><br> " . $row["text"] . "<br><br><br>";
}
echo '<div class = "white_line_comments"></div>';
} else {
echo "0 results";
}
This has worked fine so far, everything prints as it's supposed to.
Then I decided I wanted a way to give each individual comment some sort of identification to make them unique. I tried putting each single comment into its own div, using the SQLtable row id as id for the div.
However, when I try to access my webpage now, it tells me the website doesn't work (HTTP Error 500).
<?php
$sql = "SELECT id,name,email,number,text FROM comments";
$result = $conn->query($sql);
if($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<div class='$row[' id'].'>";
echo "<strong>ID:</strong><br> " . $row["id"] . "<br>";
echo "<strong>Navn:</strong><br> " . $row["name"] . "<br>";
echo "<strong>Email:</strong><br> " . $row["email"] . "<br>";
echo "<strong>Nummer:</strong><br> " . $row["number"] . "<br>";
echo "<strong>Melding:</strong><br> " . $row["text"] . "<br><br><br>";
echo '</div>';
}
echo '
<div class="white_line_comments"></div>';
} else {
echo "0 results";
}
Any ideas on this? I guess I must've done something wrong when including the div, but I can't figure out what!
You have an error in this line after starting while loop:
echo "<div class ='$row['id'].'>";
It should be
echo "<div class ='". $row['id'] ."'>";
You should also configure your web server/hosting/localhost to throw a PHP error.
Read this if you are on localhost or your own server:
How can I make PHP display the error instead of giving me 500 Internal Server Error
Read this if you are using shared hosting: How do I displaying details of a PHP internal server error?
echo "<div class ='$row['id'].'>";
First line in while loop should look like this
echo "<div class = '".$row['id']."'>";
or
echo "<div class = '$row['id']'>"
You have mixed different apostrophe, try this:
echo "<div class ='" . $row['id'] . "'>";

While loop and reusing fetch_assoc()

For a project I am building a flash game website, and I would like to know how to reuse this piece of code:
$result = $conn->query("SELECT DISTINCT `category` FROM beoordeling");
<?php
echo "<div class='row list jumbotron'>";
while($data = $result->fetch_assoc()) {
echo "<div class='col-md-3'><a href='category.php?id=" . $data['category'] . "' class='thumbnail'><h4>" . ucfirst($data['category']) . " games</h4>";
echo "<img src='" . $imgLocation . $data['category'].".jpg' class='img-rounded' alt='" . $data['category'] . "' width='304' heigth='182'>";
echo "</a></div>";
}
echo "</div>";
?>
I need to be able to use the $data['category'] again for dynamicly filling my menu with all of the games categories. If I just try to use the while loop again but then only one will work. The other one stays empty. Thanks alot!
You need to adjust the result pointer to point to the beginning of the result set so that you could use it again. Make use of mysqli_result::data_seek() method for this.
Here's the reference:
mysqli_result::data_seek()
So your code should be like this:
<?php
$result = $conn->query("SELECT DISTINCT `category` FROM beoordeling");
echo "<div class='row list jumbotron'>";
while($data = $result->fetch_assoc()) {
echo "<div class='col-md-3'><a href='category.php?id=" . $data['category'] . "' class='thumbnail'><h4>" . ucfirst($data['category']) . " games</h4>";
echo "<img src='" . $imgLocation . $data['category'].".jpg' class='img-rounded' alt='" . $data['category'] . "' width='304' heigth='182'>";
echo "</a></div>";
}
echo "</div>";
// adjust the result pointer to point to the beginning of the result set
$result->data_seek(0);
// now you can use the result set again
// for example, you can iterate through it using while loop again
?>

Increase in Value button "mrk2"

Update post for: Increase in Value button
I made a post asking about how make an increase value button. I got one decent answer, I tried it and it didn't work.
Original:
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th>Down Votes</th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td>" . $row['upvotes'] . "</td>";
echo "<td>" . $row['downvotes'] . "</td>";
}
echo "</table>";
Current:
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th>Down Votes</th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td><a href='action.php?do=up&id=" . $row['upvotes'] . "'>Upvote [" . $row['upvotes'] . "]</a></td>";
echo "<td><a href='action.php?do=down&id=" . $row['downvotes'] . "'>Downvote [" . $row['downvotes'] . "]</a></td>";
}
echo "</table>";
mysqli_close($con);
?>
action.php:
$action = $_GET['do'];
$id = $_GET['id'];
if ($action=="up") {
$result = mysqli_query($con, "UPDATE champion_counters_b SET" . $id . "=" . $id+1 . "'");
}
elseif ($action=="down") {
$result = mysqli_query($con, "UPDATE champion_counters_b SET" . $id . "=" . $id-1 . "'");
}
else {echo "error: 002 / voting error";}
mysqli_close($con);
?>
As you can see I implemented the changes that were recommended and that could of worked, but they didn't rather than updating the data it did nothing. As when pressing "upvote"/"downvote" it grabbed the current value as $id rather than the position of the data to update it.
tl;dr: I tried a fix from the previous thread, it didn't do anything. Help please?
sorry if I have been unclear, let me give it another try:
You insert a link into your table, which calls an action.php. The action.php updates the database. The information needed for updating are passed as GET-parameters.
For updating the database, you will need to know WHAT to do, and secondly, WHICH database entry is actually affected.
Step by step:
First, you have to insert the links into your table:
$result = mysqli_query($con, "SELECT * FROM champion_counters_b WHERE champion_name='" . $search_result . "'");
echo "<table class='champion_counters' border='1'><tr><th>Champion Counter</th><th>Up Votes</th><th></th><th>Down Votes</th><th></th></tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['champion_counter'] . "</td>";
echo "<td>" . $row['upvotes'] . "</td>";
echo "<td><a href='action.php?do=up&id=" . $row['key'] . "'>Upvote</a></td>";
echo "<td>" . $row['downvotes'] . "</td>";
echo "<td><a href='action.php?do=down&id=" . $row['key'] . "'>Downvote</a></td>";
echo "</tr>";
}
echo "</table>";
On clicking the link, we are sending two pieces of information to the action.php.
The action we have to perform, either up- or downvoting. It tells us WHAT to do.
The id of the element we have to up- or downvote. The id tells us WHICH element is affected, and not the number of votes an element has.
As mentioned in my answer to your previous post, $row['key'] should contain the primary key of your database, e.g. an unique identifier. You should have such an identifier in your database, otherwise you cannot make a reference to a specific database entry. However, as we want to update the vote count for a very specific database entry, we need a possibility to uniquely identify this database entry.
In your action.php, you have to do the following:
$action = $_GET['do'];
$id = $_GET['id'];
if ($action=="up") {
mysqli_query($con, "UPDATE champion_counters_b SET upvotes = upvotes + 1 WHERE key = " . $id . "'");
}
elseif ($action=="down") {
mysqli_query($con, "UPDATE champion_counters_b SET downvotes = downvotes - 1 WHERE key = " . $id . "'"); }
else {echo "error: 002 / voting error";}
mysqli_close($con);
We use the id value to select the database entry we have to update. This is done by WHERE key = $id in the UPDATE-statement. The current vote count is taken from the database itself - there is no need to pass the current vote count in the GET-parameters.
After you have updated your database, you can redirect to the original page and reload your table. Then, the updated vote count should show up.

Select 2 tables in one php select statement

I have two tables in mysql
practice_sheets and parent_pin
And I want to use one select statement and get data from both tables.
I have tried
$result = mysqli_query($con,"SELECT * FROM practice_sheets AND parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
and also:
$result = mysqli_query($con,"SELECT * FROM practice_sheets, parent_pin
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
I've never tried to do this before and the previous solutions are what I found searching.
Update
I think it would help if I included my full code. the table data is going into a table on my page. the student_name field from the practice_sheets and parents_student from parent_pin will be matched.
<?php
$con=mysqli_connect();
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM practice_sheets
WHERE student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
$numrows = mysqli_num_rows($result);
if($numrows == 0) {
echo "<div class='alert alert-danger'>";
echo "No Entries, See your instructor for details.";
echo "</div>";
} else {
echo "<table class='mws-table table-striped table-hover'>";
echo "<thead align='center'>";
echo "<tr>";
echo "<th>Sheet Number</th>";
echo "<th>Total Minutes</th>";
echo "<th>Due Date</th>";
echo "<th>PIN</th>";
echo "<th>View</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody align='center'>";
while($row = mysqli_fetch_array($result)){
if ($row["total_min"]>=$row["required_min"]) {
echo "<tr class='success'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
} else {
echo "<tr class='info'>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['total_min'] . "</td>";
echo "<td>" . $row['due_date'] . "</td>";
echo "<td>" . $row['parent_pin'] . "</td>";
echo "<td> <a href='account/practiceSheets?id=" . $row["id"] . "&total_min=" . $row["total_min"] ."&due_date=" . $row["due_date"] ."&mon_min=" . $row["mon_min"] ."&tues_min=" . $row["tues_min"] ."&wed_min=" . $row["wed_min"] ."&thurs_min=" . $row["thurs_min"] ."&fri_min=" . $row["fri_min"] ."&sat_min=" . $row["sat_min"] ."&sun_min=" . $row["sun_min"] ."&name=" . $row["student_name"] ."&assignment=" . $row["assignment"] ."&required_min=" . $row["required_min"] ."'> <i class='icon-eye-open'> </i> </a> </td>";
echo "</tr>";
}
}
echo "</tbody>";
echo "</table>";
mysqli_close($con);
}
?>
$result = mysqli_query($con,"SELECT *
FROM practice_sheets, parent_pin
WHERE student_name = parents_student
AND student_name='$_SESSION[SESS_FIRST_NAME] $_SESSION[SESS_LAST_NAME]'");
Use explicit names for WHERE statament, e.g.
$result = mysqli_query("SELECT student_name.practice_sheets FROM practice_sheets AND parent_pin WHERE student_name.practice_sheets = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
MySQL will not AFAIK automatically check where the constraints are and rightly so considering that you may have conflicting names. Note that this is still pseudo code and you will need to change the fetched results accordingly. Usually it is considered to be good practice to also define explicitly the columns you wish to fetch, but otherwise you can use JOIN as well.
And to help writing shorter code, you can also use shorthands for the table names, e.g.
$result = mysqli_query("SELECT student_name.ps AS name, pin.pp AS pin FROM practice_sheets AS ps, parent_pin AS pp WHERE student_name.ps = '{$_SESSION['SESS_FIRST_NAME']} {$_SESSION['SESS_LAST_NAME']}'");
Update
You also have in your updated version an issue. You call mysqli_fetch_array, which returns an ordered (i.e. numbered) array. If you wish to use keyed, use mysqli_fetch_assoc.
And you are closing the MySQL connection at the moment only if the query was successful. Move mysqli_close outside of the brackets.

Filtering mysql results via select dropdown

I'm a new member of StackOverflow, and although I've been using the website for a long time, it's my first time posting a question, in a hope that someone will be able to help me. I'll start by saying that my knowledge of PHP and MySQL is basic, but what I'm trying to do isn't too complex in my opinion, so hopefully I won't be asking for much. I've done a lot of prior research, but I just couldn't find the right answer.
In short, this is what I'm trying to do:
I've got an html form, which upon submission writes data to a database, and then publishes a table on a separate html page. With each successful submission a new table gets generated and published, while the old one gets pushed underneath. This all works fine, and I've also implemented pagination so that only 5 tables are visible per page.
What I'd like to be able to do is allow people to ONLY view/display results (tables) based on a specific criteria, in this case "rating", by selecting a rating from a drop-down on the page where tables are published. Rating is one of the fields in my form which gets submitted to a database and then published in one of the rows in a table.
Below is the code which publishes tables. Thanks in advance for your help!
<?php
include('dbconnect.php');
mysql_select_db("vtracker", $con);
$result = mysql_query("SELECT * FROM userdata");
$age = "Age:";
$rating = "Rating:";
$country = "From:";
$name = "Name:";
while($row = mysql_fetch_array($result))
{
echo "<table id='mft_table' cellspacing='0'>";
echo "<tbody>";
echo "<tr>";
echo "<td class='row1'>" .$name . " " . $row['personsname'] . "</td>";
echo "<td rowspan='4'>";
echo "<div class='mft_column'>" . $row['mft'] . "</div>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row2'>" . $country . " " . $row['nationality'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row3'>" . $age . " " . $row['personsage'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row4'>" . $rating . " " . $row['rating'] . "</td>";
echo "</tr>";
echo "</tbody>";
echo "<br>";
echo "</table>";
}
?>
for both true and false use can add thid in your code:
if($_POST['rating_dropdown']!='')
{
$temp_rating = $_POST['rating_dropdown'];
$query=mysql_query("SELECT * FROM userdata WHERE rating = '$temp_rating'");
}
else
{
$query=mysql_query("SELECT * FROM userdata");
}
Dunno if this works, it's just a hinch. haha.
It will see if the rating is true(not null), if it's true it will echo the results.
while($row = mysql_fetch_array($result))
{
if ($rating)
echo "<table id='mft_table' cellspacing='0'>";
echo "<tbody>";
echo "<tr>";
echo "<td class='row1'>" .$name . " " . $row['personsname'] . "</td>";
echo "<td rowspan='4'>";
echo "<div class='mft_column'>" . $row['mft'] . "</div>";
echo "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row2'>" . $country . " " . $row['nationality'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row3'>" . $age . " " . $row['personsage'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class='row4'>" . $rating . " " . $row['rating'] . "</td>";
echo "</tr>";
echo "</tbody>";
echo "<br>";
echo "</table>";
}
}
Once the dropdown gets selected and posted to your display page, use this code:
$temp_rating = $_POST['rating_dropdown'];
mysql_query("SELECT * FROM userdata WHERE rating = '$temp_rating'");
Keep in mind, however, that you should be using PDO or mysqli extension, not the mysql extension. According to PHP's website:
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
See also MySQL: choosing an API guide and related FAQ for more
information.

Categories