Selecting data from mysql database from a search form - php

I am new at this and still learning. I have a search page and want to use the input to search a mysql table and display results in a form to update the record back into the table.
Every time I try and run it I get a PHP Notice: Undefined variable: password in /var/www/html/update.php on line 106, referer: http://172.20.10.161/search.php
in the error_log.
All help would be most appreciated.
I have google and tried various methods to get this right, i feel there is some little thing I am missing here.
Below is the code from my search.php page
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
?>
<form action="update.php" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Search">
</div>
</form>
Then on my page that should show the results if have the following.
update.php
top of page
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
header("location: login.php");
exit;
}
?>
Code in page to run query
<?php
require_once "include/dbconf.php";
if(isset($_POST['Search']))
{
$name=$_POST['name'];
$sql = "SELECT (name, surname, email, username, password) from net_users WHERE name LIKE '%".$name."%'";
$result = mysqli_query($link, $sql) or die ('Something went wrong');
while($row=mysqli_fetch_array($result))
{
$username =$row['username'];
$password =$row['password'];
$name =$row['name'];
$surname =$row['surname'];
$email =$row['email'];
}
}
mysqli_close($link);
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<label>Surname</label>
<input type="text" name="surname" class="form-control" value="<?php echo $surname; ?>">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" value="<?php echo $email; ?>">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="text" name="password" class="form-control" value="<?php echo $password; ?>">
/div>
<div class="form-group">
<input type="update" class="btn btn-primary" value="update">
</div>
</form>
I am hoping to pull the desired input on search $name to search the mysql db and return the results in the form on the update page to update the information back into the database.

