JQuery functions not running - javascript

The program below contains various error messages to be displayed under certain conditions. These conditions are found through PHP code, after which the necessary JQuery script is echoed in PHP to make the messages appear.
At first, all messages in the .warning class are hidden. Then, if a certain condition is met, particular ids of this class are shown. Below is the relevant code.
<?php require_once 'connection.php'; ?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Create Account</title>
<link rel="stylesheet" type="text/css" href="Styles2.css">
<script src="JQuery.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$('.warning').hide();
});
</script>
<div class="unloggedheadingbar">
</div>
<br>
<div class="createaccount">
<center><h1>Create Account</h1></center>
<center><table>
<form action="create_account.php" method="post">
<tr><td><font class="createaccountfont">Email</font></td><td><input type="text" name="Email" placeholder="someone#somewhere.com" value="<?php if(isset($_POST['Create'])){ echo $_POST['Email']; } ?>" class="createaccounttext"></td></tr>
<tr><td colspan="2"><br></td></tr>
<tr><td><font class="createaccountfont">Password</font></td><td><input type="password" name="Password" class="createaccounttext"></td></tr>
<tr><td colspan="2"><br></td></tr>
<tr><td><font class="createaccountfont">Confirm Password </font></td><td><input type="password" name="ConfirmPassword" class="createaccounttext"></td></tr>
</table></center>
<br>
<center><input type="submit" name="Create" value="Create Account" class="createButton" id="Create"></center>
</form>
<br>
<div class="warning" id="passwordMatchError">
<center><font class="warningText">Your password confirmation must match with your original password!</font></center>
</div>
<div class="warning" id="emailFormatError">
<center><font class="warningText">Your email must match the someone#something.com format.</font></center>
</div>
<div class="warning" id="emailDuplicateError">
<center><font class="warningText">An account under this email already exists.</font></center>
</div>
</div>
<?php
if(isset($_POST['Create'])){
$email = $_POST['Email'];
$password = md5($_POST['Password']);
if(strpos($email, '#') !== TRUE){
echo '<script>
$(".warning").hide();
$("#emailFormatError").show();
</script>';
}elseif($_POST['Password'] != $_POST['ConfirmPassword']){
echo '<script>
$(".warning").hide();
$("#passwordMatchError").show();
</script>';
}else{
$query = "SELECT * FROM user_table WHERE Email = '" . $email . "';";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0){
$query = "INSERT INTO user_table VALUES ('" . $email . "', '" . $password . "');";
mysqli_query($con, $query);
}else{
echo '<script>
$(".warning").hide();
$("#emailDuplicateError").show();
</script>';
}
}
}
?>
</body>
However, the objects with particular IDs are not actually shown. Does anyone know why this may be? Thank you.

jQuery actions should be placed in $( document ).ready( function () {} );, i.e.:
echo '<script>$( document ).ready( function () {
$(".warning").hide();
$("#emailFormatError").show();
} );</script>';

Related

CRUD application create working, but not update or delete

