I am working on a HTML website. I am using a MySQL Database and PHP.
The concept so far is fairly simple:
The user can add some text onto the site by clicking on an add button - the user gets directed to a page with a dialogue box
When he clicks submit, that text is in the data base.
The PHP code knows: while the data base has entries -> echo the text onto the HTML website (I added a while loop)
Now my next step is to let the user delete the text. I added a trash can glyphicon onto the HTML site. When the user clicks it, I would like for the current row in the table to be removed. Unfortunately nothing happens!
Here's the code:
<?php
$query = " SELECT * FROM Thesis";
$sql = mysqli_query($conn, $query);
$count = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
?>
<div class="box green-box">
<p><div class="center-box-content">
<!--echo the title -->
<?php echo $row["title"]; ?>
<br>
<!--echo the description -->
<?php echo $row["description"]; ?>
</p>
<div class="lower-right-box-content">
<a href="adminview.php">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button">
<?php
$delquery = " DELETE * FROM Thesis";
mysqli_query($conn, $delquery);
?>
</span>
</a>
</div>
</div>
</div>
<?php };
?>
What am I doing wrong? I know that the main mistake must lie somewhere
in $delquery. But I am lost.
I also know that it would be better to have an ID for each row. But I would like to avoid it, because since we are in a while loop, there must be a way to just delete the current row that the while loop is in, right? That would be my preferred solution.
Lastly, I am very new to programming and not the most elegant programmer yet, please be kind :)
You are going to want a simple ID for your thesis table, something like this:
CREATE TABLE `Thesis` (
`thesis_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`thesis_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I would separate out the PHP from the display code, putting the PHP code at the top of your file. For security and better code, I would use bind variables with PDO (instead of mysqli). But sticking with your original code, I would rewrite it like this:
<?php
// Establish the connection
$sql = mysqli_query($conn, $query);
// Delete a specific element
if (isset($_GET['delete_id']) && $_GET['delete_id'] > 0) {
$query = "DELETE FROM Thesis WHERE thesis_id = " . $_GET['delete_id'];
mysqli_query($conn, $query);
}
// Gather all the rows
$query = "SELECT * FROM Thesis";
$count = mysqli_num_rows($sql);
$rows = [];
while ($row = mysqli_fetch_array($sql)){
$rows[] = $row;
}
?>
<?php foreach ($rows as $row): ?>
<div class="box green-box">
<p><div class="center-box-content">
<!--echo the title -->
<?= $row["title"] ?>
<br>
<!--echo the description -->
<?= $row["description"] ?>
</p>
<div class="lower-right-box-content">
<a href="adminview.php?delete=<?= $row['thesis_id'] ?>">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button"></span>
</a>
</div>
</div>
</div>
<?php endforeach; ?>
The foreach call above is a common PHP shortcut, and the <?= tag will echo back something without having to call echo. The deletion of element using a GET call is not recommended, but for simplicity I'm keeping it in place.
WARNING: BE CAREFUL OF SQL INJECTIONS!!
Now, back to the problem.
First of all, your delete SQL code is run every time a row is inserted, so you will never have rows. First step is to delete
<?php
$delquery = " DELETE * FROM Thesis";
mysqli_query($conn, $delquery);
?>
Next, you want that certain row to be deleted if the user clicks the trash icon. To do this, you can pass the row ID to a PHP page via <a> or $.ajax, then delete it from that PHP page. However, BE CAREFUL OF SQL INJECTIONS
So you would need on your main page:
[delete icon]
And on your deleteRow.php:
$id=$_GET['id'];
//anti-injection code
mysqli_query($conn,"DELETE FROM Thesis WHERE id='$id'");
<a href="adminview.php">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button">
<?php
$delquery = " DELETE * FROM Thesis";
mysqli_query($conn, $delquery);
?>
</span>
</a>
In above code you deleting all the rows. which is wrong. what you should do is:
<a href="adminview.php?id=<?php echo $row["id"];?>">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button"></span>
</a>
in adminview.php
if(isset($_REQUEST['id'])) {
$delquery = " DELETE FROM Thesis WHERE id= '".$_REQUEST['id']."' ";
mysqli_query($conn, $delquery);
}
Related
Hey I've recently been making a website and want to display the data from my database in a grid format opposed to it just listing down the page.
Here is my code right now:
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
I was wondering how I would go about creating a for loop to allow the data from this database in conjunction with the image to span across the page with 7 columns and however many rows down until it reaches the end of the database.
Thanks!
<?php
$query = "Select * from tablename";
$bind = $conn->query($query);
if ($bind->num_rows > 0){
while ($row = $bind->fetch_assoc()){
?>
<p>
<a href="pokemondetails.php?dex=<?php echo $row['dex'];?>">
<?php echo $row['name']; ?>
<br>
<img src="assets/<?php echo $row['dex']?>.png">
</a>
</p>
<?php
}
}
?>
Try this, I just add while loop until End Of file (EOF table)
Hey there guys/girls I have an issue I'm currently trying to work through being a novice to MYSQL / PHP. Currently I'm using Bootstrap accordion collapsible components to display HTML tables (That are reports). Here is my current table:
Current Table in MYSQL.
So as you can see the reports row contains some HTML information which are tables. I wanted to take the information and display it on a webpage assuming that every row was a different report. So I was able to do so with writing this:
<div class="accordion" id="accordionExample">
<?php
require('db.php');
$i = 0;
$sql = "SELECT `report` FROM `automation-reports`;";
$query = mysqli_query($connection, $sql);
while($row = mysqli_fetch_assoc($query))
{
foreach($row as $key => $value)
{
?>
<div class="card">
<div class="card-header" id="heading<?php echo $i ?>">
<h5 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse<?php echo $i ?>" aria-expanded="true" aria-controls="collapse<?php echo $i ?>">
Report #1: 8/6/2018
</button>
</h5>
</div>
<div id="collapse<?php echo $i ?>" class="collapse" aria-labelledby="heading<?php echo $i ?>" data-parent="#accordionExample">
<div style="text-align: center;" class="card-body">
<h3 style="float: left;"> Rating-Pull: </h3>
<?php
$i++;
echo $key;
echo "$value";
?>
</div>
</div>
</div>
<?php
}
}
?>
</div>
Which is great because it does what I thought I wanted it to do , which is this:
Display Output
What's not so great is now I realize that multiple reports are going to be in one accordion "folder" which is where the reportid row comes into play. So lets say I run my program and two (different) reports run on it but I want it in the say "folder" on the webpage. Both of these get labeled with a reportid of 1.
So what I want to do is loop through reports and then if they have the same ID group them together in that folder and iterate through the whole table like that. So that's the part where I have attempted to do so with a nested loop and SELECT 'report' FROM 'automation-reports' WHERE 'reportid' = '$i' ; and I just ended up getting the first element. Could somebody give me a hand with this and a good explanation so I can understand and learn what's happening?
Thank you!
EDIT:
Maybe a visual would be better?
VISUAL
I think GROUP BY and GROUP_CONCAT are what you are looking for.
SELECT `reportid`, GROUP_CONCAT(`report` SEPARATOR '') as report
FROM `automation-reports`
GROUP BY `reportid`
shoud do the job.
SELECT *
FROM `automation-reports`
GROUP BY `reportid`
will give you one row for each id ie.
id 1,
id 2,
id 3
Or do you want to display each row like so?
id 1, id 1,
id 2,
id 3, id 3,
id 4
if so here is a possible example of combining the reports in a loop first
$sql = "SELECT reportid, GROUP_CONCAT(report SEPARATOR ',') as reports FROM `automation-reports` GROUP BY `reportid`;";
while($row = mysqli_fetch_assoc($query)) {
echo "<div id='{$row['reportid']}'>";
echo $row['reports'];
echo "</div>";
}
I know this isn't the HTML you're after but you should be able to place your HTML in this code
I have a website where I am getting information of college student profiles on a database and displaying it as a linked collection. When I'm looping through the database I want to give each row a specific link to the profile of the student. Right now I am linking it to "profilePage.html" with generic information but I want it to be correlated with the row the user chose on the last(college) page.How do I save/transfer that information to the page. I do not want multiple profile pages but one template that is filled with the user previous choice.
<?php
$result = mysql_query("SELECT * FROM student_info WHERE college='Boston College'", $db);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
?>
<a href="profilePage.html" class="collection-item">
<div class="row summary">
<div class="col s4 center">
<img class = "profile-pic" src="img/defaultProfile.jpg">
</div>
<div class="col s8">
<div class="title"> <?php echo $row[student_Name]; ?> </div>
<div class="black-text condensed thin"><i class="tiny material-icons">today</i> Founder, CEO at Linkle since January 1st, 2015</div>
<div></div>
</div>
</div>
</a>
<?php } ?>
Key thing, my urls are mysite.com/college.php and have no id's to specify them.
Structure of the Database student_info:
Shows the structure of the database
First, do you have an URL Rewriting ? If not, your target page should be a PHP page, like profilePage.php.
Your link to this page have to include a parameter (Query String) which is, for example, the student's ID :
<a href="profilePage.php?id=<?php echo $row['id'] ?>" class="collection-item">
This type of URL will be generated: profilePage.php?id=36
In profilePHP.php, retrieve the parameter in the Query String :
<?php
$idStudent = mysql_real_escape_string($_GET['id']);
?>
mysql_real_escape_string() is really important, it prevents SQL injections.
After that, you could retrieve the student's informations with a SQL query.
<?php
$idStudent = mysql_real_escape_string($_GET['id']);
$sql = sprintf("SELECT * FROM student_info WHERE id = %s", $idStudent);
$query = mysql_query($sql);
$student = mysql_fetch_object($query);
// you should check if the ID exists, and if there is 1 result
?>
<p>Student name is <?php echo $student['student_Name'] ?></p>
A little advice: mysql_query() will disappear soon, you should take a look at PDO.
<li class="list-group-item">
<a href="/user/Michael" class="thumb-sm pull-left m-r-sm">
<img src="http://www.gravatar.com/avatar/8b7a9ba3cbf958009080f6da12a55029?&d=mm&r=g?&d=mm&r=g&s=215" class="img-circle">
</a>
<a href="user/Michael" class="clear">
<strong class="block">
<?php include '/includes/connection.php';?>
<?php echo $products['Title'] ; ?>
</strong>
<?php include '/includes/connection.php';?>
<small><?php echo $products['Followers'] ; ?> Followers </small>
</a>
</li>
<li class="list-group-item">
<a href="/user/Steven" class="thumb-sm pull-left m-r-sm">
<img src="http://www.gravatar.com/avatar/a5fb2decd550cdf33cbb8ce7566ba772?&d=mm&r=g?&d=mm&r=g&s=215" class="img-circle">
</a>
<a href="/user/Steven" class="clear">
<strong class="block">
<?php include '/includes/connection.php';?>
<?php echo $products['Title'] ; ?>
</strong>
<small><?php echo $products['Followers'] ; ?> Followers</small>
</a>
</li>
do i need to manually insert for every content?
I have over 100 contents how can i automatically insert in every line like content 1 display row 1 followers and content box 2 display row 2 followers and so on
The trick here is to make a loop within the code. This means you have to generate all content from out of the database or it's not gonna work. Let me show you an example:
<ul>
<?php
$sql = "SELECT ProjectId, ProjectTitel, ProjectExpertise
FROM project";
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1,$ProjectId,$ProjectTitel,$ProjectExpertise);
while (mysqli_stmt_fetch($stmt1)){
?>
<li class="wow fadeInLeft" data-wow-offset="30" data-wow-duration="1.5s" data-wow-delay="0.15s">
<a href="inc/elements/project.php?id=<?php echo $ProjectId; ?>" class="meer">
<img src="img/portfolio/<?php echo $ProjectId; ?>/thumbnail/1.jpg" alt="<?php echo $ProjectTitel; ?> project">
<div class="project-info">
<div class="project-details">
<h5 class="witte-text blauwe-streep-onder">
<?php echo $ProjectTitel; ?>
</h5>
<div class="details witte-text">
<?php echo $ProjectExpertise; ?>
</div>
</div>
</div>
</a>
</li>
<?php
}
?>
</ul>
I start an UL outside of the PHP code and then I start my PHP query, as you see, i select the items i need from the database. Here i create a while loop and run through my setup of the list element. As you see, i use my items within the project id link (the link is an ajax call to another page), the thumbnail needed to show the picture, the title and the expertise i used.
In your case, the while loop you need requires more than just the the title and followers. I think you need as well an userid / username so you can take in account which user it is. Your loop would now proces all on the same user, since its staticly defined in your code. Also the avatar picture is staticly defined. Let me try to resolve some for you.
<?php
include '/includes/connection.php';
$sql = "SELECT products.title, products.followers
FROM products"; // as example query
$stmt1 = mysqli_prepare($con, $sql);
mysqli_stmt_execute($stmt1);
mysqli_stmt_bind_result($stmt1,$title, $followers);
while (mysqli_stmt_fetch($stmt1)){
?>
<li class="list-group-item">
<a href="/user/Michael" class="thumb-sm pull-left m-r-sm"> <!-- make the username also to be pulled out of a database. -->
<img src="http://www.gravatar.com/avatar/8b7a9ba3cbf958009080f6da12a55029?&d=mm&r=g?&d=mm&r=g&s=215" class="img-circle">
</a> <!-- you should save the avatar link into a database as well -->
<a href="user/Michael" class="clear"> <!-- make the username also to be pulled out of a database. -->
<strong class="block">
<?php echo $title; ?>
</strong>
<small>
<?php echo $followers; ?>
Followers
</small>
</a>
</li>
<?php
}
?>
This as example. As you see, i added notitions behind some code, to explain this should also be dynamic, since it will help you Remember. being a programmer is to find shortcuts on how you display your information. Code that repeats itself constantly with a changing variable should always be looped, to make sure you dont type unneccesairy code.
Since I dont know how your database is made, i can only guess, Michaels name is probably linked to an ID in the same table your products are, which you can use then in to pull out of the database, by searching in your user table. I hope I make sense here. For instance, your products.userid should be as well in your user table as user.userid. Most likely the userid will have a name linked to it in the user table.
$sql = "SELECT products.title, products.followers, products.userid, user.userid, user.username
FROM products, user
WHERE user.userid = product.userid";
So now you have in each row as well the name of the person of who's title it is. And that you can echo out again in the code i put up. (make sure you bind the result in the same order as you pulled them up)
Writing code is all about making it easier to display your information. Loops is and stays the keyword here, as NadirDev explains.
I hope I helped you getting on the right track.
I'm new to php and mysql so sorry if i'm doing it wrong. i have a page on my site that lists the reviews that members give to other other users.
Basically i have approved and deleted in my database which means that after a user sends the review it has to be reviewed by the user before it gets displayed.
once the user clicks the approved image which is a tick it goes to approved_review.php and in their i have my sql code to update the value from 0 to 1 in my database.
It should work exactly the same for the delete but obviously instead of updating the approved column it will update deleted.
the code i have tried is not working i have been working on this for quite some time and can;t figure it out.
Can someone please tell me where i'm going wrong?
Heres the code:
<?php
$reviews_set = get_pending_reviews();
while ($reviews = mysql_fetch_array($reviews_set)) {
?>
<p> </p>
<div class="pending-review-content">
<?php
$date = $reviews['date_added'];
?>
<div class="prof-content-pend-reviews" id="reviews">
<div class="message_pic"><?php echo "<a href=\"profile.php?id={$reviews['from_user_id']}\">
<img width=\"50px\" height=\"50px\" src=\"data/photos/{$reviews['from_user_id']}/_default.jpg\" /></a>";?>
</div>
<div class="reviews-date"><? echo "$date"; ?></div>
<div class="reviews-from">
<?php echo "<a href=\"profile.php?id={$reviews['from_user_id']}\">{$reviews['display_name']}"; ?>
</a> Wrote:
</div>
<div class="reviews-content">
<?php echo "{$reviews['content']}"; ?>
</div>
</div>
<div class="reviews-approve">
<img src="assets/img/icons/tick.png" width="30" height="25" /></div>
<div class="reviews-delete">
<img src="assets/img/icons/cross.png" width="30" height="25" />
</div>
<? } ?>
approved_review.php function:
<?
$sql = "UPDATE `playtime`.`ptb_reviews` SET `approved` = '1' WHERE `ptb_reviews`.`id` =".$_SESSION['user_id']."";
echo "<div class=\"infobox1\">review approved.</div>";
?>
Your approach seems logical. After you loop through your reviews, you click on the tick or delete pngs to update or delete.
So, in approved_review.php
<?php
//you are missing the connection to your mysql database...
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$sql = "UPDATE `playtime`.`ptb_reviews` SET `approved` = '1' WHERE `ptb_reviews`.`id` =".$_SESSION['user_id']."";
//execute the mysql query
$r = mysql_query($sql);
if (!mysql_error())
{
echo "<div class=\"infobox1\">Review Approved.</div>";
}
?>
a little edit rrrfusco's post
// or die for details if mysql_query won't work correct
$r = mysql_query($sql) or die (mysql_error());