Home displaying all users info - php

I built a simple CRUD using PHP but the home file is displaying all the info I have in the database, even the info added by other users. How can I filter this to show only the logged users info?
Here is the home.php file:
<?php
session_start();
if(isset($_SESSION['user'])){
echo "Logado como ". $_SESSION['user'];
}
else {
echo"<script language='javascript' type='text/javascript'>alert('Voce deve estar logado');window.location.href='index.php';</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Perfil</title>
</head>
<body>
</br>
Sair</br>
<h2 align="center">Lista de contatos</h2>
<table align="center" border="1">
<tr>
<th>Nome</th>
<th>Telefone</th>
<th>Endereco</th>
<th>Editar</th>
<th>Deletar</th>
</tr>
<?php
mysql_connect("localhost", "root","") or die(mysql_error()); //Connect to server
mysql_select_db("forms") or die("Cannot connect to database"); //connect to database
$query = mysql_query("Select * from contatos"); // SQL Query
while($row = mysql_fetch_array($query))
{
Print "<tr>";
Print '<td align="center">'. $row['nome'] . "</td>";
Print '<td align="center">'. $row['telefone'] . "</td>";
Print '<td align="center">'. $row['endereco'] . "</td>";
Print '<td align="center">Editar </td>';
Print '<td align="center">Deletar </td>';
Print "</tr>";
}
?>
</table>
<div align="center">
Adicionar contato</br>
</div>
</body>
</html>

Wherever you are assigning $_SESSION['user'] also assign the user record id to the session.. this way you can add a where clause to your sql and fetch only the desired record..
Quick example:
if(isset($_SESSION['user_id'])) {
$sql = "SELECT * FROM contatos WHERE id = {$_SESSION['user_id']}";
// ....
}

Use id or name to differentiate records
$sql = "SELECT * FROM contatos WHERE nome = ".$_SESSION['user'];
$sql = "SELECT * FROM contatos WHERE id = ".$_SESSION['id'];
You must have an autoincremented primary key which wil be your id.

Related

Get a button to delete a record and link to another page

I am displaying an HTML table of appointment bookings, and in each row there is a button that lets the user delete each individual booking. Currently it instantly deletes the record, but I was wondering if it was possible to display some sort of confirmation message before deleting, and if it was also possible to redirect the user to a new page at the same time.
<?php
require('header.php');
require('config/db_connect.php');
adminCheck();
$adminEmail = $_SESSION['email'];
// make sql
$sql = "SELECT * FROM bookings WHERE email='$adminEmail'";
// get query result
$result = mysqli_query($connection, $sql);
// fetch result in assoc array (one row, single student)
$bookings = mysqli_fetch_assoc($result);
if (isset($_GET['deleteId'])) {
// Sanitize input for SQL injection risk
$deleteId = mysqli_real_escape_string($connection, $_GET['deleteId']);
if(!is_null($deleteId)) {
$sqlB = "DELETE FROM bookings WHERE id = '$deleteId'";
mysqli_query($connection, $sqlB);
// Could use a modal otherwise this instantly deletes the record
}
}
?>
<!DOCTYPE html>
<html>
<head>
<h2> All bookings </h2>
</head>
<body>
<table class='striped white'>
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Surname</th>
<th>Date</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
// This doesn't echo the first record in the database for some reason
echo
"<tr>".
"<td>". $row['id'] . "</td>" .
"<td>". $row['firstName'] . "</td>" .
"<td>". $row['surName'] . "</td>" .
"<td>". $row['date'] . "</td>" .
"<td>". $row['timeSlot'] . "</td>" .
"<td>Delete Row</td>" . // trying to link to a new page too
"</tr>";
}
} else{
echo 'no bookings';
}
?>
</tbody>
</table>
</body>
</html>
<?php require('footer.php'); ?>
Furthermore, when the table is displayed, the first record is always missing for some reason too. Is there something I'm missing? Thank you.
For the first problem, you can do something like this, using javascript to ask for confirmation
Delete Row</td>'; }">Delete row </a>
For the second thing, maybe try to add an html redirect only if there is the get variable set
<?php if(isset($_GET['deleteId'])) { ?>
<meta http-equiv="refresh" content="0; url=http://example.com/" />
<?php } ?>