I tried getting the CRUD app to work from Tutorial Republic. I can create rows, but can’t read, update, or delete them.
I uploaded index, create, read, update, delete, config, and error.php. It loads index.php fine but when I try to update, read, or delete, all I get is a blank page. Please help. Here’s the code.
config.php
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'user');
define('DB_PASSWORD', 'secret');
define('DB_NAME', 'demo');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
read.php
<?php
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Include config file
require_once "config.php";
// Prepare a select statement
$sql = "SELECT * FROM employees WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = trim($_GET["id"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$name = $row["name"];
$address = $row["address"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id parameter. Redirect to error page
header("location: error.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>View Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h1 class="mt-5 mb-3">View Record</h1>
<div class="form-group">
<label>Name</label>
<p><b><?php echo $row["name"]; ?></b></p>
</div>
<div class="form-group">
<label>Address</label>
<p><b><?php echo $row["address"]; ?></b></p>
</div>
<div class="form-group">
<label>Salary</label>
<p><b><?php echo $row["salary"]; ?></b></p>
</div>
<p>Back</p>
</div>
</div>
</div>
</div>
</body>
</html>
update.php
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$name = $address = $salary = "";
$name_err = $address_err = $salary_err = "";
// Processing form data when form is submitted
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Get hidden input value
$id = $_POST["id"];
// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
} elseif(!filter_var($input_name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$name_err = "Please enter a valid name.";
} else{
$name = $input_name;
}
// Validate address address
$input_address = trim($_POST["address"]);
if(empty($input_address)){
$address_err = "Please enter an address.";
} else{
$address = $input_address;
}
// Validate salary
$input_salary = trim($_POST["salary"]);
if(empty($input_salary)){
$salary_err = "Please enter the salary amount.";
} elseif(!ctype_digit($input_salary)){
$salary_err = "Please enter a positive integer value.";
} else{
$salary = $input_salary;
}
// Check input errors before inserting in database
if(empty($name_err) && empty($address_err) && empty($salary_err)){
// Prepare an update statement
$sql = "UPDATE employees SET name=?, address=?, salary=? WHERE id=?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sssi", $param_name, $param_address, $param_salary, $param_id);
// Set parameters
$param_name = $name;
$param_address = $address;
$param_salary = $salary;
$param_id = $id;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records updated successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Get URL parameter
$id = trim($_GET["id"]);
// Prepare a select statement
$sql = "SELECT * FROM employees WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = $id;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) == 1){
/* Fetch result row as an associative array. Since the result set
contains only one row, we don't need to use while loop */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
// Retrieve individual field value
$name = $row["name"];
$address = $row["address"];
$salary = $row["salary"];
} else{
// URL doesn't contain valid id. Redirect to error page
header("location: error.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Update Record</h2>
<p>Please edit the input values and submit to update the employee record.</p>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control <?php echo (!empty($name_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $name; ?>">
<span class="invalid-feedback"><?php echo $name_err;?></span>
</div>
<div class="form-group">
<label>Address</label>
<textarea name="address" class="form-control <?php echo (!empty($address_err)) ? 'is-invalid' : ''; ?>"><?php echo $address; ?></textarea>
<span class="invalid-feedback"><?php echo $address_err;?></span>
</div>
<div class="form-group">
<label>Salary</label>
<input type="text" name="salary" class="form-control <?php echo (!empty($salary_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $salary; ?>">
<span class="invalid-feedback"><?php echo $salary_err;?></span>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
delete.php
<?php
// Process delete operation after confirmation
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Include config file
require_once "config.php";
// Prepare a delete statement
$sql = "DELETE FROM employees WHERE id = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Set parameters
$param_id = trim($_POST["id"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records deleted successfully. Redirect to landing page
header("location: index.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter
if(empty(trim($_GET["id"]))){
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Delete Record</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="alert alert-danger">
<input type="hidden" name="id" value="<?php echo trim($_GET["id"]); ?>"/>
<p>Are you sure you want to delete this employee record?</p>
<p>
<input type="submit" value="Yes" class="btn btn-danger">
No
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
error.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5 mb-3">Invalid Request</h2>
<div class="alert alert-danger">Sorry, you've made an invalid request. Please go back and try again.</div>
</div>
</div>
</div>
</div>
</body>
</html>

How to pass PHP variable value to html input box from external PHP file?

HTML FILE
<body>
<input type="text" id="name" class="form-control" name="name">
<label for="name">name</label>
<script type="text/javascript" src="PHPfile.php"></script>
</body>
Separate PHP FILE
I have done MySQL query, and I have query value in $row['name'].
How can I put this value in the HTML input box?
<?PHP
**some code here**
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo "<script>
var name = <?php echo $row['name'] ?>;
document.getElementById(name).value='name';
window.location.href='htmlpage.html';
</script>";
?>
I tried this but this didn't work. I got the following error
Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in...
I have tried to provide custom variable to var name and then document.getElementByID line. Still, it doesn't work.
Any Solution?
This should work.
<?php
/**some code here**/
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo '<script>
document.getElementById("name").value = "' . $row['name'] . '";
</script>';
?>
or same thing if more complex HTML/script needed:
<?php
/**some code here**/
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
?>
<script>
document.getElementById("name").value = "<?=$row['name'];?>";
</script>
<?php
/* more php code */
?>
If you still get the same error message, than the problem is somewhere else.
To echo a variable in a string ( in php ) we can use concatenation " . " $var['code'] ". " or template string { $var["code"] }
PHPfile.php
<?php
$row = ["name" => "something"];
echo "
let input = document.getElementById('name');
input.value = '{$row['name']}';
setTimeout(()=>{
window.location.href='htmlpage.html';
} ,2000)
"
?>
For echoing variables in string use {$var} instead of simple concatenation
Extended answer
index.php
<?php
// all querys here ... getting results from db
// assuming result
$row = [
"username" => "xxxxxxxxx",
"email" => "xxxxx#example.com"
];
$name = $row['username'];
?>
<!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>Damn Forms ! </title>
</head>
<body>
<form action="file.php" method="post" accept-charset="utf-8">
<label for="name">Name <span class="red">*</span></label>
<input type="text" id="name" class="form-control" name="name" placeholder="Enter your full name " value="<?= $name ?>">
<!-- sending values to another php file -->
<button type="submit">Submit</button>
</form>
</body>
</html>
file.php
<?php
if($_SERVER["REQUEST_METHOD"] === "POST"){
$name = $_POST['name'];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width">
<title>Input Form </title>
</head>
<body>
<input type="text" name="name" id="" value="<?= $name ?>" />
</body>
</html>
I see 2 answers already, but my way of doing it would be....
HTML
<body>
<input type="text" id="name" class="form-control" name="name">
<label for="name">name</label>
<div id="externalPHP"></div>
<script type="text/javascript">
document.getElementById("externalPHP").innerHTML='<object type="type/php" data="PHPfile.php" ></object>';//javascript
$('#externalPHP').load('PHPfile.php');//jQuery
</script>
</body>
The php file
<?PHP
**some code here**
//value in $row['name']
//confirmed by echo $row['name'];
// now I want to pass this value to my HTML input box
echo '<script>document.getElementById("name").value='."$row['name']".';</script>';
?>

How to change Login to Logout button on wordpress using $_SESSION?

So I have a custom Login page on Wordpress that connects to my users database and checks if all the information is correct. This is the login.php:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['email'])){
// removes backslashes
$email = stripslashes($_REQUEST['email']);
//escapes special characters in a string
$email = mysqli_real_escape_string($conn,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($conn,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password)."'";
$result = mysqli_query($conn,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['email'] = $email;
// Redirect user to index.php
header("Location: index.php");
}else{
echo "<div class='form'>
<h3>Email/password is incorrect.</h3>
<br/>Click here to <a href='../login/'>Login</a></div>";
}
}else{
?>
<div class="form">
<!-- <h1>Log In</h1> -->
<form action="" method="post" name="login">
<input type="text" name="email" placeholder="Email" required />
<input type="password" name="password" placeholder="Password" required />
<br>
<input name="submit" type="submit" value="Login" />
</form>
<p>Not registered yet? <a href='../register/'>Register Here</a></p>
</div>
<?php } ?>
</body>
</html>
What I want to do is change the LOGIN button on my Wordpress header to LOGOUT (and showing the user information if it's possible) after the user is logged, and I suppose that I can do that using the $_SESSION['email'] = $email;variable.
How can I do that?
Thanks a lot!
You can use the built-in WordPress function is_user_logged_in() or is your login using also a custom table in the database and not the WordPress user table wp_user?
<?php
if ( is_user_logged_in() ) {
echo 'Login out';
} else {
echo 'Login';
}
?>
If your login system is independent of WordPress, you need to check your login function and see what session variables it creates, you might also need to start the session your self then if it is not in the function something like this then
session_start();
if (isset($_SESSION['email'])) {
/// your login button code here
} else {
/// your logout button code here
}
A function that would add it to your wordpress menu you need to style it:
add_filter('wp_nav_menu_items', 'button_login_logout', 10, 2);
function button_login_logout() {
ob_start();
if (isset($_SESSION['email'])) :
?>
<a role="button" href="logoutlink">Log Out</a>.
<?php
else :
?>
<a role="button" href="loginlink">Log In</a>
<?php
endif;
return ob_get_clean();
}

How to get the value of mysql.user password

When I log in I am using the mysql.user but I can't log on if the user has a password. If i logged on using any user a with password the page can't logged on to the other php.
The user inputted on the log in will be use on the connection for the database.
<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<title>Log in</title>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/structure.css">
<?php include('connection.php'); ?>
</head>
<body>
<form class="box login" method="post">
<fieldset class="boxBody">
<label>Username</label>
<input type="text" tabindex="1" placeholder="Username" required name="username" id="username">
<label><label class="rLink" tabindex="5">Optional</label>Password</label>
<input type="password" tabindex="2" placeholder="Password" name="password" id="password" >
</fieldset>
<footer>
<input type="submit" class="btnLogin" value="Login" tabindex="4" name="sent">
</footer>
</form>
<?php
if (isset($_POST['sent'])) {
$servername = "localhost";
$username = ($_POST['username']);
$password = ($_POST['password']);
$message="";
// Create connection
$result = $conn->query("SELECT user FROM mysql.user where user='$username' and password='$password'");
if ($result->num_rows > 0) {
$_SESSION["uname"] = "$username";
$_SESSION["pass"] = "$password";
echo '<script type="text/javascript">alert(<?php echo "Success!";?>)</script>';
header("location: main.php");
} else {
$message = "Successfuly entered! hi! $username";
echo '<script type="text/javascript">alert(<?php echo "$message";?>)</script>';
}
}
// Check connection
?>
</body>
</html>
You'd better check for database errors that might happen here
$conn->query("SELECT user FROM mysql.user where user='$username' and password='$password'");
Check if the query executes first.
Its also better to use this one
"SELECT * FROM mysql.user WHERE user= ?"
After checking row count. You can hash current password with user's salt then check if they are equal.
For more security use prepared statements.And check if $_POST['username'] and $_POST['password'] are set too (even if your input fields are "required")
And for echoing your errors you can have a paragraph with error id
<p id="error"></p>
And echo this one
'<script>
document.getElementById("error").innerHTML = "'.$error.'"
</script>'
My first answer sorry for bad English.

how do I display different content from database on one php file?

I am trying to use one php file php.project and depending on the name of 1 variable I get all the data from the database that is needed and display it on the site. Right now I have one problem.
I have one php file that is this:
<?php
$pName = $_POST['name'];
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
//insert into database
if(isset($_POST['insertComments'])){
include('connect-mysql.php');
$username = $_POST['username'];
$comment = $_POST['comment'];
$sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
if (!mysqli_query($db_connection, $sqlinsert)){
die('error inserting new record');
}
else{
$newRecord = "1 record added";
}//end nested statement
}
//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="libs/ppo.js"></script>
<link rel="stylesheet" href="libs/ppo.css"/>
</head>
<body>
<div id="intro">
</div>
<div id="bgNav">
<nav id="nav">
Home
<a class="rightNav" href="register.php">Register</a>
<a class="rightNav" href="login.php">Log in</a>
</nav>
</div>
<div id="projectTile">
<span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
<h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
<?php
while($row = mysqli_fetch_array($results))
{
echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
}
?>
</div>
<div id="uploadComments">
<form method="post" action="project.php">
<label for="name"><input type="hidden" name="insertComments" value="true"></label>
<fieldset>
<legend>comment</legend>
<label>Name:<input type="text" id="name" name="username" value=""></label><br/>
<label>Comments: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Submit" id="submitComment">
</fieldset>
</form>
</div>
</body>
</html>
depending on the variable $pName the content of the site changes, because it gets its content from a database and $pName stands for "project name".
$pName is determenent by the name of the picture you click on the index page which is this:
<?php
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="libs/ppo.js"></script>
<link rel="stylesheet" href="libs/ppo.css"/>
</head>
<body>
<div id="bgNav">
<div id="login">
Register
Log in
</div>
<nav id="nav">
Home
</nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
<?php
while($row = mysqli_fetch_array($results))
{
$project = $row["name"];
echo nl2br("<img id=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form action="project.php" method="post" id="formF">
<label><input id="inputF" type="hidden" name="name"></label><br>
<input type="submit">
</form>
</body>
</html>
by clicking the image I put the name of it in a form and submit it to project.php. in project. php it is stored in the variable $pName . The problem is that once I refresh the page the $pName becomes Null and you see none of the database's data on the page. my question is: how can change this code in a way that $pName doesn't become Null when I refresh the page? and are there any suggestions on how to improve this code?
this is my javascript:
var check = null;
var form = $('#myForm');
$(document).ready(function(){
$('img').click(function(){
$('#inputF').val(this.id);
$("input[type=submit]").trigger("click");
});
});
Add Sessions to you code (as requested by #aleation).
Also, using parameters directly to query your database is very dangerous (as #jeroen mentioned).
Read up on the topic of SQL Injections and try to evaluate $pName before using it in a query.
<?php
session_start();
if(!is_null($_POST['name']))
{
$pName = $_POST['name'];
$_SESSION['pName'] = $pName;
}
elseif (array_key_exists('pName',$_SESSION)) {
$pName = $_SESSION['pName'];
}
else {
$pName = ''; // Maybe set a default here?
}
$pName = $_POST['name'];
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
...
Tiny glimpse into the Problem SQL Injections bring: In your example, imagine someone send's a POST request where name is ';Delete FROM project where id <>.
This would result in you loosing all your entries in the project table.
And that Query injection wouldn't even be that hard to guess.
With analyzing your website, someone could get hold of userdata, manipulate userdata, insert userdata ... you see? It is a mess.
Why are you using a $_POST variable for selecting the right content? If you make your images hyperlinks with the project name in the address, you can refresh the page without losing the variable content.
change:
echo nl2br("<img id=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>");
into
echo nl2br("<img id=\"$project\" width='100px' alt='Project name' height='100px' class='tile' src=".$row['image']."/>");
and then get $pname = $_GET['name'] instead of $pname = $_POST['name']

Categories