I have three pages at the moment:
config.php: contains the configuration for mysql connection
list.php: lists entries in a mysql table
edit.php: edits a specific entry selected in list.php
config.php:
define('DB_SERVER', 'server');
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'pass');
define('DB_NAME', 'database');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
list.php:
<?php
require_once "config.php";
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<meta http-equiv="Content-type" content="text/html; charset=utf8">
<title>Bienvenue</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<table class="table table-striped">
<tr>
<th></th>
<th>column 1</th>
<th>column 2</th>
</tr>
<?php
$result = mysqli_query($link, "select * from TABLE");
while($row = mysqli_fetch_array($result)){
echo "<tr>
<td><a href='edit.php?id=" . $row['IDCOLUMN'] . "' class='btn btn-success ml-3'>Modifier</a></td>
<td>" . $row['column 1'] . "</td>
<td>" . $row['column 2'] . "</td>
</tr>"; //$row['index'] the index here is a field name
}
mysqli_close(); //Make sure to close out the database connection
?>
</table>
</body>
</html>
edit.php:
<?php
require_once "config.php";
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$id = $_GET['id'];
$resname_err = $rescity_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate new password
if(empty(trim($_POST["nom_residence"]))){
$resname_err = "Entrer le nom de la résidence.";
} elseif(empty(trim($_POST["ville_residence"]))){
$rescity_err = "Entrer la ville de la résidence.";
}else{
$resname1 = trim($_POST["nom_residence"]);
$rescity1 = trim($_POST["ville_residence"]);
}
// Check input errors before updating the database
if(empty($resname_err) && empty($rescity_err)){
// Prepare an update statement
$sql = "UPDATE residences SET RESIDENCE = ?, VILLE = ? WHERE residenceID = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssi", $resname1, $rescity1, $id);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
header("location: list.php?=".$resname1.$rescity1);
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
mysqli_stmt_close($stmt);
}
}
}
?>
<!DOCTYPE html>
<html lang>
<head>
<meta charset="utf8">
<meta http-equiv="Content-type" content="text/html; charset=utf8">
<title>Bienvenue</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<?php
$result = mysqli_query($link, "select * from residences where residenceID=".$id);
while($row = mysqli_fetch_array($result)){ //Creates a loop to loop through results
$resname = $row['RESIDENCE'];
$rescity = $row['VILLE'];
}
mysqli_close($link)
?>
<div class="wrapper">
<h2>modify entry</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>value name1</label>
<input name="nom_residence" class="form-control <?php echo
(!empty($resname_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $resname; ?>">
<span class="invalid-feedback"><?php echo $resname_err; ?></span>
</div>
<div class="form-group">
<label>value name2</label>
<input name="ville_residence" class="form-control <?php echo
(!empty($rescity_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $rescity; ?>">
<span class="invalid-feedback"><?php echo $rescity_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Enregistrer">
<a class="btn btn-link ml-2" href="list.php">Annuler</a>
</div>
</form>
</div>
</body>
</html>
My current problem is that the Mysql entry is never updated.
This section runs:
header("location: list.php?=".$resname1.$rescity1);
So I know every condition is met correctly
Note: I added this part to know their values when redirected to list.php:
.$resname1.$rescity1
I ran all the code inside a PHP shell and it worked perfectly.
Of course, I had to set the values resname1 and rescity1 manually, so I'm thinking it must be some formatting issue?
Related
This problem in php I need solution in this day
Please for my homework
Can you help me in my homework please because I'm not working but I'm reading in my university Please can you solve this problem.
Can you explain to my this problem or can connection to my desktop to solution this problem or can send explain .
This code
index.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<?php require_once 'process.php'?>
<?php
if(isset ($_SESSION['message']));?>
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
// and this problem !
<?php endif ?>
?>
<div class="contener">
<?php
$mysqli = new mysqli('localhost', 'root', 'rootroot','crudcrud') or die(mysqli_error($mysqli));
$result = $mysqli->query("SELECT * FORM data") or die($mysqli->error);
?>
<div class="row justify-content-center">
<table class="table">
<thead>
<tr>
<th>usernames</th>
<th>Passowrds</th>
<th colspan="2">Action</th>
<tr>
</thead>
</div>
<?php while ($row = $result->fetch_assoc()): ?>
<tr>
<td><?php echo $row ['username'];?></td>
<td><?php echo $row ['password'];?></td>
<td>
<a href="index.php?edit=<?php echo $row ['id']; ?>"
class="btn btn-info">edit</a>
<a hraf="process.php?delete=<?php echo $row ['id']; ?>"
class="btn btn-danger">
</td>
</tr>
//this problem !
<?php endwhile; ?>
</table>
<?php
function pre_r( $arry ){
echo'<pre>';
print_r($array);
echo'</pre>';
}
?>
<div class="col-lg-6 m-auto">
<form action="process.php" method="post">
<input type="hidden" name="id" value=" <?php echo $id ?> "
<br><br><div class="card">
<div class="card-header bg-dark">
<h1 class="text-white text-center"> Insert Operation </h1>
</div><br>
<label> Username: </label>
<input type="text" name="username" class="form-control" value=" <?php echo $username; ?> " placeholder="Enter Your Username"> <br>
<label> Password: </label>
<input type="text" name="password" class="form-control" value=" <?php echo $password; ?> " placeholder="Password"> <br>
<?php
if ($update == true)
?>
<button class="btn btn-info" type="submit" name="update"> update </button>
<?php else: ?>
<button class="btn btn-success" type="submit" name="save"> Submit </button>
// and this problem !
<?php endif; ?>
</div>
</form>
</div>
</div>
</body>
</html>
code
process.php
=======================================================
<?php
session_start();
$mysqli = new mysqli('localhost', 'root', 'rootroot','crudcrud') or
die(mysqli_error($mysqli));
$id = 0;
$update = false;
$username = '';
$password = '';
if (isset ($_POST['save'])){
$usernames = $_POST['username'];
$passwords = $_POST['password'];
$mysqli->query("INSERT INTO data (username, password) VALUES('$username', '$password')") or
die($mysqli->error);
$_SESSION['message'] = "Record has been saved!";
$_SESSION['msg_type'] = "success!";
header('loocation: index.php');
}
if (isset ($_GET['delete'])){
$id = $_GET['delete'];
$mysqli->query("DELETE FROM data WHERE id=$id") or
die($mysqli->error());
SESSION['message'] = "Record has been deleted!";
SESSION['msg_type'] = "denger!";
header('loocation: index.php');
}
if (isset ($_GET['edit'])){
$id = $_GET['edit'];
$update = true;
$result = $mysqli->query("DELETE FROM data WHERE id=$id") or
die($mysqli->error());
if (count($result)==1){
$row = $result->fetch_array();
$username = $row['username'];
$password = $row['password'];
}
}
if (isset($_POST['update'])){
$id = $_POST['id'];
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli->query("UPDATE data SET username='$username', password='$password' WHERE id=$id") or
die($mysqli->error);
$_SESSION['message'] = "Record has been Update!";
$_SESSION['msg_type'] = "warning!";
header('loocation: index.php');
}
This piece is completely wrong:
if(isset ($_SESSION['message']));?> //<-- : not ;
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
//<-- no closing tag
<?php endif ?> //<-- missing ;
Should be:
if(isset ($_SESSION['message'])):?>
<div class="alert alert-<?=$_SESSION['msg_type']?>">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
endif; ?>
It get's pretty ugly when you use a lot of PHP and HTML in the same file, it might be time to look at using a template engine.
Warning: Cannot modify header information - headers already sent by
(output started at/admin/index.php:21) in
/var/www/web143366/html/admin/index.php on line 24
<?php
require_once('../config.php');
require_once('../php/functions.php');
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="admin.css">
<link rel="stylesheet" type="text/css" href="../layout.css">
</head>
<body>
<?php
if (!isset($_SESSION['adminid'])) {
header('Location: /admin/login');
} else {
?>
<div id="leftPanel">
<div class="przyciskPanelAdmina">Homepage</div>
<div class="przyciskPanelAdmina active">Dashboard</div>
<div class="przyciskPanelAdmina">Manage Accounts</div>
<div class="przyciskPanelAdmina">Add Account</div>
<div class="przyciskPanelAdmina">Add Category</div>
<div class="przyciskPanelAdmina">Messages</div>
<div class="przyciskPanelAdmina">Logout</div>
</div>
<div id="rightPanel">
<h3>Recent payments</h3>
<table>
<tr class='first'>
<td width='20%'>Account Login</td>
<td width='20%'>Account Password</td>
<td width='20%'>Date</td>
<td width='20%'>Amount</td>
<td width='20%'>Payment ID</td>
</tr>
<?php
$sql = $conn->prepare('SELECT accounts.login AS Login, accounts.password AS Pass, date, amount, paymentID FROM payments INNER JOIN accounts ON payments.accountId=accounts.id order by date DESC');
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr><td width='20%'>" . $row['Login'] ."</td><td width='20%'>" . $row['Pass'] ."</td><td width='20%'>" . $row['date'] ."</td><td width='20%'>" . $row['amount'] ."$</td><td width='20%'>" . $row['paymentID'] ."</td></tr>";
}
?>
</table>
<div class="clear"></div>
</div>
<?php
}
?>
</body>
</html>
Edit all: This is the error. When I remove line 24 I get the following error.
Fatal error: Call to undefined method mysqli_stmt::get_result() in
/var/www/web143366/html/admin/login.php on line 32
Line 32: $result = $sql->get_result();
Code:
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Wrong email or password</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$p = $row['password'];
$uid = $row['id'];
}
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
header('Location: /admin');
} else {
echo "<h1>Wrong email or password 2</h1>";
}
}
}
Login.php=
<?php
require_once('../config.php');
require_once('../php/functions.php');
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
</head>
<body>
<?php
if (isset($_POST['loginBtn'])) {
$email = htmlspecialchars($_POST['mail']);
$pass = htmlspecialchars($_POST['password']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Wrong email or password</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$p = $row['password'];
$uid = $row['id'];
}
if (password_verify($pass, $p)) {
$_SESSION['adminid'] = $uid;
header('Location: /admin');
} else {
echo "<h1>Wrong email or password 2</h1>";
}
}
}
if (isset($_POST['forgotBtn'])) {
$code = randomChars(20);
$email = htmlspecialchars($_POST['mail']);
$sql = $conn->prepare('SELECT * FROM admin WHERE email = ?');
$sql->bind_param('s', $email);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>No user with that email</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['id'];
}
$sql = $conn->prepare('INSERT INTO resetpass (userID, code) VALUES (?, ?)');
$sql->bind_param('ss', $uid, $code);
$sql->execute();
$message = "Your reset link: " . "http://" .$_SERVER['SERVER_NAME'] . '/admin/login?r=' . $code;
$to = $email;
$title = "Reset Password";
if (sendEmail($to, $message, $title)) {
echo "Email with reset code has been sent";
} else {
echo "Error while sending email";
}
}
}
if (isset($_POST['resetBtn'])) {
$nPass = htmlspecialchars($_POST['nPass']);
$code = $_POST['code'];
$password = password_hash($nPass, PASSWORD_DEFAULT);
$sql = $conn->prepare('SELECT * FROM resetpass WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows < 1) {
echo "<h1>Error</h1>";
} else {
while ($row = $result->fetch_assoc()) {
$uid = $row['userID'];
}
$sql = $conn->prepare('UPDATE resetpass SET used = "1" WHERE code = ?');
$sql->bind_param('s', $code);
$sql->execute();
$sql = $conn->prepare('UPDATE admin SET password = ? WHERE id = ?');
$sql->bind_param('ss', $password, $uid);
$sql->execute();
echo "Password changed successfuly, you can now login";
}
}
?>
<?php
if (!isset($_SESSION['adminid'])) {
if (isset($_GET['forgot'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">Account Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<input type="submit" name="forgotBtn" value="Reset">
</form>
<?php } else if (isset($_GET['r'])) { ?>
<form action="" method="POST">
<div class="formularzowyNaglowek">New Password:</div>
<input type="password" name="nPass" placeholder="New password" required>
<input type="hidden" name="code" value="<?php echo $_GET['r'] ?>" required>
<input type="submit" name="resetBtn" value="Reset">
</form>
<?php
} else { ?>
<h2 style="text-align: left;">Login to admin panel</h2>
<form action="" method="POST">
<div class="formularzowyNaglowek">Email Address:</div>
<input type="email" name="mail" placeholder="Email address" required>
<div class="formularzowyNaglowek">Password:</div>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" name="loginBtn" value="Login">
</form>
Forgot your password?
<?php
}
} else {
header('Location: /admin');
}
?>
</body>
</html>
The line header('Location: /admin/login'); will redirect to the login page when the user is not logged in.
The problem is, that the function header() doesnt work when there has been content outputted already (echo or html).
<?php
session_start(); // only if you havent called session_start in config.php or functions.php
require_once('../config.php');
require_once('../php/functions.php');
if (!isset($_SESSION['adminid'])) {
header('Location: /admin/login');
exit();
}
?>
<!DOCTYPE>
<html lang="eng">
<head>
<meta charset="UTF-8">
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="admin.css">
<link rel="stylesheet" type="text/css" href="../layout.css">
</head>
<body>
<div id="leftPanel">
<div class="przyciskPanelAdmina">Homepage</div>
<div class="przyciskPanelAdmina active">Dashboard</div>
<div class="przyciskPanelAdmina">Manage Accounts</div>
<div class="przyciskPanelAdmina">Add Account</div>
<div class="przyciskPanelAdmina">Add Category</div>
<div class="przyciskPanelAdmina">Messages</div>
<div class="przyciskPanelAdmina">Logout</div>
</div>
<div id="rightPanel">
<h3>Recent payments</h3>
<table>
<tr class='first'>
<td width='20%'>Account Login</td>
<td width='20%'>Account Password</td>
<td width='20%'>Date</td>
<td width='20%'>Amount</td>
<td width='20%'>Payment ID</td>
</tr>
<?php
$sql = $conn->prepare('SELECT accounts.login AS Login, accounts.password AS Pass, date, amount, paymentID FROM payments INNER JOIN accounts ON payments.accountId=accounts.id order by date DESC');
$sql->execute();
$result = $sql->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr><td width='20%'>" . $row['Login'] ."</td><td width='20%'>" . $row['Pass'] ."</td><td width='20%'>" . $row['date'] ."</td><td width='20%'>" . $row['amount'] ."$</td><td width='20%'>" . $row['paymentID'] ."</td></tr>";
}
?>
</table>
<div class="clear"></div>
</div>
</body>
</html>
I am creating a webshop and I have the login working but I ran into a problem. I need to use sessions in order to display and hide certain pages. It's a login screen for the backend of my webshop so it makes sense that it should be secured and hidden from people who aren't allowed to access the backend. I know that I need to start a session at the top of the pagebut then what? I searched Google but I can't find a solution wich I can apply to my code.
<?php
session_start();
*my information*
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])) {
$uname = $_POST['username'];
$wwoord = $_POST['wachtwoord'];
$query = "SELECT * FROM Medewerkers WHERE medewerker_username='$uname' && medewerker_password='$wwoord'";
$result = mysqli_query($conn, $query);
if($result) {
$_SESSION['ingelogd'] = true;
echo"U bent ingelogd!";
header("location: index.php");
} else {
echo "Inloggegevens incorrect.";
}
}
?>
<html lang="en"><head>
<meta charset="UTF-8">
<title>Admin panel</title>
<link rel="stylesheet" type="text/css" href="tables.css">
</head>
<body>
<div id="content">
<ul>
<li>Admin panel</li>
<li>Medewerkersoverzicht</li>
<li>Medewerkers toevoegen</li>
<li>Klantenoverzicht</li>
<li>Productoverzicht</li>
<li>Product toevoegen</li>
<li>Reparatieoverzicht</li>
<li>Contactoverzicht</li>
</ul>
<h1>Admin login</h1>
<form role="form" method="post" action="index.php" class="contactForm">
<table>
<tr>
<td><label for="username">Username</label></td>
<td><input type="text" name="username" class="" id="username"> <br><br></td>
</tr>
<tr>
<td><label for="wachtwoord">Wachtwoord</label></td>
<td><input type="password" name="wachtwoord" class="" id="wachtwoord"><br><br></td>
</tr>
<tr>
<td><button type="submit" name="submit" class="button">Inloggen</button><br></td>
</tr>
</table>
</form>
</div>
</html>
Once the session is started check for the existence of the session variable- if it already exists then redirect the user.
<?php
if( !isset( $_SESSION ) ) session_start();
/* if the session already exists, redirect user */
if( isset( $_SESSION['ingelogd'] ) ) header("location: index.php");
/* don't echo content outwith the document body ~ other than suitable head content */
$msg='';
$conn = new mysqli( $dbhost, $dbuser, $dbpass, $dbname );
if ( $conn->connect_error ) die("Connection failed");/* don't reveal too much information about db ! */
if( isset( $_POST['submit'] ) ) {
$uname = $_POST['username'];
$wwoord = $_POST['wachtwoord'];
$query = "SELECT * FROM Medewerkers WHERE medewerker_username='$uname' && medewerker_password='$wwoord'";
/* best practise: don't mix OO & procedural code */
$result = $conn->query( $query );
if( $result ) {
$_SESSION['ingelogd'] = true;
header("location: index.php");
} else {
/* assign error message as a variable to echo later */
$msg="Inloggegevens incorrect.";
}
$conn->close();
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin panel</title>
<link rel="stylesheet" type="text/css" href="tables.css">
</head>
<body>
<div id="content">
<ul>
<li>Admin panel</li>
<li>Medewerkersoverzicht</li>
<li>Medewerkers toevoegen</li>
<li>Klantenoverzicht</li>
<li>Productoverzicht</li>
<li>Product toevoegen</li>
<li>Reparatieoverzicht</li>
<li>Contactoverzicht</li>
</ul>
<h1>Admin login</h1>
<?php
echo $msg;/* error message */
?>
<form role="form" method="post" action="index.php" class="contactForm">
<table>
<tr>
<td><label for="username">Username</label></td>
<td><input type="text" name="username" class="" id="username"><br><br></td>
</tr>
<tr>
<td><label for="wachtwoord">Wachtwoord</label></td>
<td><input type="password" name="wachtwoord" class="" id="wachtwoord"><br><br></td>
</tr>
<tr>
<td><button type="submit" name="submit" class="button">Inloggen</button><br></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Just coverting #Divyesh Savaliya 's comment into code.
<?php session_start(); ?>
<?php if(isset($_SESSION['ingelogd'])){ ?>
// ... the rest of your code in index.php
<?php } else {
header('location: login.php'); // if your login page is login.php
}?>
actually, since you don't fill the session if login fails, it is better to store some information about the user (such as the username or user id) in the session and check using isset instead of storing boolean in the session.
you will want this value later.
So I'm working on this page and I have an error somewhere in my code as the page is not being displayed.
The code is fine until line 27 as when I try to load the page both echo statements are executed.
The page also loads fine when I comments out the $results statement which is line 28. I just cant seem to fine whats wrong with it.
Code is posted below:
<?php
session_start();
include 'phpFunctions.php';
$error = "";
//if(!isset($_SESSION["id"]))
//{
// header("Location: http://tylerforaie.com/csproject/login.php");
//}
if(!empty($_POST))
{
$connect = new mysqli("localhost", "username", "password", "dbname");
if ($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
$sql = "INSERT INTO requestOff (employeeId, day, approved, reason) VALUES ('".$_SESSION['id']."', '".$_POST['date']."', 'Pending', '".$_POST['reason']."')";
if (!$connect->query($sql)) {
printf("Errormessage: %s\n", $connect->error);
}
$connect->query($sql);
}
$id = $_SESSION['id'];
echo $id;
$sql = "SELECT * FROM requestedOff where employeeId='".$id."'";
echo $sql;
$result = $connect->query($sql);/*******THIS IS LINE 28********/
if(!$result){
echo $connect->error;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request Day Off</title>
</head>
<body bgcolor="">
<div id="wrapper">
<div class="float left">
<?php navigation(); ?>
</div>
<div class="float right">
<h3>Request a Day Off</h3>
<form action="dayOffRequest.php" method="post">
<p><?php print $error; ?></p>
<table align="center">
<tr>
<td>Date</td>
<td><input type="text" name="date" placeholder="YYYY/MM/DD"/></td>
</tr>
<tr>
<td>Reason for Request</td>
<td><textarea class="width" type="text" name="reason" height="50px"></textarea></td>
</tr>
</table>
<p><input type="submit" value="Submit" /></p>
</form>
<hr />
<h3>Submitted Requests</h3>
<table align="center">
<tr>
<th>Date</th>
<th>Approved</th>
</tr>
<?php
while($row = $result->fetch_assoc())
{
print "<tr>";
print "<td>".$row['day']."</td>";
print "<td>".$row['approved']."</td>";
print "</tr>";
}
?>
</table>
</div>
</div>
</body>
</html>
try this one -
<?php
session_start();
include 'phpFunctions.php';
$error = "";
//if(!isset($_SESSION["id"]))
//{
// header("Location: http://tylerforaie.com/csproject/login.php");
//}
if(!empty($_POST))
{
$connect = new mysqli("localhost", "username", "password", "dbname");
if ($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
$sql = "INSERT INTO requestOff (employeeId, day, approved, reason) VALUES ('".$_SESSION['id']."', '".$_POST['date']."', 'Pending', '".$_POST['reason']."')";
if (!$connect->query($sql)) {
printf("Errormessage: %s\n", $connect->error);
}
$connect->query($sql);
}
$id = $_SESSION['id'];
echo $id;
$sql = "SELECT * FROM requestOff where employeeId='".$id."'";
echo $sql;
$result = $connect->query($sql);/*******THIS IS LINE 28********/
if(!$result){
echo $connect->error;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Request Day Off</title>
</head>
<body bgcolor="">
<div id="wrapper">
<div class="float left">
<?php navigation(); ?>
</div>
<div class="float right">
<h3>Request a Day Off</h3>
<form action="dayOffRequest.php" method="post">
<p><?php print $error; ?></p>
<table align="center">
<tr>
<td>Date</td>
<td><input type="text" name="date" placeholder="YYYY/MM/DD"/></td>
</tr>
<tr>
<td>Reason for Request</td>
<td><textarea class="width" type="text" name="reason" height="50px"></textarea></td>
</tr>
</table>
<p><input type="submit" value="Submit" /></p>
</form>
<hr />
<h3>Submitted Requests</h3>
<table align="center">
<tr>
<th>Date</th>
<th>Approved</th>
</tr>
<?php
while($row = $result->fetch_assoc())
{
print "<tr>";
print "<td>".$row['day']."</td>";
print "<td>".$row['approved']."</td>";
print "</tr>";
}
?>
</table>
</div>
</div>
</body>
</html>
So as it turns out I had put the connect function inside the if statement so when the form wasnt being submitted there was no connection to the database. I fixed it by moving the connection function outside of the if
<?php
session_start();
include 'phpFunctions.php';
$error = "";
//if(!isset($_SESSION["id"]))
//{
// header("Location: http://tylerforaie.com/csproject/login.php");
//}
$connect = new mysqli("localhost", "username", "password", "db");
if ($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
if(!empty($_POST))
{
$sql = "INSERT INTO requestOff (employeeId, day, approved, reason) VALUES ('".$_SESSION['id']."', '".$_POST['date']."', 'Pending', '".$_POST['reason']."')";
if (!$connect->query($sql)) {
printf("Errormessage: %s\n", $connect->error);
}
}
$result = $connect->query("SELECT * FROM requestedOff where employeeId='1'");
?>
I'm creating a page with PHP for a class and when I echo things it shows up in the wrong place.
Here is my HTML page
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<table>
<tr>
<td><span>First name:</span></td>
<td><input type="text" name="firstname"></td>
</tr>
<tr>
<td><span>Last name:</span></td>
<td><input type="text" name="lastname"></td>
</tr>
<tr>
<td><span>Age:</span></td>
<td><input type="number" name="age"></td>
</tr>
</table>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
Here is my PHP page:
<?php
$con = mysql_connect("localhost","USERNAME","PASSWORD");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
mysql_select_db("a7068104_world") or die("Cannot connect to database");
header("refresh:1.5; url=NamesAction.php");
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$fullname = mysql_real_escape_string($_POST['firstname'] . " " . $_POST['lastname']);
$age = mysql_real_escape_string($_POST['age']);
$query = "SELECT * FROM names_1 WHERE fullname='$fullname'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname, lastname, fullname, age) VALUES('$firstname', '$lastname', '$fullname', '$age')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
When I echo stuff in my PHP page it shows up at the very top of the frame that it's in right above the
<div id="main">
I want the echoed text to go in the very bottom of the
<div id="main">
Is there any way that I can do that? I appreciate your help!
Thanks,
Leonardude
Your issue is that you are echo'ing the message before you supply your HTML.
Which is evident here:
if($result) {
echo "Your name was successfully added to the database!";
}
else{
echo "Your name couldn't be added to the database!";
}
Because PHP is a server-side language and HTML is client-side, the PHP will process well before the HTML, meaning it will echo before the page is displayed. Hence the issue where it is before your <div id="main"></div>.
A way around this is by setting a variable
if($result) {
$var = "Your name was successfully added to the database!";
}
else{
$var = "Your name couldn't be added to the database!";
}
And somewhere in your <div id="main"></div> you could do something like the following:
<div id="main">
<?php
if(isset($var) && !empty($var)) {
echo $var;
}
?>
</div>