show all users projects stored in the database - php

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

Related

Updating and deleting from a data table, warning undefined array key

I have been following a lesson on how to make an admin page. I got all the information out of my database to a table on the page. I have an update button and when I change the information and press the button I receive this error: Warning: undefined array key "WebID" in ..\Update.php on line 3
From my search online everyone is trying to change the code so that if array key does not exist: return null. I tried that and the error does not appear no more, but the table does not change.
Any thoughts?
This is the code:
<?php
require_once("DB/DB.php");
$SearchQueryParameter = $_GET["WebID"];
if (isset($_POST["Update"])) {
$Ename = $_POST["Ename"];
$Eid = $_POST["Eid"];
$Erank = $_POST["Erank"];
$Eemail = $_POST["Eemail"];
$Edate = $_POST["Edate"];
$Epassword = $_POST["Epassword"];
$Specialisms = $_POST["Specialisms"];
global $ConnectingDB;
$sql ="UPDATE emp_data SET Ename='$Ename', Eid='$Eid', Erank='$Erank', Eemail='$Eemail', Edate='$Edate', Epassword='$Epassword',
Specialisms='$Specialisms' WHERE WebID='$SearchQueryParameter'";
$Execute = $ConnectingDB->query($sql);
if ($Execute) {
echo '<script>window.open("adminpage.php?WebID=Recored Updated","_self")</script>';
}
}
?>
<?php
<?php
global $ConnectingDB;
$sql = "SELECT * FROM emp_data WHERE WebID='$SearchQueryParameter'";
$stmt = $ConnectingDB->query($sql);
while ($DataRows = $stmt->fetch()) {
$WebID = $DataRows["WebID"];
$Ename = $DataRows["Ename"];
$Eid = $DataRows["Eid"];
$Erank = $DataRows["Erank"];
$Eemail = $DataRows["Eemail"];
$Edate = $DataRows["Edate"];
$Epassword = $DataRows["Epassword"];
$Specialisms = $DataRows["Specialisms"];
}
?>
Html file used to update:
<form id="UpdateForm" method="post" action="Update.php?WebID<?php echo $SearchQueryParameter; ?>">
<div class="form-group">
<button type="submit" name="Update" class="form-control-submit-button">Update</button>
</div>
you have to write the form action like this.. you missed the = sign
action="Update.php?WebID=<?php echo $SearchQueryParameter; ?>"
<form id="UpdateForm" method="post" action="Update.php?WebID=<?php echo $SearchQueryParameter; ?>">
You missed the = sign, in the url

input file Update images inside database

