PHP - User Management Delete Problem - php

I am working on a custom content management system. I was instructed to do some changes, and this is what I need to do. I need to create a user management page which allows the administrator to delete (or disable his status) a user from the database.
This is my User Management Page:
<?php
$query = 'SELECT author_id, author_email as Email, author_name as Name
FROM authors
ORDER BY Name
LIMIT 0, 30';
$result = mysql_query($query);
?>
<table class="listing">
<thead>
<tr>
<td>Author ID</td>
<th>Author E-Mail</th>
<th>Author Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $row = mysql_fetch_array($result); $i++) {
if ($i % 2 == 0) {
echo '<tr class="even">';
} else {
echo '<tr class="odd">';
}
echo "<td>{$row['author_id']}</td>";
echo "<td>{$row['Email']}</td>";
echo "<td>{$row['Name']}</td>";
echo "<td>X</td>";
echo '</tr>';
}
?>
</tbody>
</table>
This is my del-user.php page:
<?php
include('inc/config.php');
$title = 'Delete Individual User';
include('inc/db.php');
include('inc/header.php');
echo '<h2>Delete</h2>';
if (isset($GET['term'])) {
$query = "DELETE FROM authors WHERE author_id = {$GET['term']} LIMIT 1";
mysql_query($query) or die('Failed to delete user');
echo '<p>User Deleted</p>';
echo '<p>Back to <a href="manage-users.php">Manage Users </>.</p>';
} else {
echo '<p>Tried to Delete: "';
echo ($GET['term']);
echo '"</p>';
echo '<p>Nothing to Delete</p>';
}
include('inc/footer.php');
?>
I am new to PHP, but this is not working, the author_id value is not being passed to the other page, and it is being left empty. So I cannot delete anything from the del-users.php page.
I'm guessing that this is the problematic part:
echo "<td>X</td>";
Anybody knows why this is happening?

Several issues:
You send data like this:
del-user.php?term={$row['author_id']}
So that means that actualy $_GET['term'] contains the id.
You catch the value like this:
if (isset($_GET['author_id'])) {
$query = "DELETE FROM authors WHERE author_id = {$_GET['author_id']} LIMIT 1";
And it is not good, since $_GET['term'] contains the id, so you have to fix the lower one to look like this:
if (isset($_GET['term']))
$query = "DELETE FROM authors WHERE author_id = {mysql_real_escape_string($_GET['term'])} LIMIT 1";
Also you need to expand the select query, since you are not actualy fetching the author_id from the db:
$query = 'SELECT author_email as Email, author_name as Name, author_id
FROM authors
ORDER BY Name
LIMIT 0, 30';
Please, escape your variables before you trow them to the database...
http://php.net/manual/en/function.mysql-real-escape-string.php
Cheers

the problem is your query!
$query = 'SELECT author_email as Email, author_name as Name
FROM authors
ORDER BY Name
LIMIT 0, 30';
you are not selecting the author_id

You pass your user id in the url like this :
echo "<td><a href=\"del-user.php?term={$row['author_id']}\"
The you must GET term, not author_id :
$query = "DELETE FROM authors WHERE author_id = {$GET['term']} LIMIT 1";
And by the way, you should read about prepared query and sql injection ;)

use author_id in your query
<?php
$query = 'SELECT author_id, author_email as Email, author_name as Name
FROM authors
ORDER BY Name
LIMIT 0, 30';
$result = mysql_query($query);
?>

Related

Struggling to select a value from another table

