POST method problem in php in trying to create CRUD - php

I'm trying to create a CRUD data grid with php it is very simple but facing a problem with POST method every time I refresh my page it enters my previous data. Im trying to learn php i have basic knowledge of different languages like c# and java. Kindly answer me as soon as possible.
here is my code :
home.php :
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP CRUD</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<?php require_once 'process.php'; ?>
<?php
$mysqli = new mysqli('localhost','root','','crud')or die(mysql_error($mysqli));
$result= $mysqli->query("SELECT * FROM data")or die($mysqli->error);
?>
<div class="row justify-content-center">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = $result->fetch_assoc()): ?>
<tr>
<td>
<?php echo $row['name'] ?>
</td>
<td>
<?php echo $row['location'] ?>
</td>
<td></td>
</tr>
<?php endwhile; ?>
</table>
</div>
<div class="container">
<div class="row justify-content-center">
<form action="process.php" method="GET">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="Enter your name">
</div>
<div class="form-group">
<label>Location</label>
<input type="text" name="location" class="form-control" value="Enter Your Location">
</div>
<div class="form-group">
<button type="submit" name="save" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</body>
</html>
This the the process.php :
<?php
$mysqli = new mysqli('localhost','root','','crud') or die(mysql_error($mysqli));
if(isset($_GET['save']))
{
$name=$_GET['name'];
$location=$_GET['location'];
$mysqli->query("INSERT INTO data (name,location) VALUES ('$name','$location')") or die($mysqli->error);
}
?>

First you need to use parameterized queries (How can I prevent SQL injection in PHP?). Second, you should use POST and redirect after:
HTML
<form action="process.php" method="POST">
PHP
if(isset($_POST['save']))
{
$stmt = $mysqli->prepare(("INSERT INTO data (name, location) VALUES (?, ?)");
$stmt->bind_param('ss', $_POST['name'], $_POST['location']);
$stmt->execute();
header("location: confirmation.php"); // or whatever
} else {
header("location: home.php"); // or whatever
}
exit;
Find a tutorial as there are other things you need to do, such as making sure the $_POST values are !empty(), checking for DB errors, etc.

Related

input forms doesn't save in phpmyadmin

I am new to PHP. My input forms doesn't save any of it in my MySQL database but everytime I press my submit button it shows "register=success",
even though its not inserted in my database and its not showing any errors in any line.
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form id="BG" class="col-lg-8" action="includes/register.php" method="POST">
<div class="form-group">
<label for="formGroupExampleInput">Firstname</label>
<input type="text" class="form-control col-lg-6" id="formGroupExampleInput" placeholder="Firstname" name="fName">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Lastname</label>
<input type="text" class="form-control col-lg-6" id="formGroupExampleInput2" placeholder="Lastname" name="lName">
</div>
<div class="form-group">
<label for="formGroupExampleInput">Plate #</label>
<input type="text" class="form-control col-lg-6" id="formGroupExampleInput" placeholder="Plate #" name="plateNo">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Vehicle brand</label>
<input type="text" class="form-control col-lg-6" id="formGroupExampleInput2" placeholder="Vehicle brand" name="vBrand">
</div>
<div class="form-group">
<label for="formGroupExampleInput">color</label>
<input type="text" class="form-control col-lg-6" id="formGroupExampleInput" placeholder="color" name="color">
</div>
<button type="submit" name="submit" class="btn btn-primary">Register</button>
</form>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.slim.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</html>
conn.php
<?php
$dbSname='localhost';
$dbUname ='root';
$pwd='';
$dbName = 'capstone';
$conn = mysqli_connect($dbSname,$dbUname,$pwd,$dbName);
register.php
<?php
include_once 'includes/conn.php';
$fname=$_POST['fName'];
$lName=$_POST['lName'];
$plateNo=$_POST['plateNo'];
$vBrand=$_POST['vBrand'];
$color=$_POST['color'];
$sql = "INSERT INTO register(name,lastname,Plateno,vehiclebrand,color)
VALUES($fname,$lName,$plateNo,$vBrand,$color);";
mysqli_query($conn,$sql);
header("Location: ../index.php?register=success");
?>
I was expecting my input to save data to my MySQL database.
First you need to know if an error is happening when you run your query. So, my recomendation is to change your .php script to handle exceptions, like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
//start of your code
$host = "localhost";
$user = "root";
$pass = "";
$db = "capstone";
$conn = new mysqli($host,$user,$pass,$db);
$sql = "INSERT INTO register(name,lastname,Plateno,vehiclebrand,color)
VALUES($fname,$lName,$plateNo,$vBrand,$color);";
$conn->query($sql);
//end of your code
}
catch(mysqli_sql_exception | Exception $e){
$error="Error #".$e->getCode()." ".$e->getMessage().PHP_EOL;
if(isset($conn) && get_class($e) == "mysqli_sql_exception")
$error.="SQLSTATE #".$conn->sqlstate." SQL: $sql".PHP_EOL;
$error.=$e->getTraceAsString();
echo(nl2br($error));
}
finally {
if(isset($result) && $result instanceof mysql_result)
$result->free();
if(isset($conn) && is_resource($conn) && get_resource_type($conn) === 'mysql link')
$conn->close();
}
?>
Once you have an error, you can edit your question and share it.
After you can solve your problem, I would recommend to take a look to this question: How can I prevent SQL injection in PHP?, because is important to learn early how to avoid SQL injection, a concerning security problem.
if (isset($_POST['submit'])) {
$fname=$_POST['fName'];
$lName=$_POST['lName'];
$plateNo=$_POST['plateNo'];
$vBrand=$_POST['vBrand'];
$color=$_POST['color'];
}
I think you should have a if checking if the button isset. If this does not answer your question, pls send the database info So I can check it.

