I have created php submit button using form action with the intention of just storing a username and school name to be stored in a database using xampp by clicking okay button. I have set the database table to have flds for ID as primary key and AI, username and school set to varchar with max length of 50. The code i have used shown does $con to the DB but only the ID is being send to the DB?? (what have i missed or need to do so that the data inputted can be stored like the ID)?.
<?php
require 'config.php';
$username = " "; //$username
$school = " ";//what school they attend
if(isset($_POST['register_button'])){
$_SESSION['reg_username'] = $username; //Stores first name into session variable
$_SESSION['reg_school'] = $school; //Stores first name into session variable
$query = mysqli_query($con, "INSERT INTO users VALUES ('', '$username', '$school')");
}
?>
<html>
<head>
<title> School </title>
</head>
<body>
<h1> Welcome! </h1>
<form action="index.php" method="POST">
<input type="text" name="reg_username" placeholder="Name" value="<?php
if(isset($_SESSION['reg_username'])) {
echo $_SESSION['reg_username'];
}
?>" required>
<br>
<input type="text" name="reg_school" placeholder="School" value="<?php
if(isset($_SESSION['reg_school'])) {
echo $_SESSION['reg_school'];
}
?>" required>
<br>
<input type="submit" name="register_button" value="Okay">
</body>
</html>
You need to load the post data into your variables before you insert them. The only assignement you did was $username = '';
$username = $_POST['reg_username'];
$school = $_POST['reg_school'];
Related
I have a form that show the user information and when I load userpage.php all info appear in each field and user can edit his information all is good until the user click on save button, it have to show the same form with updated information, data updated in database but the new data doesn't appear when user click save.
This is the form fields values after click on save button:
Notice: Trying to access array offset on value of type
null in C:\xampp\htdocs\server\userpage.php on line
27
Notice: Trying to access array offset on value of type
null in C:\xampp\htdocs\server\userpage.php on line 28
Notice: Trying to access array offset on value of type
null in C:\xampp\htdocs\server\userpage.php on line 29
This is the userpage.php file:
<?php
session_start();
include 'connection.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Account</title>
</head>
<body>
<?php
if(isset($_SESSION['Status'])){
echo "<h2>".$_SESSION['Status']."<h2>";
unset($_SESSION['Status']);
}
$id = $_POST['loginID'];//a get this from login page
$_SESSION['nid'] = $id; //To use it in update file
$query = "SELECT id, username, phone, email FROM user WHERE id ='$id';";
$result = mysqli_query($conn,$query);
$info =mysqli_fetch_array($result);
?>
<form id="profile" action="update.php" method="post">
<fieldset>
<input type="text" name="username" id="username" value="<?php echo $info['username'] ?>" >
<input type="tel" name="phone" id="phone" value="<?php echo $info['phone'] ?>" >
<input type="email" name="email" id="email" value="<?php echo $info['email'] ?>">
<input class="button" type="submit" name="save" value="save">
</fieldset>
</form>
</body>
</html>
Update.php file code:
<?php
session_start();
include 'connection.php';
if(isset($_POST['save'])){
$id = $_SESSION['nid']; //Get the id from userpage.php file
$phone = $_POST['phone'];
$email = $_POST['email'];
$query = "UPDATE user SET phone='$phone', email='$email' WHERE id='$id'";
$result = mysqli_query($conn,$query);
if($result){
$_SESSION['Status'] = "Updated";
header('location: userpage.php');
}
else{
$_SESSION['Status'] = "Not updated";
header('location: userpage.php');
}
}
?>
On your userpage.php. You get $id via method POST but in the page update.php you redirect back to userpage.php. The redirection is method GET that is why you lost the ID.
To prevent this, use session that is already set.
First, remove your 2 lines of code.
$id = $_POST['loginID'];//a get this from login page
$_SESSION['nid'] = $id; //To use it in update file
And replace with this.
$id = ($_POST['loginID'] ?? null);// use null coalesce operator to prevent undefined index.
// the $_POST['loginID'] code above still get the value that send via method POST from login page.
if ($id !== '' && !is_null($id)) {
// if id is not empty and not null. I don't check with empty() function to allow zero (0) value.
// set it to session.
$_SESSION['nid'] = $id;
} elseif (isset($_SESSION['nid'])) {
// if session nid was set, use it.
// this condition will work on redirected back.
$id = $_SESSION['nid'];
} else {
// if come to this condition, it means that you have no ID at all!
// do whatever you want such as redirect to logout page for login again.
}
And then you can use $id as before.
i am trying to create a login and registration page using php and mysql but i met with some problem.
I reference to this video and the code is below (the code is incomplete, i only did for registration).
So the problem is that when i submit an entry using the register side, my database shows a blank record. I tried various method like
$reg = "INSERT INTO usertable (user,pwd) values ('".$user."','".$pwd."')";
but it did not work and when i did this:
$reg = "INSERT INTO usertable (user,pwd) values ('ABC','1234')";
it worked. What should i do to insert entry using the input text?
<?php
session_start();
$conn = mysqli_connect('localhost', 'root', '1234');
mysqli_select_db($conn,'registeration');
$user = $_POST["user"];
$pwd = $_POST["pwd"];
$s = "select * from usertable where user = '$user'";
$result = mysqli_query($conn,$s);
$num = mysqli_num_rows($result);
if($num == 1){
echo"Username Already Taken";
}
else{
$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')";
mysqli_query($conn,$reg);
}
?>
<h2> Register Here </h2>
<form action="index.html" method="post">
<label>Username</label>
<input type="text" name="user" required>
<label>Password</label>
<input type="text" name="pwd" required>
<br><button type="submit"> Login </button>
</form>
A easy way to know what's full SQL query string the program or you have made.
$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')";
echo $reg
It is better use {} to instead of . to insert variable into a string.
$reg = "INSERT INTO usertable (user,pwd) values ('{$user}','{$pwd}')";
To be sure the POST/GET action target is correct,
For your current code I am not sue index.html can handle it, probably it should be $_SERVER["PHP_SELF"]
To understand PHP String Operators, please refer to
https://www.php.net/manual/zh/language.operators.string.php
I found my mistake. I wrote my php and the register table (together in registration.php) however, my form redirects me to index.html. I copied and pasted my php into my index.php (changed the name) and it worked.
Thanks for those who helped me!
<h2> Register Here </h2>
<form action="index.php" method="post">
<label>Username</label>
<input type="text" name="user" required>
<label>Password</label>
<input type="text" name="pwd" required>
<br><button type="submit"> Login </button>
</form>
I am a complete beginner when it comes to PHP. I have successfully created a login form/page that requires a user to enter his/her username and password which is then added to a database. I have also managed to create a page (using php) to display the data contained in all the data fields. I have the db connection file separately which works well. I have a functions.php file which contains the functions.
Now, I have created a php file in which I should be able to update the data in the various fields in the database. Instead of updating/replacing the existing data (username & password) in the selected row (targeting the id) it creates a new row in the db with the new username & password. Herewith my code to update existing data fields.
<?php include "db.php";?>
<?php include "functions.php";?>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .= "username = '$username', ";
$query .= "password = '$password', ";
$query .= "WHERE id = $id ";
$result = mysqli_query($connection, $query);
if(!$result) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="col-sm-6">
<form action="login_create.php" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<select name="id" id="">
<?php
showAllData();
?>
</select>
</div>
<input class="btn btn-primary" type="submit" name="submit" value="UPDATE">
</form>
</div>
</div>
</body>
</html>
I can simply not find the problem. Since people use PHP differently I am unable to find a solution based on the specific coding I have tried.
Update
Kindly note that I am working on a localhost as part of learning php and have not yet started looking at security. I am initialising the $connection via a different file (db.php) which I am calling in the first line of my previous code.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');
if(!$connection) {
die("Database connection failed");
}
?>
Since you didn't say what does the login_create.php do and what is the filename of that php code in your post. I can only guess that your login_create.php file is to create a new account not update it. Perhaps your file with that UPDATE query is not named login_create.php. Hence, my guess is that you put a wrong filename in your <form action="login_create.php" method="post">
(Posted solution on behalf of the question author).
The problem was with the incorrect naming of the form action. I used
<form action="login_create.php" method="post">
instead of
<form action="login_update.php" method="post">
I have 3 files.
1st one :
<html>
<form action="employeeDel.php" method ="post">
Enter Ssn To Delete Employee:<br>
<input type="number" name="ssnDel">
<br>
<br>
<input type="submit" value="Submit">
</form>
</html>
This form sends data to employeeDel.php.
employeeDel.php :
<html>
<form action ="employeeDelFinal.php" method="post">
<input type="hidden" name="ssn" value="ssnDel">
<?php
$ssnDel = $_POST ["ssnDel"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = mysqli_connect ( $servername, $username, $password, $dbname );
// Check connection
if (! $conn) {
die ( "Connection failed: " . mysqli_connect_error () );
}
$sql = "SELECT * from employee WHERE ssn=".$ssnDel;
<input type="submit" name="Delete?">
</form>
</html>
From here, when user clicks on submit button, I want html form to send ssnDel value to employeeDelFinal.php file.
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
That value never reaches here. I got an error on employeeDel.php file, it says value of ssnDel is null. I guess in the beginning of form in employeeDel file, I create ssnDel again, so it becomes null.
Is there a way to send a data from html form to employeeDel.php, from employeeDel.php to employeeDelFinal.php by using form? I tried hidden text but it didn't solve my problem as seen.
The line
<input type="hidden" name="ssn" value="ssnDel">
should be something like
<input type="hidden" name="ssn" value="<?php echo(intval($_POST['ssnDel'])); ?>">
(Assuming that ssnDel is an ID-Number.)
Otherwise that hidden variable will have the string-value ssnDel, not the value of the variable $_POST['ssnDel'].
And as already mentioned, echo ssnDel; should be echo $ssnDel; and you should use less spaces (e.g. no spaces after $_POST or function names).
There are couple of things I noticed. You have
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
You don't have a dollar sign in your echo statement ssnDel.
And why do you have spaces in between $_POST ["ssnDel"] make it
$_POST["ssnDel"]
This is an effort to create a PHP page to add data to a table. I am getting a parsing error on line 79 so I have been fiddling with it for a while:
Parse error: syntax error, unexpected T_STRING in /home/sharah19/dev.rahmaninet.org/new.php on line 79
Also I have another question: Whats the easiest way to make this page secure? So only users who are authenticated through the login page can add a record?
The contents of new.php:
<?php
/*
NEW.PHP
Allows user to create a new entry in the database
*/
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($first, $last,$email, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Add a New Record</title>
<link href="rahmani.css" rel="stylesheet">
</head>
<body>
<div id="main">
<h1>RahmaniNET CRM System</h1>
<?php include("header.php"); ?>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>First Name: *</strong> <input type="text" name="first_name" value="<?php echo $first_name; ?>" /><br/>
<strong>Last Name: *</strong> <input type="text" name="last_name" value="<?php echo $last_name; ?>" /><br/>
<strong>email: *</strong> <input type="text" name="email" value="<?php echo $email; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$first_name = mysql_real_escape_string(htmlspecialchars($_POST['first_name']));
$last_name = mysql_real_escape_string(htmlspecialchars($_POST['last_name']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
// check to make sure both fields are entered
if ($first_name == '' || $last_name == ''|| $email == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($first_name, $last_name, $email, $error);
}
else
{
// save the data to the database
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email' )
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('$first', '$last','$email', $error);
}
?>
The error comes from the lack of a closing quote on your MySQL query:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email') or die(mysql_error());
It should be:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email'") or die(mysql_error());
Also you ask:
Also I have another question: Whats the easiest way to make this page
secure? So only users who are authenticated through the login page can
add a record?
If you are using Apache then you should you use Apache AuthType Basic. More details are here. Details under “Getting it working.”
You are missing a double quote in your sql string:
mysql_query("INSERT contacts SET first_name='$first_name', last_name='$last_name',email ='$email' )