Im currently constructing a database using PHP, HTML and MySQL.
I have an events table. Event_id is the primary key. When someone registers for an event they input their student_id and they also select an event from a dropbox that pulls the events from my events table. I have an event_registration table which records all entries into this form. I have event_id in my event_registration table and I'm trying to make it so that when someone selects a certain event, that event's id automatically goes into the event_registration table. My PHP code at present is this:
$student_id = $_POST['student_id'];
$title = $_POST['title'];
$sql = "select event_id from events where title LIKE $title";
$db->select_db($database);
$event_id = $db->query($sql);
$q = "INSERT INTO event_registration (";
$q .= "student_id, event_id, title";
$q .= ") VALUES (";
$q .= "'$student_id', '$event_id', '$title')";
$result = $db->query($q);
The student_id, title, and registraion_id (auto- increment) are inserting fine, but event_id is always showing up as 0, I'm not sure where I'm going wrong. Any help is appreciated.
<td style="width: 176px; height: 23px">Event Title</td>
<td style="height: 23px"><select name="title" style="width: 124px">
<?php
include ("detail.php");
$sql = mysqli_query($db, "SELECT title FROM events");
while ($row = $sql->fetch_assoc()){
?>
<option><?php echo ($row['title']); ?></option>";
<?php
}
?>
</select></td>
my dropdown code
The problem you seem to be having is:
$event_id = $db->query($sql);
Probably doesn't give you the number you're expecting right away, instead you need to fetch like this:
$result= $db->query($sql);
$result = $result->fetch_assoc();
$event_id = $result['event_id'];
However, based on your comment, you're constructing your dropdown with this:
<?php
include ("detail.php");
$sql = mysqli_query($db, "title FROM events");
while ($row = $sql->fetch_assoc()){
?>
<option><?php echo ($row['title']); ?></option>
<?php } ?>
You can do this instead:
<?php
include ("detail.php");
$sql = mysqli_query($db, "SELECT event_id,title FROM events");
while ($row = $sql->fetch_assoc()){
?>
<option value="<?php echo $row['event_id']; ?>"><?php echo ($row['title']); ?></option>";
<?php } ?>
Notice how I'm also adding event_id on the select caluse. WIth this the users will see the title as expected, but you'll get the id directly with POST like this:
$event_id = $_POST['event_id'];
You DO have to change the name of the select dropdown to event_id instead of title like this:
<select name="event_id">

Using PHP variables as name of table in MySQL

I want to use a PHP variable ( $username ) as the name of the SQL table I am creating.
I need to use this because in my webpage each user needs to have his own table where he can put data , When I try to select the data from the table doesn't work, I have tried a lot of times but it is not working, can you help me with this problem?
$result = mysqli_query($mysqli, "SELECT * FROM `$username` ORDER BY id DESC");
and
$sql= "SELECT * FROM `$username` ORDER BY data DESC";
Neither of these do not work , Can you please help me?
This is the code I have
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header("location: login.php");
}
$sql= 'SELECT * FROM '.$username.' ORDER BY data DESC';
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<br/><br/>
<div>
<table align="center" width='100%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Data</td>
<td>Cantiere</td>
<td>Pranzo</td>
<td>Cena</td>
<td>Hotel</td>
<td>Macchina</td>
<td>Note</td>
<td>Edit/Delete</td>
</tr>
<?php
while($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$res['data']."</td>";
echo "<td>".$res['cantiere']."</td>";
echo "<td>".$res['pranzo']."</td>";
echo "<td>".$res['cena']."</td>";
echo "<td>".$res['hotel']."</td>";
echo "<td>".$res['macchina']."</td>";
echo "<td>".$res['note']."</td>";
echo "<td>Edit | <a
href=\"delete.php?id=$res[id]\" onClick=\"return confirm('Are you sure you
want to delete?')\">Delete</a></td>";
}
?>
</table>
</div>
</body>
</html>
and i get the error :
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in index.php on line 36
Try it like this
$sql= 'SELECT * FROM '.$username.' ORDER BY data DESC';
or
$result = mysqli_query($mysqli, "SELECT * FROM " .$username. " ORDER BY id DESC");
When you use a variable you need to use quotes
You should try something like this:
$result = mysqli_query($mysqli, "SELECT * FROM " . $username . " ORDER BY id DESC");
Because SQL does not know what $username is
This goes for both of the query's
As suggested by Loek:
Note that this answer (and the question) contain sql that easily be hijacked! Please prepare your statements before executing them!
Try to add string concatenation:
$result = mysqli_query($mysqli, "SELECT * FROM " . $username . " ORDER BY id DESC");
and
$sql= "SELECT * FROM " . $username . " ORDER BY data DESC";
You need to concatinate your variable into your select statement, i.e.
$sql="SELECT * FROM ".$username." ORDER BY id DESC";
And
$sql="SELECT * FROM ".$username." ORDER BY data DESC";