So im trying to change the image thats already inside the database but i cant seem to make it work i kept looking at tutorials and other related questions but couldnt find the exact solution.
this is what i have in php
// Als de knop van de formulier is ingedrukt update de data dat van de database afkomt
if (isset($_POST['update'])) {
if (isset($_GET['id'])) {
$chauffeurs_id = $_GET['id'];
}
if (isset($_POST['Chauffeurs_foto'])) {
$Chauffeurs_foto = $_POST['Chauffeurs_foto'];
}
$sql = "SELECT * FROM chauffeurs ORDER BY 'chauffeurs_geboortedatum ASC";
$sql = "UPDATE `chauffeurs`
SET `Chauffeurs_foto`=$Chauffeurs_foto
WHERE `id`='$chauffeurs_id'";
$result = $conn->query($sql);
if ($result == TRUE){
echo "Aanpassingen zijn voltooid.";
}else{
echo "Error:" . $sql . "<br>" . $conn->error;
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];
Here is my html code:
<!-- Formulier waar alles in komt om te veranderen -->
<form action="" method="post" enctype='multipart/form-data' >
<fieldset>
<legend>Gegevens chauffeur:</legend>
<div class="form-group col-md-4">
//I did it like this so i could style the input file
<input type="file" name="file" id="file" class="inputfile" value="data:image/jpeg;base64, <?php.base64_encode($row['chauffeurs_foto']).?>" />
<label class="btn btn primary"for="file">Choose a file</label>
<input type="submit" value="Chauffeur Aanpassen" name="update">
</fieldset>
</form>
</div>
If anyone of you has a solution i would greatly appreciate it cause i need to finish it for my internship if not i'm just going to keep searching.
File uploads can be tricky. May I suggest you start by reading the documentation on file uploading first?
You will see that your upload can best be reached using the $_FILES array. You will need to store the uploaded data in a variable, using the file_get_contents() method. And it's the file data you'll be uploading to your mySQL server.
Your code should look something like this:
$foto = file_get_contents($_FILES['file']['tmp_name']);
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto`='{$foto}' WHERE `id`='$chauffeurs_id'";
Finally, it's generally not good practise to store file data in your database, as the database size can get out of hand if the number of files you're storing in it grows. You're better off storing files (and images) separately and only storing a file reference in the database.
You have mistakes in your '. Try this code:
session_start();
include "config.php";
if (isset($_POST['update'])) {
if (isset($_GET['id'])) {
$chauffeurs_id = $_GET['id'];
}
if (isset($_POST['Chauffeurs_foto'])) {
$Chauffeurs_foto = $_POST['Chauffeurs_foto'];
}
$sql = "UPDATE chauffeurs SET Chauffeurs_foto = '$Chauffeurs_foto' WHERE id = '$chauffeurs_id'";
$result = $conn->query($sql);
if ($result == TRUE){
echo "Aanpassingen zijn voltooid.";
}else{
echo "Error:" . $sql . "<br>" . $conn->error;
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM `chauffeurs` WHERE `id`='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$chauffeurs_foto = $row['chauffeurs_foto'];
}
$backId = $_SESSION['krijgid'];
}
}
Assuming this is for a real application, you should properly escape SQL values for security reasons. Never trust user input! I'm going to assume you're using mysqli, so I'm using mysql::real_escape_string().
Also, you should properly embed your variables in the query, like so:
if (isset($_GET['id'])) {
$chauffeurs_id = $conn->real_escape_string($_GET['id']);
}
if (isset($_POST['Chauffeurs_foto'])) {
$Chauffeurs_foto = $conn->real_escape_string($_POST['Chauffeurs_foto']);
}
$sql = "SELECT * FROM chauffeurs ORDER BY `chauffeurs_geboortedatum` ASC"; // This statement can you remove, it will never be used in this way
$sql = "UPDATE `chauffeurs` SET `Chauffeurs_foto` = '{$Chauffeurs_foto}' WHERE `id`='{$chauffeurs_id}'";
Succes ermee.

img src showing wrong user from database

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.

AJAX Refresh - Duplicates already loaded Data from Database

On the current page I've been working on, I've set the code out in a way that it would work as a live blog / update kind of system. The problem is, I load the stuff in from my database in my PHP, then I have AJAX which links to another file which will get the database content and refresh the area it is contained in on my site.
Thus' meaning it will auto-update every 15000 miliseconds with the data from the database. The Problem is, it already has the existing data loaded in. So no matter what. every 15000 milisecond it will refresh that div, so data that is already on the page will be duplicated.
More Clear Bulletpoint form
PHP queries database, echo's out the data.
AJAX checks another php page every 15000 miliseconds and echo's that out onto the first page.
Instead of only posting new content, it simply duplicates the original content. (Can have double posts or even tripple. It seems to vary)
I'm only really getting into PHP, I haven't put much time into it, and my knowledge of AJAX is non-exisistant so it presents problem doing something like this. I've tried searching on how to only echo out the existing data on page one, even though page two is handling the updates.
Here is the code however, sorry if it's messy, or does things in correctly. I am still learning this language.
First Page matchdayupdates.php?id=(in this case the id is 6)
$id = $_GET['id'];
if(isset($_GET['id'])) {
$requestMatchInformation = mysqli_query($connect, "SELECT * FROM matchinfo WHERE pageid='$id' LIMIT 500");
while ($row = mysqli_fetch_assoc($requestMatchInformation)) {
$pageid = $row['pageid'];
$type = $row['type'];
$postheader = $row['postheader'];
$postcontent = $row['postcontent'];
$posttime = $row['posttime'];
echo "<div class='center-match-container'>
<div class='match-information'>
<div class='post-container'>
<div class='post-left'>
<img class='post-type-icon' src='images/icons/$type' />
</div>
<div class='post-right'>
<h3 class='header-top'>$postheader</h3>
<span class='time-red-right'>$posttime</span>
<br />
<br />
<p class='post-content'>$postcontent</p>
</div>
</div>
</div>
</div>";
}
$requestEventsInformation = mysqli_query($connect, "SELECT * FROM events WHERE id='$id'");
while($row = mysqli_fetch_assoc($requestEventsInformation)) {
$opponent = $row['opponent'];
$datetime = $row['datetime'];
$datetimedisplay = $row['datetimedisplay'];
$location = $row['location'];
$datepassed = $row['datepassed'];
$rowonescore = $row['rowonescore'];
$rowtwoscore = $row['rowtwoscore'];
$rowoneplayers = $row['rowoneplayers'];
$rowtwoplayers = $row['rowtwoplayers'];
}
}
else {
}
if(!$requestEventsInformation && !$requestMatchInformation) {
echo '<div class="match-notice"><h4>There are currently no updates, this page will auto-update when there are new updates.</h4></div>';
}
echo $id;
?>
<script>
var auto_refresh = setInterval(function () {
$('.center-match-container').fadeOut('slow', function() {
$(this).load('/esports/match/matchinforequest.php?id=<?php echo $id; ?>', function() {
$(this).fadeIn('slow');
});
});
$.ajaxSetup({ cache: true });
}, 15000);
</script>
Second Page matchinforequest.php?id=(again this id is 6)
$id = $_GET['id'];
if(isset($_GET['id'])) {
$requestMatchInformation = mysqli_query($connect, "SELECT * FROM matchinfo WHERE pageid='$id' LIMIT 500");
while ($row = mysqli_fetch_assoc($requestMatchInformation)) {
$pageid = $row['pageid'];
$type = $row['type'];
$postheader = $row['postheader'];
$postcontent = $row['postcontent'];
$posttime = $row['posttime'];
echo "<div class='center-match-container'>
<div class='match-information'>
<div class='post-container'>
<div class='post-left'>
<img class='post-type-icon' src='images/icons/$type' />
</div>
<div class='post-right'>
<h3 class='header-top'>$postheader</h3>
<span class='time-red-right'>$posttime</span>
<br />
<br />
<p class='post-content'>$postcontent</p>
</div>
</div>
</div>
</div>";
}
$requestEventsInformation = mysqli_query($connect, "SELECT * FROM events WHERE id='$id'");
while($row = mysqli_fetch_assoc($requestEventsInformation)) {
$opponent = $row['opponent'];
$datetime = $row['datetime'];
$datetimedisplay = $row['datetimedisplay'];
$location = $row['location'];
$datepassed = $row['datepassed'];
$rowonescore = $row['rowonescore'];
$rowtwoscore = $row['rowtwoscore'];
$rowoneplayers = $row['rowoneplayers'];
$rowtwoplayers = $row['rowtwoplayers'];
}
echo "Received Data";
}
else {
}
The problem is that you are loading the new data into any HTML element with the class center-match-container, but the new data you get with AJAX also contains an element with the class center-match-container, so the second call loads it into two places and so on.
In matchinforequest.php remove <div class='center-match-container'> and the corresponding </div> and it should work.
As a side note, you are not using prepared statements, but instead putting the contents of $_GET['id'] directly into your database query. This means someone could easily wipe your database by setting id to something like 0'; DELETE FROM matchinfo; '. Please look into prepared statements http://php.net/manual/en/mysqli.prepare.php and update your code to avoid this security risk!

Passing php variables through pages / sql

i have the following information displayed
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0)
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
?>
as you can see i have created a game_details page which will display that specific Game_id when the image is clicked
im having trouble understanding how to pull the data out from that game_id in sql on the other page.
here is my attempt on the game_details page
<?php
if (!isset($_GET['$game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id={$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['$game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
This attempt is giving me the "invalid category ID" error
Would appreciate help
There are a few issues with your code.
Let's start from the top.
['$game_id'] you need to remove the dollar sign from it in $_GET['$game_id']
Then, $row['$game_id'] same thing; remove the dollar sign.
Then, game_id={$game_id}' will throw a syntax error.
In your first body of code; you should also use proper bracing for all your conditional statements.
This one has none if (mysqli_num_rows($result) > 0) and will cause potential havoc.
Rewrites:
<?php
$my_query="SELECT * FROM games";
$result= mysqli_query($connection, $my_query);
if (mysqli_num_rows($result) > 0){
while ($myrow = mysqli_fetch_array($result))
{
$description = $myrow["game_description"];
$image = $myrow["gamepic"];
$game_id = $myrow["game_id"];
$gamename = $myrow["game_name"];
echo "<div class='cover'>
</div>";
}
}
?>
Sidenote for WHERE game_id='{$game_id}' in below. If that doesn't work, remove the quotes from it.
WHERE game_id={$game_id}
2nd body:
<?php
if (!isset($_GET['game_id']) || empty($_GET['game_id']))
{
echo "Invalid category ID.";
exit();
}
$game_id = mysqli_real_escape_string($connection, $_GET['game_id']);
$sql1 = "SELECT * games WHERE game_id='{$game_id}'";
$res4 = mysqli_query($connection, $sql1);
if(!$res4 || mysqli_num_rows($res4) <= 0)
{
while ($row = mysqli_fetch_assoc($res4))
{
$gameid = $row['game_id'];
$title = $row['game_name'];
$descrip = $row['game_description'];
$genre = $row['genretype'];
echo "<p> {$title} </p>";
}
}
?>
Use error checking tools at your disposal during testing:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
You want to be using $_GET['gameid'] as that's the parameter you passed.
You are calling for game_id when the link to go to game_details.php has the variable gameid. Either change the parameter in the link to game_id or call for gameid in your $_GET['$game_id'].
Also, as Fred -ii- said, take out the dollar sign in $_GET['$game_id']

Categories