Trying to get a PHP button to delete MySQL rows - php

EDIT: Added the whole code for viewProblems, with the actual credential information just ***.
I've been trying to do this all day and I can't figure it out. What I want is a button at the end of each row (the button shows up correctly) that allows me to delete that row from the MySQL database and the page (doesn't delete anything though). The code I have is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>View Problems</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="well">
<div class="container">
<div class="page-header">
<h1>Jimmy's Laundry</h1>
</div>
<ol class="breadcrumb">
<li>Home</li>
<li>Login</li>
<li>Admin page</li>
</ol>
</div>
</div>
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT problem_id, machine_id, description FROM tbl_problem";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo '<table class="table table-hover"><tr><th>Problem ID</th><th>Machine Number</th><th>Problem Description</th><th> </th></tr>';
while($row = $result->fetch_assoc())
{
echo "<tr><td>" . $row['problem_id']. "</td><td>" . $row['machine_id']. "</td><td>" . $row['description']. "</td><td><form action='deleteProblem.php?name=" . $row['problem_id']."' method= 'post'><input type='hidden' name='id' value=".$row['problem_id']."><input class ='btn btn-danger' type='submit' name='submit' value='Resolved?'></form></td></tr>";
}
echo "</table>";
}
else
{
echo "There are no problems! :)";
}
?>
</table>
</body>
For my main page, viewProblems.php. My deleteProblem.php page is as follows:
<?php
$query= "DELETE FROM tbl_problem WHERE problem_id={$_POST['id']}";
mysql_query ($query);
if (mysql_affected_rows() == 1)
{
echo "<strong>Row has been deleted</strong>"
}
else
{
echo "<strong>Deletion Failed</strong>"
}?>
I've been browsing this site and Google, and I'm trying to get it to work, but it just won't. The page loads the table correctly, but when I click the button, it takes me from website/viewProblems.php to website/deleteProblem.php?name=9(or 10, 11, 12, 13, depending on which button I press) but the page is just white space and the database doesn't get updated.
Any help would be appreciated.
P.S. I know that mySQL_ methods are dated, but we have to use them.

The script that deletes the row is a separate script that is executed in a separate request. Therefor, it is completely isolated from the request that generated the page and you will have to make a new database connection if you want to query or delete data.
In your current situation, you don't make a connection, so that's why the delete statement fails.

Related

Retrieving and displaying logged in info in PHP

I'm trying to retrieve my logged in user data to no avail. Please check my
enter code here private function getUserData($user_name)
{
// if database connection opened
if ($this->databaseConnection()) {
// database query, getting all the info of the selected user
$query_user = $this->db_connection->prepare("SELECT * FROM users WHERE user_name='$_SESSION['user_name']'");
$query_user->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_user->execute();
// get result row (as an object)
return $query_user->fetchObject();
} else {
return false;
}
}
Got the way to move about it ,Thanks #ADyson for the response and follow up
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>YOUR ORDER , We will contact you in a few !!!!</title>
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/main.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<?php include 'header.php'; ?>
<section>
<div class="container">
<strong class="title">MY ORDERS</strong>
</div>
<div class="profile-box box-left">
<?php
require('db.php');
// SQL query
$strSQL = "SELECT user_name, phone, firstname, lastname, service, referal,user_registration_datetime FROM users WHERE user_name = '".$_SESSION['user_name']."'";
// Execute the query (the recordset $rs contains the result)
$rs = mysqli_query($myConnection, $strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysqli_fetch_array
while($row = mysqli_fetch_array($rs)) {
echo WORDING_PROFILE_PICTURE . '<br/>' . $login->user_gravatar_image_tag;
echo "<div class='info'> <strong>NAME:</strong> <span>".$row['firstname'].", ".$row['lastname']."</span></div>";
echo "<div class='info'><strong>phone No:</strong> <span>".$row['phone']."</span></div>";
echo "<div class='info'><strong>SERVICE:</strong> <span>".$row['service']."</span></div>";
echo "<div class='info'><strong>REFERAL:</strong> <span>".$row['referal']."</span></div>";
echo "<div class='info'><strong>DATE QUERIED:</strong> <span>".$row['user_registration_datetime']."</span></div>";
}
// Close the database connection
mysqli_close($myConnection);
?>
<div class="options">
<a class="btn btn-primary" href="editprofile.php">Edit Profile</a>
<a class="btn btn-success" href="changepassword.php">Change Password</a>
</div>
</div>
</section>
<script src="assets/js/jquery-3.1.1.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>

Select from database and echo on html page

Im trying to echo the information that is inserted to my database. As im pretty new to coding php im not really sure how i could manage to do this. My database name is "nyheter" and the table is "post". So i want to selecte the data from db and echo it on the page.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "nyheter");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM post");
$all_property = array(); //declare an array for saving property
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<link rel="stylesheet" href="nyheter.css" type="text/css" />
<link rel="stylesheet" href="read.css">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="jquery.dynamicmaxheight.js"></script>
</head>
<body>
<div class="allt-2">
<div class="content">
<img src="http://cdn4.iconfinder.com/data/icons/socialmediaicons_v120/48/google.png"/ alt="" >
<h3><?php echo $Name?></h3>
</div>​
<section class="section js-dynamic-height" data-maxheight="150" >
<p class="dynamic-height-wrap"> Hej
</p>
<button class="js-dynamic-show-hide button" title="Läs mer" data-replace-text="Läs mindre">Läs mer</button>
</section>
<img class="ny-img" src="http://placehold.it/500x320"/>
</div>
</body>
<script>
$(document).ready(function(){
$('.js-dynamic-height').dynamicMaxHeight();
});
</script>
</body>
</html>
You're selecting everything from the database. So you've to use a loop to display the content you've selected from the database.
Write something similar to this:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "name: " . $row["name"]."<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn); ?>
Hope this was helpful.

