PHP and DataBase - php

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'");
?>

Related

Page to update mysql entry does not run sql query

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?

PHP - Session error messages not showing

I have a page with a contact form.
I'm trying to make some error messages appear next to the fields if the fields are empty/invalid. If all fields are OK the field's contents are sent to a database.
The validation itself works. If the fields are empty or invalid it does not submit them into the database. However no error messages are shown next to the fields.
Here are the codes
Page with the contact form named palaute3.php:
<?php
session_start();
$_SESSION["nimiVirhe"]="";
$_SESSION["spostiVirhe"]="";
$_SESSION["palauteVirhe"]="";
$servername = "localhost";
$username = "username";
$password = "passwd";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game Over</title>
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="tyyli1.css"/>
<style type="text/css">
#import url('https://fonts.googleapis.com/css?family=Press+Start+2P');
</style>
</head>
<body>
<div id="container">
<div id="header">
</div>
<div id="menuBG">
</div>
<ul class="navlist">
<li>Etusivu
</li>
<li>Leffat
</li>
<li>Pelit
</li>
<li>Ota yhteyttä
</li>
</ul>
<div id="content">
<h3>Palaute</h3>
<p>Anna Palautetta sivujen ulkonäöstä tai vinkkejä uusiksi arvosteluiksi!</p>
<p><span class="error">Kaikki kentät ovat pakollisia</span></p>
<form method="post" action="validointi.php">
<table width="450px">
<tr>
<td valign="top">
<label for="nimi">Nimi</label>
</td>
<td valign="top">
<input type="text" name="nimi" /><span class="error"><?php echo $_SESSION["nimiVirhe"];?></span>
</td>
</tr>
<tr>
<td valign="top">
<label for="sposti">Sähköposti</label>
</td>
<td valign="top">
<input type="text" name="sposti" /><span class="error"><?php echo $_SESSION["spostiVirhe"];?></span>
</td>
</tr>
<tr>
<td valign="top">
<label for="palaute">Palaute</label>
</td>
<td valign="top">
<textarea name="palaute" maxlength="1000" cols="30" rows="6"></textarea><span class="error"><?php echo $_SESSION["palauteVirhe"];?> </span>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="Lähetä" name="submit">
</td>
</tr>
</table>
</form>
<?php
session_unset();
?>
<p>
Palautteet tähän
</p>
<?php
$sql = "SELECT id, palaute FROM dbtable";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Palaute: " . $row["palaute"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</div>
<div id="footer">
<p>© Game Over 2018 All rights reserved</p>
</div>
</div>
</body>
</html>
Here is the validation:
<?php
session_start();
$_SESSION["nimiVirhe"]="";
$_SESSION["spostiVirhe"]="";
$_SESSION["palauteVirhe"]="";
if (isset($_POST['submit'])) {
if (empty($_POST["nimi"])) {
$_SESSION["nimiVirhe"] = " Nimi on pakollinen.";
}
else {
$nimi = $_POST["nimi"];
$_SESSION["nimi"]=$nimi;
if (!preg_match("/^[a-zA-Z ]*$/",$nimi)) {
$_SESSION["nimiVirhe"] = " Nimi on väärässä muodossa.";
}
}
if (empty($_POST["sposti"])) {
$sposti = $_SESSION["sposti"];
$_SESSION["spostiVirhe"] = " Sähköposti on pakollinen.";
}
else {
$sposti = $_POST["sposti"];
$_SESSION["sposti"]=$sposti;
if (!filter_var($sposti, FILTER_VALIDATE_EMAIL)) {
$_SESSION["spostiVirhe"] = " Sähköpostiosoite on väärässä muodossa.";
}
}
if (empty($_POST["palaute"])) {
$_SESSION["palauteVirhe"] = "<br>Palaute on pakollinen.";
}
else {
$palaute = $_POST["palaute"];
$_SESSION["palaute"]=$palaute;
}
if($_SESSION["nimiVirhe"] == "" && $_SESSION["spostiVirhe"] == "" && $_SESSION["palauteVirhe"] == ""){
header("Location: yhteystesti.php");
return;
} else {
header("Location: palaute3.php");
return;
}
}
?>
The database insertion works fine so I'm not going to include it here.
Any idea what am I doing wrong here?
PS: This is a school assignment and the teacher tried to make it work but couldn't.
Ath the top of your palaute3.php file you have this
$_SESSION["nimiVirhe"]="";
$_SESSION["spostiVirhe"]="";
$_SESSION["palauteVirhe"]="";
So you re-init your session error messages before using this them.
Those 3 lines should be in the validation page, but not in your error page !
Remove that and it will work.

How to display a user profile pics while the user is logged in php?

