UPDATE I added this to my while loop during the array fetch. Does this work, or is there a better way? It is showing the correct pic now:
$query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
if($username == $row['username']) { //<--- NEW CODE
$profile_pic = '<img src="' . $row['avatar'] . '" style = "width:70%" alt="Profile Photo"/>';
}
}
}
I tried to search for this, but couldn't find anything similar. I've edited nothing on my profile.php page. I created several test users to test the functionality of a live user search. Everything was working fine until I logged in as another user. The profile pic that is displayed in the browser is pointing to a different user, yet the real image path is correctly stored in the database. I deleted all users except for the original two, and nothing has changed. I haven't changed any code, but I will show the relevant code that displays the profile pic and the live search.
(Note: I will work on more secure queries later. Learning to translate into prepared statements as I go.)
The pic container from profile.php. I'm even echoing the current username temporarily at the top left just to show that it's getting the correct name.
<div id="avatar-container" class="dsh-display-container">
<button type="button" id="upload-toggle"><i class="fa fa-camera"></i><span> Update Avatar </span></button>
<?php
$query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$profile_pic = '<img src="' . $row['avatar'] . '" style = "width:70%" alt="Profile Photo"/>';
}
}
?>
<?php echo $avatar_form; ?>
<?php echo $profile_pic; ?>
</div>
This is what is displaying on my profile:
On my search.php page, it displays correctly.
This is what shows the info:
try {
$db = new PDO("mysql:host=localhost;dbname=devSocial", "xxxxxxxxx", "xxxxxxxxxxxxx");
} catch(Exception $e) {
die("ERROR: ".$e->getMessage());
}
if (isset($_POST['username']) && $_POST['username'] != "") {
$req = $db->prepare("SELECT * FROM `users` WHERE username LIKE :username");
$req->execute(array(
'username' => '%' . $_POST['username'] . '%'
));
if ($req->rowCount() == 0) {
echo "Sorry. No one by that name found.";
} else {
while ($data = $req->fetch()) {
$data['gender'] = ($data['gender'] == 'm') ? 'male' : 'female';
?>
<div class="user">
<div class="img-container">
<img src="<?php echo $data['avatar']; ?>" class="userImage">
</div>
<span class="username"><?php echo $data['username']; ?></span><br/>
<span class="gender"><?php echo $data['gender'];?></span><br/>
<span class="profession"><?php echo $data['profession']; ?></span><br/>
<span class="uni"><?php echo $data['uni']; ?></span><br/>
<span class="degree"><?php echo $data['degree']; ?></span><br/>
<span class="major"><?php echo $data['major']; ?></span><br/>
<hr/>
</div>
I completely removed testUser from the database, and the profile displays correctly.
My main concern is that I changed nothing in those two segments of code and I was able to alternate between users. What is this voodoo? I've logged in as the two different users off and on for weeks and it showed correctly. I even went over my local history with a fine toothed comb and nothing has been changed. If someone could help that would be great because I've spent far too long. If I delete all but my "csheridan" user, it works. If I delete then recreate the testUser, my "csheridan" user now shows the default avatar. This is a major bug and I'm lost.
Your photo query is getting all your users:
$query = "SELECT * FROM users";
This needs to be fixed
The user never returned to post his comment as an answer, so I'll post it here. It was actually a combination of comments.
When I ran my query
$query = "SELECT * FROM `users`";
it gets all users from the DB. And during my original while loop
while($row = mysqli_fetch_assoc($result) {
$profile_pic = '<img src="' . $row['avatar'] . '" style="width:70%" alt="Profile Photo"/>';
it was always returning the last user in the database.
This is what fixed it. I added an if condition to match the row specifically to the current username:
$query = "SELECT * FROM `users`";
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
if($username == $row['username']) { //<-- THIS RIGHT HERE
$profile_pic = '<img src="' . $row['avatar'] . '" style = "width:70%" alt="Profile Photo"/>';
}
}
}
echo $avatar_form;
echo $profile_pic;
If any people search for this question, please use more secure code. I'm learning PDO and prepared statements, and the code will be replaced with it later.
Related
I am working on a project, for school. I currently have a product page to display an assortment of item includes image, description and price etc...
Under each product I have a delete button, when logged in as admin, which displays fine.
if (is_admin())
echo '<button>Delete item</button>'; }
I want to know how remove the row of data from MySQL table on clicking the delete button.
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
$deleted = mysql_query($db, "DELETE FROM products");
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'$];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo '' . $product_name ."</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo '<button>Delete item</button>';
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
<!-- end snippet -->
You should post to a url with the id in the post data, then redirect back to where you were.
<?php
//html on productpage
if(isset($_GET['product_deleted'])){
if($_GET['product_deleted'] === 'true'){
echo 'The product was deleted';
}else{
echo 'The product could not be deleted';
}
}
if (is_admin()){
/**
* It's a good idea for the page that deletes to be different from the one your on, so that when you redirect back,
* they can refresh the page without getting something
* along the lines of 'refreshing with page will re-post the data'
*/
?>
<form method="POST" action="/product/delete.php">
<button>Delete item</button>
<input type="hidden" name="id" value="<?php echo $image_id; ?>" />
</form>
<?php
}
//PHP on /product/delete.php
if(is_admin() && $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])){
//delete sql here
header('Location: /productpage.php?product_deleted=true'); //redirect back
}
One approach
Change the button to a a element and make the href look like this:
yourdomain.tld/products/delete/{id}
You have to echo the primary key from your mysql database at the id position. It will look like this:
yourdomain.tld/products/delete/5
Then you have to change your .htaccess in a way that all requests go to your index.php in your root project. At the index.php you can do the actually query then.
Update
Keep in mind that anyone visiting this URL can delete products with this approach. You have to make sure that only the admin can do that. The preferred method is a POST request.
You can also send the primary key parameter to your PHP script you are just showed. With this approach you don't need to edit your .htaccess. You may pass it as an URL parameter like this:
yourdomain.tld/your-script.php?delete-product={id}
In your script you can get the parameter like this:
<?php
if (isset($_GET['delete-product'])) {
// your mysql query to delete the product
} else {
// something else
}
If you want to delete the entire row of an record from your db you can do like this. So that you can pass the product id and delete the row. Just bind the id with query using bind parameters concept
$knownStmt=mysqli_prepare($conn, "DELETE FROM `YourTableName` WHERE `pdt_id` = ?;");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$pdt_id);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_close($knownStmt);
}
I have a Delete.php page that deletes records based on their ID.
When there is an ID, i.e., Delete.php?id=3610, all is well, and it functions as expected.
If I just go to "Delete.php" and that's it - no ID, it generates:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"
From the little I understand, it is doing this because I am trying to pass a nonexistent variable into my query.
I have been trying to put if (empty($_POST['id'])) { } in different places, which removes the error, but breaks something else.
Here is my code:
<?php
require_once 'functions.php';
$conn = mysqli_connect("localhost", "user", "pass",'db');
writeHead("Delete Track");
if (isset($_POST['delete'])) {
$trkid = $_POST['trkid'];
$query = "DELETE FROM track WHERE TrackID=$trkid";
mysqli_query($conn, $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn)>0) {
header("Location: Display.php?action=deleted&id=$trkid&status=deleted");
exit();
}
echo "<p class='error'>Unable to update record</p>";
} else {
if (!isset($_GET['id'])) {
echo "<p class='error'>No Track ID provided.<br><a href='Display.php'>Return to display page.</a><p>";
}
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}
?>
<p>Track Information:</p>
<p><?php echo "<b>ID: $trkid <br>Title: $Name</b>"; ?></p>
<form method="post" action="Comp3Delete.php">
<p>
<input type="hidden" name="trkid" value="<?php echo $trkid; ?>">
<input type="submit" name="delete" class="btn" value="Confirm Delete">
</p>
</form>
<p>Return to Track Table Display</p>
<?php writeFoot(); ?>
Your post code is fine. it's the GET code that's wrong:
if (!isset($_GET['id'])) {
^^^^^^^^--check if the parameter exists
}
$trkid=$_GET['id'];
^---try to use the parameter ANYWAYS, even if it doesn't exist.
$trkid=$_GET['id']; has no condition so it runs even when no id is passed which generates the error. Your code should go like this:
if(isset($_GET['id'])){
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}
i am making a profile.php page and i would like it to show the user all his projects, this is my first time doing something like this, and i cant find a solution for it
code to show the projects :
$username = $_SESSION['username'];
if ($_SESSION['type'] = "developer"){
$q = "SELECT * FROM `projects` WHERE `developer` = '$username'";
$result = mysqli_query($con,$q);
$row = mysqli_fetch_array($result);
$numrows = mysqli_num_rows($result);
if(empty($numrows)){
echo'
<div class="row">
<div class="col-lg-12 newp">
<p><span class="glyphicon glyphicon-plus plus"></span>Add a new project</p>
</div>
</div>';
}else{
$p_id = $row['project_id'];
$p_name = $row['project_name'];
$p_owner = $row['owner'];
$p_developer = $row['developer'];
$p_price = $row['price'];
$p_date_started = $row['date_started'];
$p_date_end = $row['date_end'];
$p_paid = $row['paid'];
//foreach project the user has do this :
echo"
<div class=\"row\">
<div class=\"col-lg-12\">
<p>$p_name </br>owner : $p_owner, developer : $p_developer, price : $p_price$</br>started : $p_date_started, ends :$p_date_end, paid :$p_paid</p>
</div>
</div>";
}
}
} else {
while($row = mysqli_fetch_array($result)) {
$p_id = $row['project_id'];
...
Besides the other answer given:
You're presently assigning instead of comparing with
if ($_SESSION['type'] = "developer"){...}
^
which the above will fail and everything inside that conditional statement and should read as
if ($_SESSION['type'] == "developer"){...}
^^
with 2 equal signs.
Make sure the session has also been started, it's required when using sessions.
session_start();
You're also open to an SQL injection. Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
i'm kind of a new player in php and sql field.
i'm trying to delete identity from my persons table when clicking on the remove link (or button)
can somebody tell me what am i doing wrong?
this is my php code:
<?php
$db = new DB();
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
$sql ="SELECT f_name, phone, c.id as idc
FROM contacts as c
WHERE c.cg_id = '$cg_id'";
$result = $db->mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article>";
if(isset($_POST['idc'])){
$idco = $_POST['idc'];
$removeQuery = "DELETE FROM contacts as c WHERE id=".$idco." ";
$resultt = mysql_query($removeQuery);
if($resultt) {
header('Location: '.$_SERVER['REQUEST_URI']);
}
echo "<script>window.location.reload(true);</script>";
}
}
}else {
echo "Please edit senior profile for monitoring!";
}
?>
Try this (obviously replacing "localhost", "dbuser", "dbpassword" and "database_name" with the details for your mysql server and database):
<?php
$db = new mysqli("localhost","dbuser","dbpassword","database_name");
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
// I've moved the deletion code to BEFORE the select query, otherwise the
// query will be shown including the to-be-deleted data and it is then deleted after it is displayed
if(isset($_GET["del"])){ // <--- this was $_POST["del"] which would have been unset
$idc = $_GET["del"];
if($db->query("DELETE FROM contacts WHERE id=$idc")){
echo "deleted";
} else {
echo "fail";
}
}
$sql ="SELECT photo, f_name, phone, street, street_num, city, l_name, c.id as idc FROM contacts as c, address as a WHERE c.cg_id = '$cg_id' and a.id = c.address_id";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<article class='contact5 lior'>";
echo "<img class='CSImage' src='" .$row["photo"]."'>";
echo "<section class='generalFormTextW nameCPosition'> " .$row["f_name"]." ".$row["l_name"]."<br></section>";
echo "<section class='generalFormTextW phoneCPosition'> " .$row["phone"]."<br></section>";
echo "<section class='generalFormTextB addressCPosition'>".$row["city"].", <br> ".$row["street"]." ".$row["street_num"]. "<br></section>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article></article>";
}
}
?>
Notice that I'm changing the way you're using mysqli so that you are using it directly rather than as a member of the DB object which is the way I've seen it used elsewhere - It looks to me as if you don't actually open the database connection (although maybe you just didn't include it because it showed your password?)
**EDIT: I've changed $_POST["del"] to $_GET["del"] -- because you are setting del in a url ("contacts2.php?del=") this will be GET not POST.
**EDIT: I've moved the deletion code so that it fixes the problem where you have to refresh the page to see the data with the record deleted - previously the information was shown and THEN deleted, we want to delete THEN show.
I have a gallery that I'm able to upload images with a title and a short description about the image. I store the images in a folder on my ftp and the data in a database. Here is a screen shot of the database.
I want to give my client a little more control over the gallery by allowing them to update the gallery and delete posts in the gallery. Right now I want to focus on the DELETING part.
I'm using the following code to try and delete the images/post by trying to select by id and delete.
When executing the delete script on the site I get no errors on the page or on my ftp, but the image does not delete.
The end result I'm looking for would be to have the row deleted from the table and the image deleted from the ftp.
I'm very new to php and know I need to learn much more about it, but if someone could help out I would appreciate it. I apologize for the code dump, but not sure how to ask the question without showing what I'm working with.
DELETE CODE:
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//deleting the row from table
$result=mysql_query("DELETE FROM images where id='$id' limit 1;");
//redirecting to the display page (index.php in our case)
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>
This is the code I'm using to to access the image on the modify-gallery page
modify-gallery code:
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
/* be safe, not sorry */
foreach ($_REQUEST as $k => $v) {
$_REQUEST[$k] = mysql_real_escape_string($v);
}
/* take cat from url if exists */
$category = #$_REQUEST["category"] ? $_REQUEST["category"] : null;
$images = mysql_query(
$category ?
sprintf(
"SELECT * FROM images WHERE data_type = '%s'",
$category
) :
"SELECT * FROM images"
);
if ($images) {
$total = mysql_num_rows($images);
if ($total) {
$per = 12;
$page = #$_REQUEST["page"] ? $_REQUEST["page"] : 1;
$pages = ceil($total/$per);
}
mysql_free_result($images);
}
?>
and then this is used to display the images/posts and lists the delete and update button..(same page)
<div class="row">
<ul id="stage" class="portfolio-4column">
<?php
if ($category) {
$images = mysql_query(sprintf(
"SELECT * FROM images WHERE data_type = '%s' ORDER BY id DESC LIMIT %d, %d",
$category, ($page - 1) * $per, $per
));
} else $images = mysql_query(sprintf(
"SELECT * FROM images ORDER BY id DESC LIMIT %d, %d",
($page - 1) * $per, $per
));
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>" data-type="<?=$image["data_type"] ?>">
<div class="grid_3 gallerybox-admin">
<div class="overallheight-admin">
<div class="gallerybox-admin"><a class="fancybox" rel="<?=$image["data_type"] ?>" href="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/gallery/<?=$image["file_name"] ?>" title="<?=$image["title"] ?>">
<img src="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/gallery/<?=$image["file_name"] ?>" alt="<?=$image["title"] ?>" class="max-img-border"></a></div>
<div class="galleryh"><?=$image["title"] ?></div>
<div class="galleryp"><?=$image["description"] ?></div>
</div>
<div class="grid_1"><h4 class="btn-green">Delete</h4></div>
<div class="grid_1"><h4 class="btn-green">Update</h4></div>
</div>
</li>
<?php
}
?>
</ul>
</div>
Code from Stack Overflow (Currently Using):
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//Select image_name(if not known)
$img = mysql_query("Select file_name from images where id=\"$id\"");
$img_res = mysql_fetch_array($img);
$filename = $img_res[0];
unlink($_SERVER['DOCUMENT_ROOT'] . "/images/gallery/" . $filename);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id=\"$id\" limit 1;");
//redirecting to the display page
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>
fix this in delete button html, to pass the file name by the url
<h4 class="btn-green">Delete</h4></div>
In your remove.php
include("/connections/dbconnect.php");
$filename = isset($_GET['value']) ? $_GET['value'] : NULL;
if (!empty($filename)) {
$delete = unlink("images/gallery/" . $filename);
if($delete){
$result = mysql_query("DELETE FROM images where file_name="'. mysql_real_escape_string($filename)."' limit 1;")";
header("Location:succes_page.php");
}else{
header("Location:failure_page.php");
}
}else{
header("Location:failure_page.php");
}
side note try to update your mysql_* functions to PDO or mysqli
"The end result I'm looking for would be to have the row deleted from the table and the image deleted from the ftp."
the row deleted from the table ✓
But you still need to remove the actual file from your server to do so use unlink($fileName);
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
// Delete the file from the server
unlink($_SERVER['DOCUMENT_ROOT'] . "{Path Where Your Images stored}" . $row['file_name']);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id='$id' limit 1;");
As you can see I used the $row['file_name'] to get the file name from you database (good to show us your table structure)
To delete a file from the ftp you should use
unlink(filename with complete path);
Complete Code:
//Change Delete code to following
<?php
//including the database connection file
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
//getting id of the data from url
$id = isset($_GET['id']) && $_GET['id'] == $row['id'];
//Select image_name(if not known)
$img = mysql_query("Select image_name(your column) from images where id=\"$id\"");
$img_res = mysql_fetch_array($img);
$filename = $img_res[0];
unlink("path to file".$filename);
//deleting the row from table
$result=mysql_query("DELETE FROM images where id=\"$id\" limit 1;");
//redirecting to the display page (index.php in our case)
echo '<table align="center" width="100%" height="100%" border="0"><tr align="center" valign="center"><td><h2>Deleting Image</h2></td></tr></table>';
echo '<meta http-equiv="refresh" content="5;URL=/admin/modify-gallery.php">';
?>