Adding a link when Admin is loged in in PHP

So I was able to make a code work where if the user is an Admin in the database, the link 'ADMIN' shows. However, when no one is logged in, it shows that part of the code to determine if the user is admin is undefined index.
How do I make it so that it doesnt show the undefined index when no one is logged in?
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="HandheldFriendly" content="True">
<link rel="stylesheet" type="text/css" media="screen" href="css/masthead.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/styles.css" />
</head>
<body>
<nav>
<div class="brand">
<h1>HOME PAGE</h1></div>
<ul>
<li>BOOKS</li>
<li>STORIES</li>
<li>QUOTES</li>
<li>UPLOAD</li>
<li>REGISTER</li>
<li>CONTACT ME</li>
<?php
$dbserverName = "localhost";
$dbuserName = "root";
$dbpassword = "";
$dbname = "database";
$db = mysqli_connect( $dbserverName , $dbuserName , $dbpassword , $dbname );
$value = $_SESSION['u_id'];
$sql = "SELECT admin, user_id FROM users WHERE username='".$value."'";
$result = mysqli_query($db,$sql);
if ($row = mysqli_fetch_assoc($result)) {
$user_id = $row['user_id'];
$u_admin = $row['admin'];
if ($u_admin === "Y") {
print '<li>admin</li>';
}
}
?>
<?php
if (isset($_SESSION['u_id'])) {
print '<form action = "includes/logout.inc.php" method="POST">
<button type="submit" name="logout">LOGOUT</button>
</form>';
}
else {
print '<form action = "includes/login.inc.php" method="POST">
<button type="submit" name="logout">LOGIN</button>
</form>';
}
?>
</ul>
</nav>
<section class="sec1"></section>
<section class="sec2"></section>
</div>
</ul>
</nav>
</div>
</header>
<main container class="siteContent">
<!-- BEGIN CHANGEABLE CONTENT. -->`enter code here`
I am stuck....I have tried different if statements with a variable equal to true instead...but that doesnt work.
I forgot to add the the error is at when I run the code. It doesnt show when the user is logged in, just when no one is logged in.
$value = $_SESSION['u_id'];
You need to check if array values are set before using them. Something like this
$u_admin = isset($row['admin']) ? $row['admin'] : false
If you are using php 7, you can shorten this with the null coalescing operator
$u_admin = $row['admin'] ?? false
This assigns your variable if it's set, otherwise it assigns it as the second value.

Draw a link from the database and add it to the HTML

I want to make a page where the element will redirect the user to a random page from the database.
I made the HTML code, but I can not deal with PHP and MySQL - I was able to connect to the database, but any attempt to connect the MySQL code with the tag ended in a loss.
Can I count on help writing a PHP script and linking code with ?
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Montserrat+Subrayada" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet">
<title>Random it</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<header></header>
<div class="random">
Random
</div>
<?php
require_once "connect.php";
$conn = #new mysqli($host, $db_user, $db_password, $db_name);
$sql = "SELECT link FROM randomit ORDER BY RAND()";
?>
<footer></footer>
</body>
</html>
Let's try this:
Put this PHP part at the top of the page;
<?php
// set a default link in case something goes wrong
$DEFAULT_LINK = "default.html";
// connect to DB
require_once "connect.php";
$conn = new mysqli($host, $db_user, $db_password, $db_name);
// set query -> get 1 result only with LIMIT 1
$sql = "SELECT link FROM randomit ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $sql);
if ($result !== false)
$row = mysqli_fetch_assoc($result);
else
$row = false;
// if we have a valid result => use it
// else => use the default
if ($row && isset($row["link"]))
$RANDOM_LINK = $row["link"];
else
$RANDOM_LINK = $DEFAULT_LINK;
?>
And now the HTML part:
<!DOCTYPE html>
<html>
<!-- head part... -->
<body>
<header></header>
<div class="random">
Random
</div>
<footer></footer>
<!-- etc... -->