How can I use a select box in HTML to search for a specific user in the database and show that information on a table?

I have a select box that shows the names of all the users in the database, however, I need, using a "Find Button" on the selected user on the combo box, that the data attached to that user shows up on the table
Table that currently shows the data of all users
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
$sql = "SELECT * FROM shifts";
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>
And here's the form that shows the users in the select box
<form name="form1" method="POST" action="">
<select name="getUser">
<?php
$res = mysqli_query($db, "SELECT * FROM shifts");
while ($row = mysqli_fetch_array($res))
{
?>
<option><?php echo $row ["name"]; ?></option>
<?php
}
?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
I'm trying to make it that so when the selected user in the combo box and the find button is pressed, that the data found goes all into the table described above.
I was maybe gonna try to attach a variable to the select box and compare it with the names field on the database.
Something like this
$query = "SELECT * FROM shifts WHERE $name == $nameSelected ";
Thanks.
first echo the user id into the option's value
<option value-"<?echo your id?>"><?php echo $row ["name"]; ?></option>
then when your form submits you get get the value from the $_POST
$userId = $_POST['getUser'];
not you can use the variable to query the database, but you should NEVER put it straight in, you should use PDO prepared statements to prevent injection.
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//something like this
$query = $conn->prepare("SELECT * FROM shifts WHERE id = :id");
$query->bindParam(':id',$userId,PDO::PARAM_INT);
$query->execute()
return $query->fetchAll();// I realised you wanted to get all the shifts so you don want fetchAll(),
notice that in mysql we only use a single = for our comparison unlike php. Also i've changed name to the unique row in the database, as unless your name field is unique how do you know which use called Dan you want?
If you want to do this without re-loading the whole page you will need to look into using Ajax and passing the value of the option tag via jQuery.
Here are some places to start:
https://www.w3schools.com/php/php_mysql_connect.asp
https://www.w3schools.com/xml/ajax_intro.asp
if you are not comfortable with javascript (AJAX), try on your form
<?php $res = mysqli_query($db, "SELECT * FROM shifts"); ?>
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"
<select name="getUser">
<option value='All'>All</options>
<?php
while ($row = mysqli_fetch_array($res)) { ?>
<option value='$row ["name"]'><?php echo $row ["name"]; ?></option>
<?php } ?>
</select>
<button class="btn-primary rounded">Find</button>
</form>
And in your table
<table class="table table-hover">
<thead class="thead-dark"></thead>
<tr>
<th scope="col">Shift ID</th>
<th scope="col">Name</th>
<th scope="col">Origin</th>
<th scope="col">Destination</th>
<th scope="col">Date</th>
</tr>
</thead>
<?php
global $result, $query;
if ($_POST['getUser'] == 'All'){
$sql = "SELECT * FROM shifts";
} else {
$sql = "SELECT * FROM shifts WHERE name = " . $_POST['getUser'];
}
$result = $db->query($sql);
//Fetch Data form database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["shift_id"]. "</td><td>" . $row["name"] . "</td><td>" . $row["origin"] . "</td><td>" . $row["destination"] . "</td><td>" . $row["date"] . "</td><td>"
. $row["password"]. "</td></tr>";
}
echo "</table>";
} else { echo "0 results"; }
?>
</table>

Unable to update MYSQL database table fields using php in XAMPP