insert the last 3 visits for each member

i'm designing a Gym Administration System, each member has a unique number stored in a database, each member should type his number when he entered the gym to make sure if his subscription is ended or not, i already design that page, but i need that page to ( add the last 3 visits for each member ) ? how can i do it ?
i need to overwrite the last 3 visits everytime .
ID's 1,2 and 3 are the last visit for member
$con = mysqli_connect('localhost', 'root', '', 'test') or die('error' . mysqli_errno($con));
$query1 = mysqli_query($con, "SELECT * FROM checkin WHERE id = 1");
while ($row = mysqli_fetch_array($query1)){
?>
<div id="checkIn">
<table>
<tr>
<td>Check-In</td>
<td><?php echo $row['timeIn']; ?></td>
<td><?php echo $row['dateIn']; } ?></td>
</tr>
<?php
$query2 = mysqli_query($con, "SELECT * FROM checkin WHERE id = 2");
while ($row = mysqli_fetch_array($query2)){
?>
<tr>
<td>Check-In</td>
<td><?php echo $row['timeIn']; ?></td>
<td><?php echo $row['dateIn']; } ?></td>
</tr>
<?php
$query3 = mysqli_query($con, "SELECT * FROM checkin WHERE id = 3");
while ($row = mysqli_fetch_array($query3)){
?>
<tr>
<td>Check-In</td>
<td><?php echo $row['timeIn']; ?></td>
<td><?php echo $row['dateIn']; } ?></td>
</tr>
</table>
First create a query to fetch all users than loop through them.
$userQuery = $con->prepare("SELECT user_id FROM users");
$userQuery->execute();
$users = mysqli_fetch_array(userQuery);
foreach($users as $user) {
$visitedQuery = $con->prepare("SELECT timeIn, dateIn FROM checkin WHERE user_id = ? ORDER BY id DESC LIMIT 3");
$visitedQuery->execute(array($user['user_id']));
$lastCheckIn = mysqli_fetch_array($visitedQuery);
foreach($lastCheckIn as $lastCheck) {
echo $lastCheckIn['timeIn']." ".$lastCheckIn['dateIn'];
}
}
You mentioned that each user have unique number.
For example:- User A have 123456 unique number.
In Header.php check the condition that user login or not. like:-
if($isset($_SESSION['user_login'])) //you can set your condition here according to your code
{
// first create a new table where user's visit will save.
// Say user database table name is USER_LOGS.which have 3 column.
// ID,User_unique_id,viewpage
$query1 = mysqli_query($con, "SELECT Id,viewpage FROM USER_LOGS WHERE User_unique_id = 12345 ORDER BY Id DESC LIMIT 0"); // that will give you the user's last log.
$total_rows = mysqli_num_rows($query1);
$current_page = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if($total_rows > 0)
{
$row = mysqli_fetch_array($query1);
if($row['viewpage'] != $current_page)
{
mysqli_query($con,"INSERT INTO USER_LOGS (Id,User_unique_id,viewpage)
VALUES ('','123456','".$current_page."')");
}
}
else
{
mysqli_query($con,"INSERT INTO USER_LOGS (Id,User_unique_id,viewpage)
VALUES ('','123456','".$current_page."')");
}
}
The above code is for inert the user log into the database now you can fetch the last three visit by using this query.
mysqli_query($con, "SELECT Id,viewpage FROM USER_LOGS WHERE User_unique_id = 12345 ORDER BY Id DESC LIMIT 0,3");

How to select column from multi table mysql

I have two tables are subscribe and favorite.
subscribe [id subscribeid subscribeto datetime]
favorite [id wordid userid datetime]
So, I want to show these actively in news feed that can separate in each loop, where from which table?my code is look like this
$sql = "(SELECT * FROM favorite) UNION (SELECT * FROM subscribe) ORDER BY datetime DESC";
$result = mysql_query($sql)or die(mysql_error());
while($array = mysql_fetch_array($result)){
if($array['wordid']!=""){
echo "This's favorite feed";
}else{
echo "This's subscribed feed";
}
//echo $array['wordid'];
echo "<hr />";
}
In the condition of if($array['wordid']!="") I think it should work, but when in echo in commented line it always has a values, I don't know why is that.
Please help or suggest, thanks.
You can use alias function to union the result set. Based on cate field you can determine the results from which table.
Use mysqli extension instead of mysql
<?php
$sql = "SELECT id,
subscribeid As common_id,
subscribeto,
datetime, 'subscribe' As cate
FROM subscribe
UNION
SELECT id,
wordid As common_id,
userid As subscribeto,
datetime,
'favorite' As cate
FROM favorite";
$result = mysql_query($sql)or die(mysql_error());
while($array = mysql_fetch_array($result)){
if($array['cate']!="subscribe"){
echo "This's favorite feed";
}else{
echo "This's subscribed feed";
}
//echo $array['wordid'];
echo "<hr />";
}

Get the data of specific user in PHP

Now I have created a login form with a session, what I need now that when the user login with his username and password, get his data such as name, about etc.. and put it in the welcome page.
Currently I have created this code but this code get all users data,
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("usersdata") or die(mysql_error());
$data = mysql_query("SELECT * FROM userid")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['Name'] . "</td> ";
Print "<th>Username:</th> <td>".$info['Email'] . " </td></tr>";
}
Print "</table>";
?>
I hope to find a way to do that. :D
Since you already created a login form with session then you get the data for the current logged in user by doing this:
$_SESSION['userid']: Should be filled in the login page.
$_SESSION['userid'] = $id
Learn more about the sessions: PHP Sessions W3schools
And then:
$query= mysql_query("SELECT * FROM `userid` WHERE `id` = '".$_SESSION['userid']."' ")or die(mysql_error());
$arr = mysql_fetch_array($query);
$num = mysql_numrows($query); //this will count the rows (if exists)
HTML
<html>
//...
<?php if($num > 0){ ?>
<table border="1" cellpadding="3">
<tr><td colspan="2" align="center">Your Info</td></tr>
<tr>
<td>Name: <?php echo $arr['Name']; ?></td>
</tr>
<tr>
<td>Email: <?php echo $arr['Email']; ?></td>
</tr>
</table>
<?php }else{ ?>
User not found.
<?php } ?>
//...
</html>
Although you should use the mysqli_ extension, rather than mysql_, you would want something like:
$result = mysql_query("SELECT * FROM userid WHERE username = '" . $username . "'")
or die(mysql_error());
if(mysql_num_rows($result) == 1) {
//Found the user
$row = mysql_fetch_array($result);
//Results can be accessed like $row['username'] and $row['Email']
} else {
//Too few or too many records were found
}
Note: I've used username='$username' as an example. It would be best to track the user's ID from the login process as the ID refers to a specific row.
$data = mysql_query("SELECT * FROM userid")
Should be
$data = mysql_query("SELECT * FROM userid WHERE Name='$selectedName'")
Of course you need to define $selectedName
I also recommend you read http://dev.mysql.com/doc/refman/5.0/en/select.html to learn about some fundamentals.
Your example code retrieves all users from the database and loops through the data using a while loop.
To get the user that has logged in you need to change your query that fetches the data.
I'm assuming you have a primary key in your table and know the id because the user already logged in.
$data = mysql_query("SELECT * FROM userid WHERE id={$userid}");
$info = mysql_fetch_array( $data );
echo $info['Name'];
$info will now contain all the user info for 1 user, you need to fill $userid with the actual id from the user that is logged in.

Categories