Not updating value and showing the same thing again when update button is pressed

This is an update query for a simple crud im a beginner and it doesnt seem to work.I have tried multiple ways but it just doesnt work the $value seems to be null and it redirects towrds the unsuccessful page
<?php
include 'db.php';
if(isset($_GET['updte']))
{
$id=$_GET['id'];
$name = $_GET['name'];
$email=$_GET['email'];
$password=$_GET['pass'];
$sql2="UPDATE `users` SET `name` = '$name', `email` = '$email', `password` = '$password' WHERE `users`.`id` =$id";
$val=$db->query($sql2);
if ($val){
header('Location:show.php');
}
else{
header('Location:nsuccess.php');
}
}
<!doctype html>
<?php include 'db.php';
$id=$_GET['id'];
$sql="select * from users where id='$id'";
$rows=$db->query($sql);
$row=$rows->fetch_assoc();
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<title>List</title>
</head>
<body>
<div class="container">
<div class="row" style="margin-top: 70px;">
<h1 class="text-center">All Users List</h1>
<div class="col-md-10 col-md-offset-1">
<table class="table">
<hr><br>
<form method="get" action="up.php">
<div class="form-group">
<h1><?php echo $row['id'];?></h1>
<label>Name</label>
<input type="text" required name="name" value="<?php echo $row['name'];?>" class="form-control">
<label>Email</label>
<input type="email" required name="email" value="<?php echo $row['email'];?>" class="form-control">
<label>Password</label>
<input type="password" required name="pass" value="<?php echo $row['password'];?>" class="form-control">
</div>
<input type="submit" name="updte" value="Update" class="btn btn-success">
</form>
</table>
<button onclick="history.go(-1);" class="btn btn-primary">Back </button>
</div>
</div>
</div>
</body>
</html>
Just want the values to be updated
For one, you have #password in your update statement instead of $password.
DB might be looking for it's own variable that's not been set
First and very important: You are wide open for SQL injections.
Then any user can override any user settings by providing a combination of id, name, mail and password simply by editing the URL.
You used #password instead of $password.

phpmyadmin I cannot delete an user