So, I am trying to design a php website, and so far it works well in terms of adding an entry to the list table.
The problem is, it isnt able to update the table using edit.php. When the edit link is clicked it shows a message:
"There is no data to be edited."
But if I try to manually put localhost/edit.php**?id=1** it shows the id numbered list and works fine. Please help.
home.php
<html>
<head>
<title>My first PHP Website</title>
</head>
<?php
session_start(); //starts the session
if($_SESSION['user']){ // checks if the user is logged in
}
else{
header("location: index.php"); // redirects if user is not logged in
}
$user = $_SESSION['user']; //assigns user value
?>
<body>
<h2>Home Page</h2>
<hello>!
<!--Display's user name-->
Click here to go logout<br/><br/>
<form action="add.php" method="POST">
Add more to list: <input type="text" name="details" /> <br/>
Public post? <input type="checkbox" name="public[]" value="yes" /> <br/>
<input type="submit" value="Add to list"/>
</form>
<h2 align="center">My list</h2>
<table border="1px" width="100%">
<tr>
<th>Id</th>
<th>Details</th>
<th>Post Time</th>
<th>Edit Time</th>
<th>Edit</th>
<th>Delete</th>
<th>Public Post</th>
</tr>
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("first_db") or die("Cannot connect to database");
$query = mysql_query("select * from list");
while($row = mysql_fetch_array($query))
{
print "<tr>";
print '<td align="center">'. $row['id'] . "</td>";
print '<td align="center">'. $row['details'] . "</td>";
print '<td align="center">'. $row['date_posted'] . " - " . $row['time_posted'] . "</td>";
print '<td align="center">'. $row['date_edited'] . " - " . $row['time_edited'] . "</td>";
print '<td align="center">edit</td>';
print '<td align="center">delete</td>';
print '<td align="center">'. $row['public'] . "</td>";
print "</tr>";
}
?>
</table>
</body>
</html>
)
edit.php
<html>
<head>
<title>My first PHP website</title>
</head>
<?php
session_start(); //starts the session
if($_SESSION['user']){ //checks if user is logged in
}
else{
header("location:index.php"); // redirects if user is not logged in
}
$user = $_SESSION['user']; //assigns user value
$id_exists = false;
?>
<body>
<h2>Home Page</h2>
<p>Hello <?php Print "$user"?>!</p> <!--Displays user's name-->
Click here to logout<br/><br/>
Return to Home page
<h2 align="center">Currently Selected</h2>
<table border="1px" width="100%">
<tr>
<th>Id</th>
<th>Details</th>
<th>Post Time</th>
<th>Edit Time</th>
<th>Public Post</th>
</tr>
<?php
if(!empty($_GET['id']))
{
$id = $_GET['id'];
$_SESSION['id'] = $id;
$id_exists = true;
mysql_connect("localhost", "root","") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //connect to database
$query = mysql_query("Select * from list Where id='$id'"); // SQL Query
$count = mysql_num_rows($query);
if($count > 0)
{
while($row = mysql_fetch_array($query))
{
Print "<tr>";
Print '<td align="center">'. $row['id'] . "</td>";
Print '<td align="center">'. $row['details'] . "</td>";
Print '<td align="center">'. $row['date_posted']. " - ". $row['time_posted']."</td>";
Print '<td align="center">'. $row['date_edited']. " - ". $row['time_edited']. "</td>";
Print '<td align="center">'. $row['public']. "</td>";
Print "</tr>";
}
}
else
{
$id_exists = false;
}
}
?>
</table>
<br/>
<?php
if($id_exists)
{
Print '
<form action="edit.php" method="POST">
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
else
{
Print '<h2 align="center">There is no data to be edited.</h2>';
}
?>
</body>
</html>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
mysql_connect("localhost", "root","") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$details = mysql_real_escape_string($_POST['details']);
$public = "no";
$id = $_SESSION['id'];
$time = strftime("%X");//time
$date = strftime("%B %d, %Y");//date
foreach($_POST['public'] as $list)
{
if($list != null)
{
$public = "yes";
}
}
mysql_query("UPDATE list SET details='$details', public='$public', date_edited='$date', time_edited='$time' WHERE id='$id'") ;
header("location: home.php");
}
?>
and here's the one with ?id=1 in the url
http;//s15,postimg,org/yoabiq0p7/screenshot_21,png (change the commas with fullstops).
You are printing only the edit.php, you need to print the entire edit link.
print '<td align="center">edit</td>';
Replace this line with:
print '<td align="center">edit</td>';
This will solve the problem.
P.S: Be careful, your code is open for SQL Injection! Make sure to use mysql_real_escape_string() in this place:
$id = mysql_real_escape_string($_GET['id']);
If the id is only number, you can do the following too to avoid SQL Injection:
$id = intval($_GET["id"]);
The SQL Injection thing is very serious and you need to filter what comes from outside. I recommend using prepared statement PDO too.
you arent passing the data in the home.php
you are doing normal link to edit.php and you arent passing the data ?id=1
try edit this:
print '<td align="center">edit</td>';
to this:
print '<td align="center">edit</td>';