I have successfully created a form that submits data and a picture of a user into my online folder and the path directory stored in the database.
My question is this how do I get users to see their picture once they are logged in?
Well Guys thanks for everything but still not getting right here is all my code
Sign Up
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
#apDiv1 {
position:absolute;
width:328px;
height:216px;
z-index:1;
left: 347px;
top: 111px;
}
-->
</style>
</head>
<body>
<div id="apDiv1">
<form method="post" action="logon.php" enctype="multipart/form-data">
<table width="332" height="210" border="0">
<tr>
<td width="155">Email</td>
<td width="167"><input type="text" name="email" /></td>
</tr>
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td>Upload Passport</td>
<td><label>
<input type="file" name="photo" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="submit" value="Sign Up" />
</label></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Logon.php
<?php
include('connection.php');
if (!isset($_FILES['photo']['tmp_name'])) {
echo "";
}else{
$file=$_FILES['photo']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['photo']['tmp_name']));
$image_name= addslashes($_FILES['photo']['name']);
move_uploaded_file($_FILES["photo"]["tmp_name"],"photos/" . $_FILES["photo"]["name"]);
$email=$_POST['email'];
$username=$_POST['username'];
$password=$_POST['password'];
$photo="photos/" . $_FILES["photo"]["name"];
$save=mysql_query("INSERT INTO info (id, email, user_name, password, photo) VALUES ('','$email','$username','$password','$photo')");
/* Redirect visitor to the thank you page */
echo '<script language="javascript">alert("Registration Succesful....")</script>';
echo '<script language="javascript">window.location = "index.php"</script>';
exit();
}
?>
Index.php
<?php
include('login.php'); // Includes Login Script
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
#apDiv1 {
position:absolute;
width:391px;
height:178px;
z-index:1;
left: 334px;
top: 166px;
}
#apDiv2 {
position:absolute;
width:259px;
height:115px;
z-index:1;
left: 380px;
top: 137px;
}
-->
</style>
</head>
<body>
<div id="apDiv2">
<form method="POST" action="">
<table width="260" height="88" border="0">
<tr>
<td width="131">Username</td>
<td width="119"><label>
<input type="text" name="username" />
</label></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="submit" value="Submit" />
</label></td>
</tr>
</table>
<table width="259" border="0">
<tr>
<td align="center">Sign Up</td>
</tr>
</table>
</form>
<p> </p>
</div>
</body>
</html>
login.php
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "User ID or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = #mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("lesson", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from info where password='$password' AND user_name='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: customer_login.php"); // Redirecting To Other Page
} else {
$error = "User ID or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
customer_login.php
<?php
include('session_connect.php');
?>
<html>
<body>
<style type="text/css">
<!--
#apDiv1 {
position:absolute;
width:259px;
height:173px;
z-index:1;
left: 25px;
top: 92px;
}
-->
</style>
<div id="apDiv1">
<p>Email: <?php echo $email; ?> </p>
<p>Username: <?php echo $username; ?> </p>
<p>Password: <?php echo $password; ?> </p>
<p>Passport: <?php echo $photo; ?> </p>
</div>
</body>
</html>
session_connect.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = #mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("lesson", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select * from info where user_name='$user_check'", $connection);
$row=mysql_fetch_array($ses_sql);
$login_session =$row['user_name'];
$email = $row['email'];//." ".$row['vLastName'];
$username = $row['user_name'];
$password = $row['password'];
$photo = $row['photo'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
Instead the above code shows me the pathway in the database i want the actual image to show...thank you
When you store the Image path in the database, there must be a reference (Foreign key or similar) to the corresponding user.
Now, when the user loggs in, you check the table, where your image paths are declared for the specific user:
SELECT imgpath FROM imgpathstable WHERE userid = $loggedInUser["id"]
and then you can display an img tag with:
<?php
echo "<img href='$imgPath' ...
<?php
if(isset($_SESSION['Anyone']))
{
?>
<img src="<?php echo image path ?>"/>
<?php
}
?>

Echoed text showing up in wrong place

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>

A form page to submit data to table in database in PHP

I am new to PHP and haven't worked much on it. I am working on a page where I need to save data from a textbox to a table on submit of a button. But somehow nothing seems to be working on press of button click.
Following is my code for the page:
<?php
require_once('auth.php');?>
<?php
if(isset($_POST['formSubmit']))
{
$errorMessage = "";
if(empty($_POST['category'])){
$errorMessage .= "<li>You forgot to enter a Category!</li>";
}
$varCategory = $_POST['category'];
if(empty($errorMessage)) {
require_once('config.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE)
or die ('Cannot connect to db');
$result = $conn->query("insert into category (name) values ('".$varCategory."')");
}
}
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Member Index</title>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Categories</h1><br>
<table>
<tr><td>My Profile | Logout</td></tr>
<tr><td>Welcome <?php echo $_SESSION['SESS_FIRST_NAME'];?></td></tr>
<tr><td><table>
<tr><td>Category</td>
<td>
<form action="member-index.php" method="post">
<input type="text" name="category" maxlength="50" value="<?=$varCategory;?>" />
<input type="submit" name="formSubmit" value="Save" />
</form>
</td>
</tr>
<tr>
<td>
<?php
require_once('config.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE)
or die ('Cannot connect to db');
$result = $conn->query("select catid, name from category");
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['catid'];
$name = $row['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
</td>
<td>Delete</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Change this
if($_POST['formSubmit'] == "Submit") // this condition will never true
to
if($_POST['formSubmit'] == "Save")
OR
if(isset($_POST['formSubmit']))
Also remove die and exit from here
echo "working"; //die; // your insert query will never execute because you placed die here
$result = $conn->query("insert into category (name) values ('".$varCategory."')");
//exit;
if($_POST['formSubmit'] == "Submit")
should be
if(isset($_POST['formSubmit']))
if you have a connection class named auth.php file with function query() then you can use this:
$sql = "insert into category(name) values('".$varCategory."')";
$conn->query($sql);

Categories