I wrote a code when a user clicks "delete" but it doesn't delete the account, only logs out, I tried searching on internet but nothing was found that helped me.
Here's the code:
<?php include('server.php');
session_start();
if (isset($_GET['delete'])) {
$query = "DELETE FROM `users` WHERE `username` = '$username', `password`='$password'";
mysqli_query($db, $query);
session_destroy();
unset($_SESSION['username']);
unset($_SESSION['password']);
unset($_SESSION['money']);
header("location: login.php");
}
?>
Is there any solutions to this code? should I use AND instead of comma, because it didn't work that way, maybe there's an mistake.
$query has the same code that was used on phpmyadmin and it was successful there.
Sorry about the server.php
Here is the code of it:
Also using md5 for encrypting passwords is not good idea, I probably need to change it.
Here is login.php where the first code came from (the register button is not programmed properly):
<?php include('server.php');
session_start();
if (isset($_GET['delete'])) {
$stmt = $db->prepare('DELETE FROM users WHERE username = ? AND password = ?');
$stmt->bind_param('ss', $_SESSION['username'], $_SESSION['password']); // 's' specifies the variable type => 'string'
$stmt->execute();
session_destroy();
unset($_SESSION['username']);
unset($_SESSION['password']);
unset($_SESSION['money']);
header("location: login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
function register() {
header("location: register.php");
}
</script>
</head>
<body>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
</br>
<form method="post" action="login.php" align="center">
<?php include('errors.php'); ?>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" >
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password">
</div>
<br/>
<div class="input-group">
<button type="submit" class="btn" name="login_user">Login</button>
</div>
<p></p></br>
<p>
<small class="input-group"> Not yet a member? </small> <button type="button" class="btn2" onclick="register()" name="register">Register</button>
</p>
</form>
</body>
</html>
This is register.php:
<?php include('server.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Registration system PHP and MySQL</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
</br></br></br></br></br></br></br>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<?php include('errors.php'); ?>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="reg_user">Register</button>
</div>
<p>
Already a member? Sign in
</p>
</form>
</body>
</html>
This is errors.php:
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
This is index.php:
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
unset($_SESSION['password']);
unset($_SESSION['money']);
header("location: login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="content">
<!-- notification message -->
<?php if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
<!-- logged in user information -->
<?php if (isset($_SESSION['username'])) : ?>
<p>Welcome <strong><?php echo $_SESSION['username']; ?></strong></p>
<p> logout </p>
<p> delete </p>
<?php endif ?>
</div>
</body>
</html>
Without knowing what the content of server.php is, I can see a few error. First, your code is vulnerable for SQL Injections. There are several topics about this on SO, rather read that one here.
Starting with your code - $db,$username, $password are undefined. Guessing from the next lines, it has to be $_SESSION['username'] and $_SESSION['password'] instead.
Also, the SQL doesn't look valid to me, but that's one thing I am not sure about - according to my brain it should be
$stmt = $db->prepare('DELETE FROM users WHERE username = ? AND password = ?');
$stmt->bind_param('ss', $_SESSION['username'], $_SESSION['password']); // 's' specifies the variable type => 'string'
$stmt->execute();
Also I hope you don't store passwords in plaintext.

header location for php going to 404

Working on a simple sign in page where the user enters the name and password. Right now I just have it so when the user enters the usrname and password it should redirect to my success.html page where it will just print out <h2>successful login</h2>. Whenever I try to click the log in button, I can see in my browser that it is catching the username and password but it shows a 404 page. Any help would be appreciated. I will put my code down below for both of the files.
`home.html`
<head>
<title>Hangman Home Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="home.css">
</head>
<body>
<?php
#not empty
#atleast 6 characters long
# array holds errors
$errors = array[];
# validation starts here
if(count($errors) == 0){
# redirect to the game page
header('Location:success.html');
exit();
}
?>
<div class="header">
<div class="a">Hangman</div>
</div>
<div class="topnav">
</div>
<br>
<br>
<br>
<!--column start here -->
<div class="hi">
<table id="leader">
<tr>
<th><img src="crown.gif"></th>
</tr>
<tr>
<td>Leader Board</td>
</tr>
<tr>
<td>1st. John : 4 guess</td>
</tr>
<tr>
<td>2nd. Smith : 6 Guesses</td>
</tr>
<tr>
<td>3rd. Tom : 7 Guesses</td>
</tr>
<tr>
<td>4th. Allen : 8 Guesses</td>
</tr>
</table>
</div>
<!-- form start here -->
<br>
<br>
<div class="b">Think You Can Beat #1 ?</div>
<center><button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Play Now!!!</button></center>
<div id="id01" class="modal">
<form method="post" class="modal-content animate">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<img src="hang1.gif" alt="logo" class="avatar">
</div>
<div class="container">
</p>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit" value="submit">Login</button>
</div>
</form>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
</div>
</body>
</html>
`success.html`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-
width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"
content="ie=edge">
<title>Document</title>
</head>
<body>
<h2> Successful Connection!</h2>
</body>
</html>
First thing, Where is the doctype and html tag for home.html? And the next is that forms should contain an action attribute that should specify the location/page where the information should be sent to like
<form action="success.html" method="POST" class="modal-content animate">
if success.html and home.html are in the same directory.
action attribute takes empty strings if you want the form to be submitted to the same page as he form.
Although it is not necessary but not specifying it creates unexpected problems sometimes. Read more basics about forms at https://www.w3schools.com/html/html_forms.asp

PHP: Issue inserting data to MySQL from simple html form

I am relatively new to the PHP / MYSQL world (and programming in general) so apologies in advance for any ignorance on my part.
I have been following a YouTube tutorial from PHPAcademy detailing how to create a simple HTML form and submit data via PHP & MySQLi. The video also teaches how to perform a SELECT * statement and display the entire table in an HTML table.
My issue is that I am unable to post or add the information from the form to the MySQL database. Below is my index.php file & database structure. Any help you can provide is greatly appreciated. Also, I have a connect.php script that initiates the MySQL connection and a security.php script that ensures only UTF-8 text can be inserted into the database. I can provide both of those upon request.
Thank you!
<?php
error_reporting(0);
require 'db/connect.php';
require 'security.php';
$records = array();
if(!empty($_POST)) {
if(isset($_POST['items_item'], $_POST['items_item_location'], $_POST['items_notes'], $_POST['items_quantity'])) {
$items_item = trim($_POST['items_item']);
$items_item_location = trim($_POST['items_item_location']);
$items_notes = trim($_POST['items_notes']);
$items_quantity = trim($_POST['items_quantity']);
if(!empty($items_item) && !empty($items_item_location) && !empty($items_notes) && !empty($items_quantity)) {
$insert = $db->prepare("INSERT INTO items (items_item, items_item_location, items_notes, items_quantity) VALUES (?, ?, ?, ?)");
$insert->bind_param('ssss', $items_item, $items_item_location, $items_notes, $items_quantity);
if($insert->execute()) {
header('Location: index.php');
die();
}
}
}
}
if($results = $db->query("SELECT * FROM items")) {
if($results->num_rows) {
while($row = $results->fetch_object()){
$records[] = $row;
}
$results->free();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Grocery list!</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
Grocery Application <small>Created by Bryce</small>
</h1>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-4 column">
<form class="form-horizontal" action="" method='post'>
<fieldset>
<legend>Add grocery item</legend>
<div class="form-group">
<label for="inputItem" class="col-lg-2 control-label">Grocery Item</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputItem">
</div>
</div>
<div class="form-group">
<label for="inputLocation" class="col-lg-2 control-label">Location</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputLocation">
</div>
</div>
<div class="form-group">
<label for="inputNotes" class="col-lg-2 control-label">Notes</label>
<div class="col-lg-10">
<textarea class="form-control" rows="3" id="inputNotes"></textarea>
<span class="help-block">Here you can enter notes about your item such as the quantity, number of units, or any other general information.</span>
</div>
</div>
<div class="form-group">
<label for="inputLocation" class="col-lg-2 control-label">Quantity</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputQuantity">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
<div class="col-md-8 column">
<?php
if(!count($records)){
echo 'No records';
} else {
?>
<table class="table table-bordered table-striped">
<tr>
<th>Item</th>
<th>Location</th>
<th>Notes</th>
<th>Quantity</th>
</tr>
<?php
foreach($records as $r){
?>
<tr>
<td><?php echo escape($r->items_item); ?></td>
<td><?php echo escape($r->items_item_location); ?></td>
<td><?php echo escape($r->items_notes); ?></td>
<td><?php echo escape($r->items_quantity); ?></td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
<br><br>
</div>
</div>
</div>
</body>
</html>
Database structure:
id (autoincremented, interger) | items_item (varchar 255) | items_item_location (varchar 255) | items_notes (text) | items_quantity (text)
Edit: This answer is a per your original post and not marking your edited question as an edit under the original.
None of your form elements contain a name attribute and are required when using POST.
Change your form elements to these, respectively:
<input name="items_item" type="text" class="form-control" id="inputItem">
<input name="items_item_location" type="text" class="form-control" id="inputLocation">
<textarea name="items_notes" class="form-control" rows="3" id="inputNotes"></textarea>
<input name="items_quantity" type="text" class="form-control" id="inputQuantity">
These ^, are to work in conjunction with:
$_POST['items_item']
$_POST['items_item_location']
$_POST['items_notes']
$_POST['items_quantity']
I hope you were not relying on an "id" alone, not for this anyway.
Plus using error_reporting(0); doesn't help, it suppresses possible errors.
Some of which would have been "Undefined index...".
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Footnotes:
Instead of doing:
if($insert->execute()) {
header('Location: index.php');
die();
}
Use/replace with: (to check for possible errors)
if($insert->execute()) {
header('Location: index.php');
die();
}
else{
die('There was an error running the query [' . $db->error . ']');
}
// rest of your code you have now

Categories