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.
Related
So I have created a streaming website and I want to create an admin panel so that admin can add a preview, a thumbnail, the category and the main video to the database. I tried in this way but this isn't working so any suggestions where I might be going wrong?
The error I am getting is "Notice : Trying to get property 'error' of non-object in adminhandler.php on line 33"
admin.php
<?php
include("config.php");`enter code here`
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ShortFilm</title>
<link rel="stylesheet" href="./css/global.css">
<link rel="stylesheet" href="./css/admin.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" />
</head>
<body>
<!-- Content Starts -->
<div class="admin-box">
<form action="adminHandler.php" method="POST" class="admin-box-form" enctype="multipart/form-data">
<h3 class="admin-box-title">Add Movie</h3>
<div class="form-group">
<label htmlFor="name">Movie Name</label>
<input type="text" name="name" id="name" placeholder="Enter movie name" value="" required />
</div>
<div class="form-group">
<label htmlFor="category_id">Movie Genre</label>
<input type="number" name="category_id" id="category_id" placeholder="Enter movie genre" value="" required />
</div>
<div class="form-group">
<label htmlFor="thumbnail">Movie Cover</label>
<input type="file" name="thumbnail" id="thumbnail" required/>
</div>
<div class="form-group">
<label htmlFor="preview">Movie Preview</label>
<input type="file" name="preview" id="preview" required/>
</div>
<!-- <div class="form-group">
<label htmlFor="filePath">Movie File</label>
<input type="file" name="filePath" id="filePath" required/>
</div> -->
<button type="submit" class="btn btn-primary" name="admin_form" value="Submit">
Submit
</button>
</form>
</div>
</body>
</html>
adminhandler.php
<?php
// Change the upload limits in php.ini
// ini_set('upload_max_filesize', '50M');
// ini_set('post_max_size', '50M');
// ini_set('max_input_time', 300);
// ini_set('max_execution_time', 300);
if (isset($_POST['admin_form'])) {
include 'config.php';
// File Targets
$targetCover = "../entities/thumbnail/" . basename($_FILES['thumbnail']['name']);
$targetMovie = "../entities/previews/" . basename($_FILES['preview']['name']);
// Store in DB
$name = strtolower($_POST['name']);
$category= strtolower($_POST['categoryId']);
$thumbnail = "entities/thumbnail/" . basename($_FILES['thumbnail']['name']);
$filePath = "entities/previews/" . basename($_FILES['preview']['name']);
$sql = "INSERT INTO entities(name, thumbnail, preview, categoryId) VALUES('$name','$thumbnail', '$filePath','$category')";
$result = $con -> query($sql);
if ($result && move_uploaded_file($_FILES['thumbnail']['name'], $targetCover) && move_uploaded_file($_FILES['preview']['name'], $targetMovie)) {
echo "<script type='text/javascript'>alert('Movie Added Successfully! Press OK to Redirect to Admin Page.')</script>";
echo '<script type="text/javascript">window.location.href="admin.php"</script>';
}
else {
echo "<script type='text/javascript'>alert(`Error Uploading Movie! Press Try Again.\n{$con -> error}`)</script>";
echo '<script type="text/javascript">window.location.href="admin.php"</script>';
}
}
?>
Database Tables
enter code here
I have uploaded all the php files on live server same as on localhost. Few files works fine. But my registration page is not working when i try to register it does not store data in phpmyadmin. and shows the error as below.
enter image description here
<!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>Event Management</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<!--<link href="css/style.css" rel="stylesheet"/>-->
<link href="layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
<!--<link href="css/bootstrap.css" rel="stylesheet"/>-->
<link href="css/bootstrap.min.css" rel="stylesheet"/>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js" type="text/javascript"></script>
</head>
<body>
<!-- Database file include -->
<?php require_once ('main.php'); ?>
<!-- Database file include End -->
<div class="container justify-content-center">
<h2 align="center">Log In or Sign Up</h2>
<div class="container">
<form method="post" action="main.php">
<div class="row justify-content-center">
<div class="col-6">
<input type="text" class="form-control" placeholder="Name" name="name"/>
<label></label>
<label></label>
<input type="text" class="form-control" placeholder="username" name="username"/>
<label></label>
<label></label>
<input type="password" class="form-control" placeholder="password" name="password"/>
<label></label>
<label></label>
<input type="email" class="form-control" placeholder="email" name="email"/>
<label></label>
<label></label>
<input type="text" class="form-control" placeholder="contact" name="contact"/>
<label></label>
<label></label><br />
<button class="btn btn-info" id="register" name="register">Register</button>
</div>
</div>
<div class="row justify-content-center">
<div class="col-6">
<label>Already have an Account?</label>
Login Here.
</div>
</div>
</form>
</div>
</div>
</body>
</html>
main.php file code for registration
if(!empty($_POST['name']) && !empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['email']) && !empty($_POST['contact']))
{
$Name = $_POST['name'];
$uName = $_POST['username'];
$pass = $_POST['password'];
$mail = $_POST['email'];
$contact = $_POST['contact'];
$date = date('d-m-yy');
$mysqli->query("insert into register(Name,username,password,Email_Id,Phone_No,
date_Created) values('$Name','$uName','$pass','$mail','$contact','$date')") or die($mysqli->error);
$mysqli->query("insert into users(email,user_name,pass_word) select r.Email_Id, r.username, r.password from register r where r.Email_Id NOT IN (SELECT email FROM users);") or die($mysqli->error);
echo "Data inserted successfully!";
header('location: login.php');
}
You've an error on main.php line number 73.
Undefined variable: mysqli
Please show more to view & get your solution.
Thanks
im creating a form using redbean php. however i had trouble in passing id in form.php to thankyou.php . i need to display total price in thank you page after customer submit form. i dont know what im missing in my code. please help me. thank you.
form.php
<?php
session_start();
require_once 'redbean_orm/rb.php';
$connection = new PDO('mysql:host=localhost;dbname=ocms','root','');
R::setup($connection);
$_SESSION["submit"] = '';
if(isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] === "POST") {
//create table and field
$customerinfo = R::dispense('customer');
$customerinfo->name = $_POST['name'];
$customerinfo->address = $_POST['address'];
$customerinfo->price = $_POST['price'];
$id = R::store($customerinfo);?>
<html>
<body>
<div class="container">
<div class="row">
<div class="col-md-8">
<form action="" method="POST" id="contact-form">
<div class="form-group">
<label>Full Name</label>
<input type="text" class="form-control" name="name" placeholder="Name" required>
</div>
<div class="form-group">
<label>Address</label>
<textarea type="text" class="form-control" name="address" placeholder="Address"></textarea>
<!--<input type="text" class="form-control" name="address" placeholder="Address" required>-->
</div>
<div class="form-group">
<label>Price</label>
<input class="form-control" name="price" value="RM100.00" readonly="readonly" type="text" id="total">
</div>
<div class="form-group">
<button class="btn btn-info" name="submit">
<a href="thankyou.php?id=<?php echo $id;?>"
style="text-decoration: none;">Submit</a></button>
<!--<?php echo R::load('users',$_POST['id']); ?>-->
</div>
</form>
</body>
</html>
thankyou.php
<?php
session_start();
require_once 'redbean_orm/rb.php';
$connection = new PDO('mysql:host=localhost;dbname=ocms','root','');
R::setup($connection);
if (isset($_SESSION["submit"])) {
$userinfo = R::load('users',$_GET['id']);
}
?>
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Thank You</title>
</head>
<body>
<div class="jumbotron text-xs-center">
<h1 class="display-3">Thank You For Your Request!</h1><br>
<p class="lead"><strong>Your total charge :</strong><br>
<?php
foreach (R::find('users') as $customer) {
echo $customer = $_GET['id'].$customer['price'];
}
?>
<!--<input name="price" value="<?php echo $userinfo->price ?>" readonly="readonly" type="text">-->
</p>
<hr>
</div>
</body>
</html>
i am familiar with sql but when used redbean php it quite confusing.
for anyone who is looking for this solution. i found it myself. i shouldnt save price in database. just store in session and send it thankyou.php. Thank you for looking here. solution:
inside post, i add $_SESSION['price'] = $_POST['price']; Then in thankyou.php. i insert echo $_SESSION['price'].
My PHP page is unable to pick values from HTML form. It's sending blank strings to database. Here is my HTML and PHP code. Please find error. I am new to PHP, unable to solve the problem.
my html page:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>LOGIN</title>
<link rel="stylesheet" href="css/reset.css">
<link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- Mixins-->
<!-- Pen Title-->
<div class="pen-title">
<h1>SYNCHPHONY</h1>
</div>
<div class="rerun">Rerun Pen</div>
<div class="container">
<div class="card"></div>
<div class="card">
<h1 class="title">Login</h1>
<form name="login" action="login.php" method="POST">
<div class="input-container">
<input type="text" id="loginid" required="required"/>
<label for="loginid">Login ID</label>
<div class="bar"></div>
</div>
<div class="input-container">
<input type="password" id="password" required="required"/>
<label for="password">Password</label>
<div class="bar"></div>
</div>
<div class="button-container">
<button><span>Go</span></button>
</div>
</form>
</div>
<div class="card alt">
<div class="toggle"></div>
<h1 class="title">Register
<div class="close"></div>
</h1>
<form name="register" action="register.php" method="POST">
<div class="input-container">
<input type="text" id="loginid" required="loginid"/>
<label for="loginid">Login ID</label>
<div class="bar"></div>
</div>
<div class="input-container">
<input type="password" id="password" required="required"/>
<label for="password">Password</label>
<div class="bar"></div>
</div>
<div class="button-container">
<button value'submitb'><span>Next</span></button>
</div>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
my php page:
**strong text** <?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "syncphony";
$loginid="";
$password="";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['loginid'])){ $loginid = $_POST['loginid']; }
if(isset($_POST['password'])){ $password = $_POST['password']; }
// Escape user inputs for security
$loginid = mysqli_real_escape_string($conn,$loginid);
$password = mysqli_real_escape_string($conn,$password);
// attempt insert query execution
$sql = "INSERT INTO users (loginid, password ) VALUES ('$loginid', '$password')";
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
// close connection
mysqli_close($conn);
?>
The inputs inside your form tag do not have names. Try this for login:
<input type="text" id="loginid" required="required" name="loginid"/>
and this for password:
<input type="password" id="password" required="required" name="password"/>
It would be nice if you would protect your users against XSS attacks and to use encryption when you store a password. Also, you should structure your code and make sure your HTML is valid.
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