I am creating a form to connect to a database using PHP. I have the form semi-functional but when I'm trying to test it by pressing the submit button, it says file not found on the webpage.
Here is code for default.php:
<!DOCTYPE HTML> <html> <head>
<title>PHP FORM - 08246 ACW PART 2</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css"> <style> .error {color:
#FF0000;} </style> </head> <body>
<ul class="w3-navbar w3-black w3"> <li>Home</li> <li>Change location to staff member</li> <li>Current location of all staff</li> <li>Edit personal details of staff member</li> <li>List all locations and show list of people in selected location</li> <li>Staff member and list locations for last24 hours</li> </ul>
<div class="w3-container"> <h2> Web Form </h2> </div>
<div class="w3-container"> <?php // defining the variables and setting them to empty values $first_nameErr = $SurnameErr = $usernameErr = $passwordErr = $previous_LocationErr = $current_LocationErr = $dateErr = $timeErr = $dErr = $tErr = ""; $first_name = $Surname = $username = $password = $previous_Location = $current_Location = $date = $time = $dErr = $tErr = "";
//----validation----
//first name if($_SERVER["REQUEST_METHOD"] == "POST"){ if(empty($_POST["first_name"])){ $first_nameErr = "First Name is required"; }else{ $first_name = test_input($_POST["first_name"]); //validation checking if(!preg_match("/^[a-zA-Z ]*$/",$first_name)){ $first_nameErr = "Please enter only letter and white space"; } }
//surname if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["Surname"])){ $SurnameErr="Surname is required"; }else{ $Surname=test_input($_POST["Surname"]); //validation checking if(preg_match("/^[a-zA-Z ]*$/",$Surname)){ $SurnameErr = " Please enter only letters and white spaces"; } }
//date and time date_default_timezone_set('UTC');
$d = str_replace('/',',', '03/05/2016'); $t = str_replace(':',',', '13:38'); $date = $t.',0,'.$d; $fulldate = explode(',',$date); echo '<br>'; $h = $fulldate[0]; $i = $fulldate[1]; $s = $fulldate[2]; $m = $fulldate[3]; $d = $fulldate[4]; $y = $fulldate[5];
echo date("h-i-s-M-d-Y",mktime($h,$i,$s,$m,$d,$y))."<br>"; echo strtotime ("03/05/2016 13:38");
function test_input($data){ $data=trim($data); $data=stripslashes($data); $data=hmtlspecialchars($data); return $data; } ?>
<?php//database
#server info
#$servername = "SQL2008.net.dcs.hull.ac.uk";
#$username = "ADIR\463142";//userid
#$dbname = "rde_463132"; $servername = "SQL2008.net.dcs.hull.ac.uk"; $username = "username"; $myDB = "examples"; $myLocation = "location";
// Create connection $conn = new mysqli($servername, $username, $myLocation); // Check connection if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
// Create database $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) {
echo "Database created successfully"; } else {
echo "Error creating database: " . $conn->error; }
$conn->close(); ?>
<p><span class="error">* are required field.</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> First Name: <input type="text" name="first_name"><br> <span class="error">* <?php echo $First_nameErr;?></span> <br> Surname: <input type="text" name="Surname"><br> <span class="error">* <?php echo $SurnameErr;?></span> <br> Username: <input type="text" name="username"><br> <span class="error">* <?php echo $username;?></span> <br> Current Location: <input type="text" name="current_Location"><br> <span class="error">* <?php echo $current_Location;?></span> <br> Date: <input type="text" name="date"><br> <span class="error">* <?php echo $date;?></span> <br> Time: <input type="text" name="time"><br> <span class="error">* <?php echo $time;?></span> <br>
<input type="submit" name="submit" value="Submit"> </form>
</div> </body> </html>
I am new to this language and still learning.
Any help or advice would be greatly appreciated.
Thank you
What version of PHP you are using to run this script?
As I can see you are using "Register globals" setting to get $_POST data: http://php.net/manual/en/security.globals.php
If you have PHP version 5.4+ you should use $_POST['form_field_name1'] ... $_POST['form_field_nameN'] to get form data.
Add check:
if (!empty($_POST)) { /* Form validation data goes here */ }
File is incorrect, the form action url points to default.php but your filename is defaul.php
Make if default.php instead of defaul.php
For better handling:
In console of your browser, please check the http call, you can see the error it is showing if its a 500 (check logs / enable the debug mode)
Related
I am trying to make a CRUD application. on the Create page I have to have three fields (title, text, category). the problem is that I have to make a method / function in PHP or JS that chooses a random picture from the "images" file and automatically loads it in the database along with the other 3 fields. then it has to appear on the admin.php page together with the other 3 fields.
Images have almost the same name except the last digit which differs (1-2-3)
I have no idea how to make this method/function.
my create.php page
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$title = $text = $category = "";
$title_err = $text_err = $category_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate title
$input_title = trim($_POST["title"]);
if(empty($input_title)){
$title_err = "Please enter a title.";
} else{
$title = $input_title;
}
// Validate text
$input_text = trim($_POST["text"]);
if(empty($input_text)){
$text_err = "Please enter an text.";
} else{
$text = $input_text;
}
// Validate category
$input_category = trim($_POST["category"]);
if(empty($input_category)){
$category_err = "Please enter the category.";
} else{
$category = $input_category;
}
// Check input errors before inserting in database
if(empty($title_err) && empty($text_err) && empty($category_err)){
// Prepare an insert statement
$sql = "INSERT INTO informatii (title, text, category) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_title, $param_text, $param_category, );
// Set parameters
$param_title = $title;
$param_text = $text;
$param_category = $category;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: admin.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
}
?>
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create 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">Create Record</h2>
<p>Please fill this form and submit to add employee record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>title</label>
<input type="text" name="title"
class="form-control <?php echo (!empty($title_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $title; ?>">
<span class="invalid-feedback"><?php echo $title_err;?></span>
</div>
<div class="form-group">
<label>Text</label>
<textarea name="text"
class="form-control <?php echo (!empty($text_err)) ? 'is-invalid' : ''; ?>"><?php echo $text; ?></textarea>
<span class="invalid-feedback"><?php echo $text_err;?></span>
</div>
<div class="form-group">
<label>Category</label>
<textarea name="category"
class="form-control <?php echo (!empty($category_err)) ? 'is-invalid' : ''; ?>"><?php echo $category; ?></textarea>
<span class="invalid-feedback"><?php echo $category_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
this should get you in the right direction (saving the image src is enough), you of course will have to adapt the path to your image folder, and image name
$nr_images = 3;
$random_nr_index = random_int(1,$nr_images);
$random_image_src = '/images/image-'.$random_nr_index.'.jpg';
To do it you need more than one step creating:
A simple html page to post 3 fields value and the image
A php file that receive the post fields and the image and save into mysql
A simple admin.PHP page that shows 3 fields and image
if you already have the images on the server please specify it in a comment
STEP 1:
<html>
<body>
<form method="POST" action="post.php">
f1:<input type="text" name="field1"><br>
f2:<input type="text" name="field2"><br>
f3:<input type="text" name="field3"><br>
im:<input type="file" name="image"><br>
<input type="submit" value="Save">
</form>
</body>
</html>
STEP 2: post.php
<?php
$f1=$_POST["field1"];
$f2=$_POST["field2"];
$f3=$_POST["field3"];
$im=$_POST["image"];
if ($f1 == "" || $f2 == "" || $f3 == "" ){
die("Errors: fields can't be empty! Go back check the fields and try Again");
}
//Saving image on Server's file system if any image
if(isset($_POST["image"])) {
//Saving image with no checking nothing: filetype, mime , extention (it may be very dangerous in a real server exposed to the public)
$where_save = "images/";
$im_name = basename($_FILES["image"]["name"]);
$tmp_name = $_FILES["image"]["tmp_name"];
move_uploaded_file ( $tmp_name , $where_save.$im_name );
}
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// WARNINGS ------------------------------------------------
// I do not care about security , please pay attention to it .
// use some mysql_escape_string , or real_mysql_escape_string
// could mitigate the violence of some sqlinjection attack
$sql = "INSERT INTO yourtable (field1, field2, field3,im_name)
VALUES ('$f1', '$f2', '$f3',$im_name)";
//executing mysql query to save data into it
if (!mysqli_query($conn, $sql)) {
die("Error: " . $sql . "<br>" . mysqli_error($conn));
}
//closing connection
mysqli_close($conn);
//Now we can redirect the user to admin.php where we show data
header("Location: admin.php");
?>
STEP 3:
<?php
$where_are_images="images/";
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Again creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//now we want to read the data from mysql
$sql = "SELECT * FROM yourtable LIMIT 1"; //just limit to the first record
$result = mysqli_query($conn, $sql);
?>
<html>
<body>
<h2>Admin page</h2>
<em> hey every one can see top secret data here , Needs soma care about security!</em>
<?php while($d = mysqli_fetch_assoc($result)){ // LOOPING ?>
<br>
f1:<?= $d["field1"] ?><br>
f2:<?= $d["field2"] ?><br>
f3:<?= $d["field3"] ?><br>
<img src="<?=$where_are_images.$d['im_name']?>">
<br>
<br>
<?php } ?>
</body>
</html>
<php? // CLOSING AND FREE RESOURCES
mysqli_free_result($result);
mysqli_close($conn); ?>
Now you have all you need . Have fun editing it with random images part ...
I hope there are no error (i have not tested it)
hi i found a code on internet and edited a bit but i stuck on showing the correct result i want.. when i type the email address i get the correct result but if i have more than 1 entry i always get the last one is it possible to make it show the result based on the email and the date?
here is my code so far
<?php
// php search data in mysql database using PDO`enter code here`
// set data in input text
$id = "";
$reservation_name = "";
$persons = "";
$date = "";
$time = "";
$email = "";
$status= "";
if(isset($_POST['Find']))
{
// connect to mysql
try {
$pdoConnect = new PDO("mysql:host=localhost;dbname=multi_edit","root","");
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
// id to search
$email = $_POST['email'];
// mysql search query
$pdoQuery = "SELECT * FROM member WHERE email = :email";
$pdoResult = $pdoConnect->prepare($pdoQuery);
//set your id to the query id
$pdoExec = $pdoResult->execute(array(":email"=>$email));
if($pdoExec)
{
// if id exist
// show data in inputs
if($pdoResult->rowCount()>0)
{
foreach($pdoResult as $row)
{
$id = $row['id'];
$reservation_name = $row['reservation_name'];
$persons = $row['persons'];
$date = $row['date'];
$time = $row['time'];
$status = $row['status'];
}
}
// if the id not exist
// show a message and clear inputs
else{
echo 'No Reservation Found On This Email';
}
}else{
echo 'ERROR Something Is Wrong Try Again';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Search Your Reservation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="search.php" method="post">
<center>
Please Enter Your Email Address : <br><br><br><input type="text" name="email" value="<?php echo $email;?>"><br><br>
Reservation Name : <br><input type="text" readonly name="reservation_name" value="<?php echo $reservation_name;?>"><br><br>
Persons : <br><input type="text" readonly name="persons" value="<?php echo $persons;?>"><br><br>
Date Y-M-D : <br><input type="text" name="date" value="<?php echo $date;?>"><br><br>
Time : <br><input type="text" readonly name="time" value="<?php echo $time;?>"><br><br>
Status : <br><input type="text" readonly name="status" value="<?php echo $status;?>"><br><br>
<input type="submit" name="Find" value="Find Data">
</center>
</form>
</body>
</html>
I have work out what you need, it require email (like foobar#gmail.com) and date (like 2018-09-23) in the form input field, if you submit it return the Reservation Name.
Notice for simplicity reason I removed these 3 columns "persons", "time" and "status", but you can add it back, it doesn't change the logic because the finding/query don't need those fields for input
This is my code:
<?php
// php search data in mysql database using PDO`enter code here`
// set data in input text
function sqlInitConn ($args) {
// Initialze connection.
$serverName = $args["serverName"];
$userName = $args["userName"];
$password = $args["password"];
$dbName = $args["dbName"];
$conn = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
// Those variables are for input to mysql.
$idIpt = "";
$reservation_nameIpt = "";
$emailIpt = "";
$dateIpt = "";
// Those variables are for output to front-end.
$idOpt = "";
$reservation_nameOpt = "";
$emailOpt = "";
$dateOpt = "";
if(isset($_POST['find']))
{
try {
// Connect to mysql.
$pdoConnect = sqlInitConn([
"serverName" => "localhost",
// Change it to your server name.
"userName" => "root",
"password" => "change_it_to__your_password_here_if_your_mysql_need_password",
"dbName" => "multi_edit",
]);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
$emailIpt = $_POST['email'];
$dateIpt = $_POST['date'];
$pdoQuery = "SELECT * FROM member WHERE email = :email AND date = :date";
// Mysql search query
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->bindValue(":email", $emailIpt);
$pdoResult->bindValue(":date", $dateIpt);
$pdoExec = $pdoResult->execute();
if($pdoExec) {
// If record exist, show data in inputs
if($pdoResult->rowCount() > 0) {
foreach($pdoResult as $row) {
$idOpt = $row['id'];
$reservation_nameOpt = $row['reservation_name'];
$emailOpt = $row['email'];
$dateOpt = $row['date'];
break;
// only get first occurrences (get first matching record) to prevent corrupted data
// , because same email might wrongly log twice in same day (= same date), like morning and afternoon.).
}
}
else {
echo 'No Reservation Found On This Email';
// If the id not exist, show a message and clear inputs
}
} else {
echo 'ERROR Something Is Wrong Try Again';
// If the id not exist, show a message and clear inputs
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Search Your Reservation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="" method="post">
<center>
<div>
<p>Please Enter Your Email Address :</p>
<input type="text" name="email" value="<?php echo $emailOpt;?>">
</div>
<div>
<p>Reservation Name :</p>
<input type="text" readonly name="reservation_name" value="<?php echo $reservation_nameOpt;?>">
</div>
<div>
<p>Date Y-M-D :</p>
<input type="text" name="date" value="<?php echo $dateOpt;?>">
</div>
<div>
<input type="submit" name="find" value="Find Data">
</div>
</center>
</form>
</body>
</html>
When the inputted number for $points is taken in the inputted field, it adds the number to the total already in the database, but for some reason the number added is double. For example if input 3, 6 will be added to the total. Can anyone help with an answer to this?
The idea is that someone should be able to add points to the total, and then on a separate page able to view it in a progress bar (which is working correctly) but the totals do not add up.
I am new to php so sorry in advance for any mistakes throughout the code.
Thank you
<?php
session_start();
if(!isset($_SESSION["sess_user"])){
header("location:login.php");
} else {
echo "Userid: ".$_SESSION["sess_id"];
?>
<!doctype html>
<html>
<head>
<h2><a id="button" href = "index.php">Main Menu</a></h2>
<h2><a id="button" href = "selftrack.php">Track your updated progress!</a></h2>
</head>
<body>
<?php
// Connect to the database
$username = "";
$password = "";
$host = "";
$db = $username;
$points = $_POST['self_p'];
// Connect to the MySQL server and select the required database
$connection = mysqli_connect($host, $username, $password, $db);
if (mysqli_connect_error()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else { // Database connected correctly
echo "<h1>Add daily points</h1>";
if (isset($_POST["addSubmit"])) {
if ((!empty($_POST["self_p"]))) {// Check all parts of the form have a value
$query="UPDATE targets
SET self_points = self_points + ".$points."
WHERE user_id='".$_SESSION['sess_id']."'";
$result = mysqli_query($connection, $query);
if ($result == false) {
// Show error message
echo "<p>The target points for " . $_POST["self_p"] . " was not added.</p>";
}
else {
echo "<p>The target points for \"" . $_POST["self_p"] . "\" has been added.</p>";
}
}
else {
echo "<p>Please fill out all the details</p>";
}
}
}
?>
<form role="form" id="addForm" name="addForm" action="?" method="post">
<div class="form-group">
<div class="col-xs-7">
<label for="addFormLast_Name">Please enter your daily points, up to 5:</label>
<input class="form-control" id="addFormLast_Name" name="self_p" type="text">
</div>
<div class="form-group">
<div class="col-xs-7">
<input class="form-control" id="addSubmit" name="addSubmit" value="Add Target" type="submit">
</div>
</div>
<?php
mysqli_close($connection);
}
?>
</body>
<?php
?>
</html>
I'm very new to PHP so please bear with me. I have a registration form and I'm submitting the values entered on that form and having them inserted into a MySQL Database table, but I'm getting the following error:
ErrorAccess denied for user ''#'localhost' to database 'myproject'
I've granted all the access that is possible to the user that I'm using in my code, but I'm still having this error. Any help is appreciated and points will be awarded!
Here is my HTML Form:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Registration Page</title>
<script>
function validateForm() {
var x = document.forms["myForm"]["netID"].value;
if (x == null || x == "") {
alert("NetID must be filled out");
return false;
}
var y = document.forms["myForm"]["email"].value;
if (y == null || y == "") {
alert("Email must be filled out");
return false;
}
var n = document.forms["myForm"]["fname"].value;
if (n == null || n == "") {
alert("First Name cannot be blank");
return false;
} else if (n.length < 2) {
alert("First name cannot be less than 2 characters!");
return false;
}
var b = document.forms["myForm"]["lname"].value;
if (b == null || b == "") {
alert("Last Name cannot be blank");
return false;
} else if (b.length < 2) {
alert("Last Name cannot b less than 2 characters!");
return false;
}
}
</script>
</head>
<body>
<ul>
<br>
<br>
<br>
<br>
<center><img src="KSUlogo.PNG" alt="logo" style="width:100px;height:50px;"></center>
<br>
<br>
<br>
<br>
<br>
<li><a class="active" href="#home">Home</a></li>
<br>
<br>
<br>
<br>
<li>News</li>
<br>
<br>
<br>
<br>
<li>Contact</li>
<br>
<br>
<br>
<br>
<li>About</li>
<br>
<br>
<br>
<br>
</ul>
<h1 style="text-align:center;">CCSE Community Profile Page</h1>
<br>
<br>
<br>
<br>
<br>
<h2 style="text-align:center;">Enter your Registration Information</h2>
<div style="text-align:center">
<form name="myForm" action="RegistrationValues.php"
onsubmit="return validateForm()" method="post">
<center>NetID: <input type="text" name="netID"></center>
<br>
<center>Email: <input type="text" name="email"></center>
<br>
<center>First Name: <input type="text" name="fname"></center>
<br>
<center>Last Name: <input type="text" name="lname"></center>
<br>
<br>
Services You Can Provide the CSE Community</center><br>
<br>
<input type="checkbox" name="radio" value="Java"> Java Tutoring<br>
<input type="checkbox" name="radio" value="Computer" checked> Computer Fixing<br>
<input type="checkbox" name="radio" value="PHP" checked> PHP Tutoring<br>
<br><br>
<select name="availabilty">
<option value="blank"></option>
<option value="Java">Morning</option>
<option value="Computer">Evening</option>
<option value="Service">Afternoon</option>
</select>
<br><br>
<center><input type="submit" value="Submit"></center>
</form>
</div>
</body>
</html>
Here is my PHP form:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Registration Page</title>
</head>
<body>
<?php include "header.html";?>
<?php include "navigation.html";?>
<div style="text-align:center">
<p>netID: <?php echo $_POST["netID"]?></p>
<p>Email: <?php echo $_POST["email"]?></p>
<p>First Name <?php echo $_POST["fname"]?></p>
<p>Last Name: <?php echo $_POST["lname"]?></p>
<?php
$netID = $email = $fname = $lname = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$netID = test_input($_POST["netID"]);
$email = test_input($_POST["email"]);
$fname = test_input($_POST["fname"]);
$lname = test_input($_POST["lname"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "myUser";
$password = "newpassword";
$dbname = "myproject";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysql_select_db("$dbname") or die( 'Error'. mysql_error() );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysql_query("insert into ProfileInformation (netID, email, fname, lname, radio, availabilty)
values
('$_POST[netID]','$_POST[email]','$_POST[fname]','$_POST[lname]','$_POST[radio]','$_POST[availabilty]')")
or die(mysql_error());
echo "Done!!!!";
$stmt->close();
$conn->close();
?>
</body>
</html>
It seems to be reading '' as a username somewhere but I'm not sure though.
Thanks in advance. It is greatly appreciated.
You need to pick one api and use it rather than mix n match - however, saying that it would be better to use prepared statements rather than embedding the $_POST variables directly in the sql. Incidentally the names within $_POST need to be quoted unless they exist as constants!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$conn->query("insert into ProfileInformation (netID, email, fname, lname, radio, availabilty)
values
( '{$_POST['netID']}', '{$_POST['email']}', '{$_POST['fname']}', '{$_POST['lname']}', '{$_POST['radio']}', '{$_POST['availabilty']}' )") or die(mysql_error());
echo "Done!!!!";
$conn->close();
Now that you have the issue of the connection sorted ( btw - what was the issue? You should perhaps share the reason it was failing for future readers ) the sql you presented initially is vulnerable to sql injection. The preferred method would be to use a prepared statement like the following:
if( isset( $_POST['netID'], $_POST['email'], $_POST['fname'], $_POST['lname'], $_POST['radio'], $_POST['availabilty'] ) ) {
$host = 'localhost';
$uname = 'xxx';
$pwd = 'xxx';
$db = 'xxx';
$conn = new mysqli( $host, $uname, $pwd, $db );
if ( !$conn ) {
die("Connection failed: " . mysqli_connect_error() );
}
$sql='insert into `ProfileInformation` ( `netID`, `email`, `fname`, `lname`, `radio`, `availabilty` ) values ( ?,?,?,?,?,? );';
$stmt=$conn->prepare( $sql );
if( $stmt ){
$netid=$_POST['netID'];
$email=$_POST['email'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$radio=$_POST['radio'];
$avail=$_POST['availabilty'];
/*
use i for integers
use s for strings
*/
$stmt->bind_params( 'isssss', $netid,$email,$fname,$lname,$radio,$avail );
$result=$stmt? 'Success!' : 'Fail!';
$stmt->close();
$conn->close();
} else {
echo 'Error creating statement';
}
} else {
echo 'One or more required POST variables are not set';
}
check your phpmyadmin. The user myUser and password newpassword that you used i think this is not exists.go phpmyadmin->user Accounts and check.you can try to do this:-
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myproject";
I've got a big issue with my website. I've made a profile page which will allow users to amend their details, and then submit. Upon submitting the details should be updated in the database, however I just get a blank page and nothing happens. I've been up for 30+ hours trying to figure things out but no luck. It's likely to be screwed up, as now is my brain.
Any help would be GREATLY appreciated.
Profile amend page:
<?php
session_start();
if (!isset($_SESSION['Username'])) {
echo 'Welcome, '.$_SESSION['Username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
<!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>Index</title>
<link href="External style sheet layout.css" rel="stylesheet" type="text/css" />
<h1><?php echo date("D M d, Y G:i a"); ?>
<?php $welcome = 'Hi';
if (date("H") < 12) {
$welcome = 'Good Morning';
} else if (date('H') > 11 && date("H") < 18) {
$welcome = 'Good Afternoon';
} else if(date('H') > 17) {
$welcome = 'Good Evening';
}
echo $welcome;
?></h1>
<div class="Login">
<h3><ul>
<?php if(isset($_SESSION['authenticatedUser']) && $_SESSION['authenticatedUser'] != null ) {?>
<li>Welcome <?php echo $_SESSION["authenticatedUser"] ?></li>
<li><span>Log Out</span></li>
<?php } else {?> <li><span>Log In</span></li> <?php } ?>
<li>Register</li>
<li>Basket</li>
</ul></h3>
</div>
</head>
<body>
<div id="container">
<div id="header">
<img src="Images/Schurter3.jpg" width="800" height="300" alt="Schurter" />
</div>
<div id="navigation">
<ul id="navbar">
<li>Home</li>
<li>Components
<ul>
<li>Circuit Protection
<li>Connectors</li>
<li>Switches</li>
<li>EMC Products</li>
<li>Other Products</li>
</ul>
</li>
<li>Electronic Manufacturing Services
<ul>
<li>Application Examples</li>
<li>Processes</li>
</ul>
</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
<?php
include 'db.inc';
//Check to see if a customer ID has been passed in the URL
$memberID = $_GET["memberID"];
// Has a custID been provided? If so, retrieve the customer
// details for editing.
if (!empty($memberID))
{
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databasename) or die ("Unable to select database!");
$query = "SELECT * FROM members WHERE id = " . $memberID;
//Get the recordset
$recordSet = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$row = mysql_fetch_assoc($recordSet);
//Check for errors
//if (!$recordSet)
// print $connection->ErrorMsg();
// else
// {
// Load all the form variables with customer data
$Firstname = $row['Firstname'];
$Surname = $row['Surname'];
$Emailaddress = $row['Emailaddress'];
$Username = $row['Username'];
$Password = $row['Password'];
// }//End else
}
?>
<form name="RegisterForm" action="ProfileUpdate.php" method="post" >
<input type="hidden" name="memberID" value="<?php echo $memberID;?>">
<label>First name*</label>
<input name="Firstname" placeholder="Enter first name here" value="<?php echo $Firstname;?>" required/>
<label>Surname*</label>
<input name="Surname" placeholder="Enter surname here" value="<?php echo $Surname;?>" required/>
<label>Email*</label>
<input name="Emailaddress" type="email" placeholder="Enter email here" value="<?php echo $Emailaddress;?>" required/>
<label>Username*</label>
<input name="Username" type="text" placeholder="Enter a desired username" value="<?php echo $Username;?>" required/>
<label>Password*</label>
<input name="Password" type="password" placeholder="Enter a desired password" value="<?php echo $Password;?>" required/>
<input id="submit" name="submit" type="submit" value="Update Details">
</form>
</body>
</html>
And this is the update action page:
<?php
require('db.inc');
$memberID = $_GET["id"];
echo $memberID;
// trim the POSTed values - gets rid of unecessary whitespace
$Firstname = $_POST['Firstname'];
$Surname = $_POST['Surname'];
$Emailaddress = $_POST['Emailaddress'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];
//Here we use validation at the server
// Vaildate the firstname
?>
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head><title>Customer Details Error</title></head>
<body bgcolor="white">
<h1>Customer Details Error</h1>
<?=$errorString?>
<br>Return to the customer form
</body>
</html>
<?php
// If we made it here, then the data is valid
$connection = mysql_connect($hostname, $username, $password) or die ("Unable to connect!");
// select database
mysql_select_db($databasename) or die ("Unable to select database!");
// this is an update
if (!empty($memberID))
{
$query = "UPDATE members SET ".
"Firstname = '$Firstname', Surname = '$Surname', " .
"Emailaddress = '$Emailaddress', Username = '$Username', Password = '$Password', " .
" WHERE id = $memberID";
$recordSet = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
echo "Your updates are complete!";
}
?>
<?php
session_start();
if (!isset($_SESSION['Username'])) {
echo 'Welcome, '.$_SESSION['Username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
Fix this one to:
<?php
session_start();
if (isset($_SESSION['Username'])) {
echo 'Welcome, '.$_SESSION['Username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
The first one is wrong, it checks for a username if there is no username then it displays the username else it doesnt.
On-topic:
<form name="RegisterForm" action="ProfileUpdate.php" method="post" >
Change the above line to:
<form name="RegisterForm" action="ProfileUpdate.php?id=<?php echo $memberID ?>" method="post" >
As your profileUpdate.php is requesting a member ID, this is necessary and after this, the code should work!