$_SESSION in PHP is always returning 1

I'm trying to develop a login system in PHP which has faculty_login.php which displays faculty_login_option.inc.php which has a login form and if $_SESSION['f_id'] is set it redirects to faculty_upload_option.php. where faculty details are fetched from faculty_table using $f_id = $_SESSION['f_id'] as the primary key.but $_SESSION['f_id'] is always returning 1 and user is logging in as the user whose f_id is 1.
<?php
//faculty login page.faculty_login.php
//if logged in show upload option/show login option.
require_once 'resources/core.inc.php';//session is set here
require_once 'resources/connect.inc.php';//init db connection
if(isset($_SESSION['f_id'])&&!empty($_SESSION['f_id'])){
require_once 'faculty_upload_option.inc.php';
}
else{
require_once 'faculty_login_option.inc.php';
}
?>
<?php
/* faculty_login_db.php
* Check if the faculty can login or the credentials are wrong.
*/
require_once 'resources/core.inc.php';
require_once 'resources/connect.inc.php';
if(isset($_POST['f_username'])&&isset($_POST['f_password'])){
if(!empty($_POST['f_username'])&&!empty($_POST['f_password'])){
$username = stripcslashes($_POST['f_username']);
$password = stripcslashes($_POST['f_password']);
$result = $conn->prepare("SELECT f_id FROM faculty_table WHERE f_username= :hjhjhjh AND f_password= :asas");
$result->bindParam(':hjhjhjh', $username);
$result->bindParam(':asas', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($result->rowCount() == 1) {
$_SESSION['f_id'] = $rows ;
$_SESSION['f_username'] = $username;
header('Location:faculty_login.php');
}
else{
header('Location:faculty_login.php?username='.$username);
}
}
else{
header('Location:faculty_login.php');
}
}
else{
header('Location:faculty_login.php');
}
?>
<?php
/* faculty_login_option.php
* faculty login page. check if user exists/ use faculty_login_db.php
*/
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 , maximum-scale=1">
<link rel="stylesheet" href="resources/loginstyle.css">
</head>
<body>
<?php
//<img alt="full screen background image" src="images/orange.jpg" id="full-screen-background-image" />
?>
<div id="back">Home</div>
<div id="header">
<h3>FACULTY LOGIN</h3><br>
</div>
<hr>
<div id="container">
<center>
<form action="faculty_login_db.php" method="post">
<input type="text" onFocus="if(this.value=='Username'){this.value=''}" name="f_username" class="buttons" value="<?php
if(isset($_GET['username']))
{
echo $_GET['username'];
}else{echo 'Username';}
?>"><br>
<input type="password" onFocus="if(this.value=='Password'){this.value='';}" name="f_password" class="buttons" value="Password"><br>
<input type="submit" value="Login" class="lbutton">
</form>
</center>
<?php
if(isset($_GET['username'])){
?>
<div id="errormsg">Username or password is invalid.</div>
<?php
}
?>
</body>
<?php
/* this is faculty_upload_option.inc.php
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once 'resources/core.inc.php';
require_once 'resources/connect.inc.php';
if(isset($_SESSION['f_id'])&&isset($_SESSION['f_username'])&&!empty($_SESSION['f_id'])){
$f_id=trim(isset($_SESSION['f_id']));
if(!empty($f_id)){
$result = $conn->prepare("SELECT * FROM faculty_table WHERE f_id=:id");
$result->bindparam(':id', $f_id);
$result->execute();
$rows = $result->fetchAll();
foreach($rows as $db_rows){
$f_username = $db_rows['f_username'];
$category = $db_rows['category'];
$branch = $db_rows['branch'];
}
//page which should be displayed if user logs in.?>
<html>
<head><title><?php echo $f_username; ?></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 , maximum-scale=1">
<link href='http://fonts.googleapis.com/css?family=Indie+Flower|Yanone+Kaffeesatz' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="resources/upload_style.css">
</head>
<body><div id="parent">
<div id="header">
<img src="images/no-profile-image.png" width="30%" id="noimg">
<span id="addfont"><h1><?php echo $f_username;?></h1></span>
<h2><?php echo $category;?></h2>
<p><?php echo $branch;?></p>
<center><div class="buttons" id="left">Home</div><div class="buttons" id="right">Logout</div></center>
</div>
Are you destroying session correctly on logout? Are you setting session id before hitting the condition somewhere? What is the value before hitting the comparion condition?

Categories