I would recommend a couple of changes to update.php.
<?php
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
// Can everyone logged in update the system. If not, filter it as required
header("location: login.php");
exit;
}
?>
Given the following connection file dbconf.php with a procedual MySQLi - https://www.php.net/manual/en/mysqli.quickstart.dual-interface.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', 'xxxxxxxx');
define('DB_PASSWORD', '**********');
define('DB_NAME', 'users');
/* 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());
}
?>
The search query will need to account for SQL Injection - How can I prevent SQL injection in PHP?.
<?php
require_once "include/dbconf.php";
// placeholder for the returned data
$data = array();
// Verify the search query is present
// Or handle empty
if(isset($_POST['name']))
{
// SQL injection - https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
$name=$_POST['name'];
// TODO: Verify that you need the password here
// Generally passwords are not to be stored as plain text
$sql = "SELECT (id, name, surname, email, username, password) from net_users WHERE name LIKE '?'";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, 's', $name);
// Execute the query
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
// Copy the result to a local array
// Each entry in $data will be an associative array of values
$data[] = $row;
}
} else {
// TODO : Handle this more gracefully
die('Search query missing');
}
mysqli_close($link);
if (empty($data))
{
// TODO: No records matched, handle gracefully
die('No records matched');
}
?>
Once you have the data, output as needed. Note that I have also selected id column - As all other fields are updateable, it would not be possible to identify the record if all the fields are changed. To work around this, you need a value that will always identify the record being updated. I have chosen the id column, but any other unique - non-updateable field would do.
<?php
foreach($data as $record)
{
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="hidden" name="id" value="<?php echo $record['id']; ?>" />
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo $record['name']; ?>">
</div>
<div class="form-group">
<label>Surname</label>
<input type="text" name="surname" class="form-control" value="<?php echo $record['surname']; ?>">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" value="<?php echo $record['email']; ?>">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $record['username']; ?>">
</div>
<div class="form-group">
<label>Password</label>
<input type="text" name="password" class="form-control" value="<?php echo $record['password']; ?>">
/div>
<div class="form-group">
<input type="update" class="btn btn-primary" value="update">
</div>
</form>
<?php
}
?>

Related

My simple html php form not inserting into database

For some reason, this form doesn't insert into my database.
Html
<form action="../php/register.php" method="post">
<div id ="personal-form">
<h4><b>Personal Details:</b></h4>
<hr>
<div class="form-group">
<label class="sr-only" for="first-name">First name</label>
First Name
<input type="text" name="firstname" placeholder=""
class="form-control" id="firstname">
<button type="submit" class="btn btn-next" id="submit">
Submit
</button>
</center>
</div>
</div>
</form>
php/register.php
<?php
include('connect.php');
if(isset($_POST["submit"])) {
$firstname = $_POST["firstname"];
$stmt = $conn->prepare("INSERT INTO storeowners (firstname) VALUES
(:firstname)");
$stmt->bindParam(':firstname', $firstname);
$stmt->execute();
header("location: next.php");
}
?>
This is connect.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=blaza", $username,
$password);
//set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "success";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
When I click on submit button, it shows the php/register.php page with the message success which is thesame message in the connect.php code if db connection was successful.
I dont know where the problem is cause it doesnt store the firstname to the database and no error was given.
if(isset($_POST["submit"]))
You have no form controls with name=submit so this condition will never be true.
You connect to the database unconditionally, but you never use the connection to do anything.
Add name="submit" to your button.
<form action="../php/register.php" method="post">
<div id ="personal-form">
<h4><b>Personal Details:</b></h4>
<hr>
<div class="form-group">
<label class="sr-only" for="first-name">First name</label>
First Name
<input type="text" name="firstname" placeholder="" class="form-control" id="firstname">
<button name="submit" type="submit" class="btn btn-next" id="submit">Submit</button></center>
</div>
</div>
</form>
Instead of $_POST["submit"] add this
if(isset($_POST["firstname"]))

I want show message about existing username under username input tag and when show the message other the data doesn't lose in php

I want show message about existing username under username input tag and when show the message other the data doesn't lose. But this codes don't work.
Here is my code for existing username:
<?php
//click register button
if(isset($_POST['register']))
{
//Retrieve the field values from our registration form.
$username = $_POST['username'];
//Now, we need to check if the supplied username already exists.
$sql = "SELECT COUNT(user_username) AS num FROM users WHERE user_username = :username";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
echo "<script>";
echo "$(document).ready(function(){document.getElementById('existing_username').innerHTML = 'existing'})";
echo "</script> ";
//the following code is work but other data like name, password is lost in input element
//echo '<div class="alert alert-danger"> <b>'.$username.'</b> This username already exist!</div>';
} }
?>
And here is my code for input data:
<form action="register.php" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="username"><b>USERNAME</b></label>
<input class="form-control" type="text" id="username" name="username">
</div>
</div>
</div>
<span class="text-danger" id="existing_username"></span>
<button class="btn btn-primary" type="submit" name="register" value="Register">Register</button>
</form>
when show the message other the data doesn't lose
What data?!
ok,so you should store the error message which is Username exist in a variable,like below :
<?php
//click register button
if(isset($_POST['register']))
{
//Retrieve the field values from our registration form.
$username = $_POST['username'];
//Now, we need to check if the supplied username already exists.
$sql = "SELECT COUNT(user_username) AS num FROM users WHERE user_username = :username";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
echo "<script>";
echo "$(document).ready(function(){document.getElementById('existing_username').innerHTML = 'existing'})";
echo "</script> ";
$error = "<b>".$username."</b> :This username already exist!";
//this code is work but other data is lost
} }
?>
<form action="register.php" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="username"><b>USERNAME</b></label>
<input class="form-control" type="text" id="username" name="username">
</div>
</div>
</div>
</form>
Check this answers too Embed Php in Html
You need to provide value attribute for your form fields. For example:
<input class="form-control" type="text" id="username" name="username" value="<?php echo $username ?>">
OR
<input class="form-control" type="text" id="name" name="name" value="<?php echo $name ?>">
etc.
Of course you need to define these variables in you code first. If form have been submitted - take them from $_POST. If not - set them as empty values.
Code example with 2 fields:
<?php
$name = null;
$username = null;
//click register button
if (isset($_POST['register'])) {
//Retrieve the field values from our registration form.
$name = $_POST['name'];
$username = $_POST['username'];
//Now, we need to check if the supplied username already exists.
$sql = "SELECT COUNT(user_username) AS num FROM users WHERE user_username = :username";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row['num'] > 0) {
echo "<script>";
echo "$(document).ready(function(){document.getElementById('existing_username').innerHTML = 'existing'})";
echo "</script> ";
$error = "<b>".$username."</b> :This username already exist!";
//this code is work but other data is lost
}
}
?>
<form action="register.php" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="name"><b>NAME</b></label>
<input class="form-control" type="text" id="name" name="name" value="<?php echo $name ?>">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="username"><b>USERNAME</b></label>
<input class="form-control" type="text" id="username" name="username" value="<?php echo $username ?>">
</div>
</div>
</div>
<span class="text-danger" id="existing_username"></span>
<button class="btn btn-primary" type="submit" name="register" value="Register">Register</button>
</form>

php coding Form submission to server using php

I have typed this coding by using php and mysql. In If statement condition Id part is not inserted into database. But other fields are inserted into database. I couldn't find out the error. Can anyone tell what is the error?
<?php
$conn=mysqli_connect("localhost","root","database","user") or die("unable to connect");
//echo "Connected Successfully";
?>
<h2>Form Submission to Server</h2>
<?php
if(isset($_POST["submit"]))
{// get user inputs
$error="";
$resultmessage="";
$id=$_POST["id"];
$firstname=$_POST["firstname"];
$lastname=$_POST["lastname"];
$email=$_POST["email"];
$password=$_POST["password"];
//error messages
$missingfirstname="<p>Enter your First name</p>";
$missinglastname="<p>Enter your Last name</p>";
$missingemail="<p>Enter your Email id</p>";
$invalidmail="<p>enter your valid mail id</p>";
$missingpwd="<p>Enter your password</p>";
if(!$firstname)
{
$error.=$missingfirstname;
}
else
{
$firstname=filter_var($firstname,FILTER_SANITIZE_STRING);
}
if(!$lastname)
{
$error.=$missinglastname;
}
else
{
$lastname=filter_var($lastname,FILTER_SANITIZE_STRING);
}
if(!$email)
{
$error.=$missingemail;
}
else
{
$email=filter_var($email,FILTER_SANITIZE_EMAIL);
if(!filter_var($email,FILTER_VALIDATE_EMAIL))
{
$error.=$invalidmail;
}
}
if(!$password)
{
$error.=$missingpwd;
}
if($error)
{
$resultmessage='<div class="alert alert-danger">'.$error.'</div>';
echo $resultmessage;
}
else
{
//no errors,prepare variables for query
$tblname="attend4";
$firstname=mysqli_real_escape_string($conn,$firstname);
$lastname=mysqli_real_escape_string($conn,$lastname);
$email=mysqli_real_escape_string($conn,$email);
$password=mysqli_real_escape_string($conn,$password);
$password=md5($password);
//execute the query
if(!$id)
{
$sql="INSERT INTO attend4(firstname,lastname,email,password)VALUES('$firstname','$lastname','$email','$password')";
}
else
{
$sql="INSERT INTO attend4(id,firstname,lastname,email,password)VALUES('$id',$firstname','$lastname','$email','$password')";
} if(mysqli_query($conn,$sql))
{
$resultmessage="Data added successfully";
echo $resultmessage;
}
else
{
$resultmessage="unable to add";
echo $resultmessage;
}
}
}
?>
<form action="33.populateusigform.php" method="post">
<div class="form-group">
<label for="number">Number</label>
<input type="number" name="id" id="id" class="form-control" maxlength="4" placeholder="Enter your Number">
</div>
<div class="form-group">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" maxlength="30" class="form-control" placeholder="Enter your Firstname">
</div>
<div class="form-group">
<label for="lastname">Lastname</label>
<input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Enter your lastname" class="form-control">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" id="email" maxlength="30" placeholder="Enter your Email Id"class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" maxlength="30" placeholder="Enter your Password" class="form-control">
</div>
<input type="submit" name="submit" class="btn btn-success center-block" value="Send data">
</form>
I suspect your issue is with the if($id) which may act strangely if given 0, triggering the sql query without the id term.
I would use if(empty($id)) instead it will be more reliable.
Too many problems...
1) you have kept your action "33.populateusigform.php" for form but are inserting data from same file....
2) have you kept your id to auto increment?
3) what is use to save id in your case, it will automatically be saved if you use as primary key in db.
Need to check your db schema for further assistance.

Automatically reload data from database into HTML form after submitting

I am trying to create a user profile registration for my site. The basics are already in place, where users can now signup and login to the site.
Each member receives a unique Member ID in the DB and after logging in they are given access to the page below. It is a simple form that loads data from the database as pre-filled values in the html form input fields. Changing this data and submit the data, stores the data correctly in the database. All thanks to examples and advice from experts at this site.
My question is how would I make the form to reload, or the fields to update with the new data from the DB without having to reload the page manually after clicking the submit button?
It would also be greatly appreciated with any feedback about the security of this form. I have tried to study mySQL PDO and prepared statements to avoid SQL injection but I feel that I have a long way to go before fully understand it all and make sure the site is secure.
<?php require('includes/config.php');
//Redirect to login page if not logged in
if(!$user->is_logged_in()){ header('Location: login.php'); }
//Get user profile data from DB
$sth= $db->query ("SELECT username, firstname, middlename, lastname, email FROM members");
$sth->bindColumn (1, $username);
$sth->bindColumn (2, $firstname);
$sth->bindColumn (3, $middlename);
$sth->bindColumn (4, $lastname);
$sth->bindColumn (5, $email);
while ($sth->fetch (PDO::FETCH_BOUND))
//Process form when submitted
if(isset($_POST['submit'])){
//if nothing is wrong, store data in DB
if(!isset($error)){
try {
//update user profile in database with a prepared statement
$sql = "UPDATE members SET username = :username,
firstname = :firstname,
middlename = :middlename,
lastname = :lastname,
email = :email
WHERE memberID = :memberID";
$stmt = $db->prepare($sql);
$stmt->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
$stmt->bindParam(':middlename', $_POST['middlename'], PDO::PARAM_STR);
$stmt->bindParam(':lastname', $_POST['lastname'], PDO::PARAM_STR);
$stmt->bindParam(':email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':memberID', $_SESSION['memberID'], PDO::PARAM_STR);
$stmt->execute();
//catch error message if something is wrong
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}
//define page title
$title = 'Profile Registration';
//include member header
require('layout/header_member.php');
?>
<div class="container">
<h2>Please Register Your Profile</h2>
<p>Get started and register your profile below</p>
<p>Your member ID is: <?php echo $_SESSION['memberID']; ?> </p>
<?php
//show any error messages from the database here
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
?>
</div>
<hr>
<div class="container">
<form class="form-horizontal" role="form" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label class="control-label col-sm-2" for="username">Display name</label>
<div class="col-sm-10">
<input type="text" required class="form-control" name="username" id="username" placeholder="Your Display Name" value="<?php if(isset($error)){ echo $_POST['username']; } ?><?php echo $username; ?>" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="firstname">First name</label>
<div class="col-sm-10">
<input type="text" required class="form-control" name="firstname" id="firstname" placeholder="Your first name" value="<?php if(isset($error)){ echo $_POST['firstname']; } ?><?php echo $firstname; ?>" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="middlename">Middle initials</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="middlename" id="middlename" placeholder="Middle initials" value="<?php if(isset($error)){ echo $_POST['middlename']; } ?><?php echo $middlename; ?>" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="lastname">Last name</label>
<div class="col-sm-10">
<input type="text" required class="form-control" name="lastname" id="lastname" placeholder="Your last name" value="<?php if(isset($error)){ echo $_POST['lastname']; } ?><?php echo $lastname; ?>" >
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email</label>
<div class="col-sm-10">
<input type="email" required class="form-control" name="email" id="email" placeholder="Your email address" value="<?php if(isset($error)){ echo $_POST['email']; } ?><?php echo $email; ?>" >
</div>
</div>
<button type="submit" name="submit" value="submit" class="btn btn-default">Submit</button>
</form>
</div>
<?php
//include footer
require('layout/footer.php');
?>
You can change the values of your HTML form to this:
value="<?php
if(isset($_POST['username'])) {
echo $_POST['username'];
} else {
echo $username;
} ?>"
The values submitted will show if the form failed (which you have used as $error) and also should the form successfully submit and update the database. In other words, it will always have either $username or the value that was last submitted in the form.
You could also look into "Sanitize filters" to filter away any unwanted characters that the user posts.

NO SQL INJECTION ERROR

When I submit this form this error appears NO SQL INJECTION.
The action of this form is the same file ..
I tried to do a lot of solutions and nothing works!
How can I escape that error? There is no change on the database.
Here is the php code
<?php
include '../inc/config.php';
include 'dbc.php';
page_protect();
if(!checkAdmin()) {
header("Location: login.php");
exit();
}
$ads_id = (isset($_GET['id']) ? $_GET['id'] : NULL);
if (!is_numeric($ads_id)) { die ('No SQL INJECTION') ;};
if ($ads_id) {
$img_ads_info = $mysqli->query("SELECT * FROM `ads_image` WHERE `id` = '$ads_id'");
$row = $img_ads_info->fetch_object();
$section_id = $row->user_id;
$ads2 = $mysqli->query("SELECT users.company_name FROM ads_image,users where
ads_image.user_id = users.id AND ads_image.user_id='$section_id'");
$row2 = $ads2->fetch_object();
?>
<div class="panel panel-default ">
<div class="panel-heading" id="accordion"><span class="glyphicon
glyphicon-comment"></span><?php echo $row->description; ?></div>
<div class="panel-body">
<form role="form" action="manage_images_ads.php" method="POST">
<div class="form-group">
<input type="hidden" name="id" value="<?php echo $row->id;
?>" />
<label>اسم المؤسسة المعلنة</label>
<input required name="company_name" class="form-
control" type="text" maxlength="255" value="<?php echo $row2->company_name; ?>"/>
</div>
<div class="form-group">
<label>عنوان الإعلان</label>
<input required name="title" class="form-control"
type="text" maxlength="255" value="<?php echo $row->title; ?>"/>
</div>
<div class="form-group">
<label>صورة الإعلان</label>
<img src="upload/<?php echo $row->up; ?>" />
</div>
<div class="form-group">
<label>عدد المشاهدات</label>
<input required name="views" class="form-control"
type="text" maxlength="255" value="<?php echo $row->views; ?>"/>
</div>
<div class="form-group">
<label>رابط الإعلان</label>
<input required name="ad_link" class="form-control"
type="text" maxlength="255" value="<?php echo $row->ad_link; ?>"/>
</div>
<button style="float:left" type="submit"
value="submit" class="btn btn-success btn-md" id="btn-chat">Send</button>
</div>
</form>
<?php
if(isset($_POST['submit'])) {
$title = $mysqli->real_escape_string($_POST['title']);
$ad_link = $mysqli->real_escape_string($_POST['ad_link']);
$views = $mysqli->real_escape_string($_POST['views']);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "UPDATE ads_image SET `title`='$title',`ad_link`='$ad_link',`views`='$views'
WHERE `id`='$ads_id'";
if ($mysqli->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
}
}
?>
The reason is that your form has 'method="POST"' while php is looking for id in the $_GET superarray. Just change
$ads_id = (isset($_GET['id']) ? $_GET['id'] : NULL);
to
$ads_id = (isset($_POST['id']) ? $_POST['id'] : NULL);
and it should start work properly.

Categories