Why won't this output all of my data from my MySQL Artist table?

I've written up a pretty simple query to output all the data from the Artist table and output them in the established tables. I've double checked the database and all the spelling is correct, but I'm not getting any data being outputted for some reason.
Connector Code
<?php
$conn = mysqli_connect("localhost", "b4014107", "Windows1", "b4014107_db2") or die (mysqli_connect_error());
?>
Main Code
!DOCTYPE HTML>
<html>
<head>
<title>View Artist Table</title>
</head>
<body>
<?php
//Includes speicifed details in order to connect to MySQL
include('ConnectorCode.php');
//mysql_query command is used to select data from Artist table
$result = mysqli_query("SELECT * FROM tbl_Artist");
echo "<table border='1'>";
echo "<tr> <th>Artist ID</th> <th>Artist Name</th> </tr>";
//Results are looped and then displayed in tables
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row ['Artist_id'] . "</td>";
echo "<td>" . $row ['Artist_Name'] . "</td>";
echo "</tr>";
}
echo "</table>";
//Connection is closed
mysqli_close($conn);
?>
<p>Add a new Artist</p>
<p>Edit a current Artist</p>
</body>
</html>
What am I doing wrong?
I think this is your problem:
Use: $result->fetch_assoc()
Instead of: mysqli_fetch_array($result)
I found the solution! I just need to add $conn within the mysqli_query.
$result = mysqli_query($conn, "SELECT * FROM tbl_Artist");

add/remove data from table from previous page

I have an HTML table being displayed from php data and I'm trying to move data from one table to another based on what is clicked. I cannot get it to move from table to another but I"m not getting any code error.
<html>
<head>
<title>View Requests</title>
</head>
<body>
<div class="breadcrumbs">
<center>
Home · Requests
</center>
</div>
<?php
require_once '../../scripts/app_config.php';
require_once '../../scripts/database_connection.php';
// get results from database
$result = mysql_query("SELECT * FROM temp")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Username</th> <th></th> <th></th></tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['User_id'] . '</td>';
echo '<td>' . $row['First_name'] . '</td>';
echo '<td>' . $row['Last_name'] . '</td>';
echo '<td>' . $row['Username'] . '</td>';
echo '<td>Approve</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
</body>
</html>
PHP EDIT SCRIPT:
<html>
<head>
<title>View Requests</title>
</head>
<body>
<div class="breadcrumbs">
<center>
Home · Requests · All Users
</center>
<?php
require_once '../../scripts/app_config.php';
require_once '../../scripts/database_connection.php';
$id = $_GET['id'];
$sql = ("INSERT INTO users
SELECT * FROM temp WHERE User_id = $id ");
mysql_query($sql)
or die(mysql_error());
?>
</body>
</html>
I needed to use
$id = $_get['id];
and in the insert statement i had to replace id with User_id
<html>
<head>
<title>View Requests</title>
</head>
<body>
<div class="breadcrumbs">
<center>
Home · Requests · All Users
</center>
<?php
require_once '../../scripts/app_config.php';
require_once '../../scripts/database_connection.php';
$id = $_GET['id'];
$sql = ("INSERT INTO users
SELECT * FROM temp WHERE User_id = $id ");
mysql_query($sql)
or die(mysql_error());
?>
</body>
</html>

Categories