PHP: Issue inserting data to MySQL from simple html form - php

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

Related

POST method problem in php in trying to create CRUD

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.

Error adding username, email and password in a mysql database with php

I am trying to register users using php. Somehow, the only thing that gets put in is the ID. Mind giving me a tip?
<?php
error_reporting(0);
require_once "php/connect.php";
$username = $_POST ['username'];
$useremail = $_POST['useremail'];
$userpwd = $_POST ['userpwd'];
$userpwd2 = $_POST['userpwd2'];
try {
$statement = $dbconnection->prepare("INSERT INTO `tbl_Nutzerdaten` (userid, username, useremail, userpwd) VALUES (null , '$username', '$useremail', '$userpwd')");
$result = $statement->execute();
$fetch = $statement->fetch();
} catch (PDOException $e) {
echo "Fehler:" . $e->getMessage();
}
?>
So this is what my insert.php looks like. I have been trying around to change my form up but still no success. The database has the table : "tbl_Nutzerdaten" with the columns userid,username,useremail and userpwd. Still i can not add anything except the ID.
<!DOCTYPE html>
<html lang="de">
<head>
<title>Registrierung</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/bootstrap.min.css" rel="stylesheet" >
<script src="js/bootstrap.bundle.min.js" ></script>
<?php
error_reporting(0);
require_once "insert.php";
?>
</head>
<body>
<div class="container bg-transparent border-0">
<div class="row">
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto border-0">
<div class="img-thumbnail my-5 border-0">
<img src="bilder/htl logo.png"></img>
<div class="card card-signin my-5 border-0">
<div class="card-body border-0">
<form class="form-signin form-control border-0" action="#" method="post">
<div class="form-label-group">
<h1 class="text-center">Registrierung</h1>
<label for="username">Benutzername</label>
<input type="text" id="username" class="form-control text-center" placeholder="Benutzername" required autofocus>
<div class="form-label-group">
<label for="useremail">Email</label>
<input type="email" id="useremail" class="form-control text-center" placeholder="Email" required autofocus>
</div>
</div>
<div class="form-label-group">
<label for="Passwort">Passwort</label>
<input type="password" id="userpwd" class="form-control text-center" placeholder="Passwort" required>
</div>
<div class="form-label-group">
<label for="Passwort2">Passwort bestätigen</label>
<input type="password" id="userpwd2" class="form-control text-center" placeholder="Passwort bestätigen" required>
</div>
<div class="custom-control custom-checkbox mb-3">
<input type="checkbox" class="custom-control-input" id="pwcheck">
<label class="custom-control-label" for="pwcheck">Password merken?</label>
</div>
<button class="btn btn-lg btn-primary btn-block text-uppercase " type="submit">Registrieren</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
And this is the form i am using.
The only thing i see in the Database every time i fill out the form is a ID and empty values.
I would really appreciate the help.
to send data to a specific PHP file you have to define where..
In HTML page in the form tag, the action attribute define the path to your file.php where to send the info.
for example:
<form class="form-signin form-control border-0" action="path/to/your/file.php" method="post">
In your input tags you have to add the "name" attribute, so you can refer to this data in your PHP file with this name... just to be clear with an example...
<input type="text" name="username" id="username" class="form-control text-center" placeholder="Benutzername" required autofocus>
and then in the PHP file take this data with something like this
$username = $_POST ['username'];
Then you have to send the data to a specific database, after all your controls on this data that you want..
To send the data you have to learn how avoid SQL injection with prepared statement, bind parameters and finally execute the statement.
I thinks you have to take a look to all this stuff, I suggest you to see this links:
https://www.php.net/manual/en/book.pdo.php
https://www.w3schools.com/php/php_forms.asp
https://www.w3schools.com/html/html_forms_attributes.asp

how to retrieve id from form page to another page using redbean php

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'].

Prevent date and time insert to the database

I am trying to make reservations system, and I have created table reservations which contain columns (id, officename, roomname, resstart, resend, resuser). Restart and resend are DATATIME type. I created a form with date picker and it's inserted successfully to the database.
Here is my PHP file:
<?php
session_start();
include('includes/config.php');
include('includes/checklogin.php');
check_login();
$username = $_SESSION['username'];
//code for add courses
if($_POST['submit'])
{
$officename=$_POST['officename'];
$roomname=$_POST['roomname'];
$startdate=$_POST['startdate'];
$enddate=$_POST['enddate'];
$query="insert into reservations (officename,roomname,resstart,resend,resuser) values(?,?,?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('sssss',$officename,$roomname,$startdate,$enddate,$username);
if($stmt->execute()){
echo"<script>alert('Your Reservation Has Been Added Successfully');</script>";
}else{
echo"<script>alert('Warning! You cannot Reserve this appointment');</script>";
}
}
?>
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<meta name="theme-color" content="#3e454c">
<title>Make New Reservation</title>
<link rel="stylesheet" href="css/awesome-bootstrap-checkbox.css">
<link rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="js/validation.min.js"></script>
<!--Load Script and Stylesheet -->
<script type="text/javascript" src="jquery.simple-dtpicker.js"></script>
<link type="text/css" href="jquery.simple-dtpicker.css" rel="stylesheet" />
$(document).ready(function() {
$( "#date" ).datepicker({ dateFormat: "yy-m-d" });
});
</script>
</head>
<body>
<?php include('includes/header.php');?>
<div class="ts-main-content">
<?php include('includes/sidebar.php');?>
<div class="content-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="page-title">Make New Reservation</h2>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Make New Reservation</div>
<?php echo "<h4>You Logged in As: <span>$username</span></h4>";
?>
<div class="panel-body">
<?php if(isset($_POST['submit']))
{ ?>
<p style="color: red"><?php echo htmlentities($_SESSION['msg']); ?><?php echo htmlentities($_SESSION['msg']=""); ?></p>
<?php } ?>
<form method="post" class="form-horizontal">
<div class="hr-dashed"></div>
<div class="form-group">
<label class="col-sm-2 control-label">Select Office </label>
<div class="col-sm-8">
<Select name="officename" class="form-control" required>
<option value="Select Office">Select Office</option>
<?php
$sql="select * from offices";
$stmt2 = $mysqli->prepare($sql);
//$stmt2->bind_param('i',$roomno);
//$stmt->bind_param('i',$aid);
$stmt2->execute() ;//ok
$res=$stmt2->get_result();
while ($row=$res->fetch_object()) {
echo "<option value=". $row->officename .">" . $row->officename . "</option>";
}
?>
</Select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Select Room </label>
<div class="col-sm-8">
<Select name="roomname" class="form-control" required>
<option value="Select Room">Select Room</option>
<?php
$sql="select * from rooms";
$stmt2 = $mysqli->prepare($sql);
//$stmt2->bind_param('i',$roomno);
//$stmt->bind_param('i',$aid);
$stmt2->execute() ;//ok
$res=$stmt2->get_result();
while ($row=$res->fetch_object()) {
echo "<option value=". $row->roomname .">" . $row->roomname . "</option>";
}
?>
</Select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Start time and date</label>
<div class="col-sm-8">
<input type="text" autocomplete="off" name="startdate" value="" required>
<script type="text/javascript">
$(function(){
$('*[name=startdate]').appendDtpicker();
});
</script>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">End time and date</label>
<div class="col-sm-8">
<input type="text" autocomplete="off" name="enddate" value="" required>
<script type="text/javascript">
$(function(){
$('*[name=enddate]').appendDtpicker();
});
</script>
</div>
</div>
<div class="col-sm-8 col-sm-offset-2">
<input class="btn btn-primary" type="submit" name="submit" value="Make New Reservation">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I want the form to prevent insert to the table, if there is a user tried to make new reservation with already exists time for the same room. Like Room 1 reserved at 1:00 to 2:00, so next user can't register Room 1 at 1:10 to 2:00 for example, but he can register Room 2 at the same time.
Thanks in advance.
Take a count from the table reservations with the requesting roomnumber and new reservation time, and see if a record exists in the table between the resstart and resend time.
If I understood your question correctly, any of the below two query should work.
select count(1) from reservations where roomname = 'XYZ' and '17-SEP-17' between resstart and resend;
or
select count(1) from reservations where roomname = 'XYZ' and to_date('17-SEP-17') between resstart and resend;
the best way to prevent duplicate is to create a unique key in your database.
ALTER TABLE reservations ADD CONSTRAINT constr_reservations UNIQUE (roomname,resstart,resend,resuser)
in this case you code must not be changed.
because you are already catching the insert failure
if($stmt->execute()){
echo"<script>alert('Your Reservation Has Been Added Successfully');</script>";
}else{
//ROOM DUPLICATE CASE!!!
echo"<script>alert('Warning! You cannot Reserve this appointment');</script>";
}

Adding data to database using modal form in bootstrap

I've been really struggling with this today. Can't seem to get it to work, all it does is navigates to 'add-entry.php?go' in the navbar, but goes grey then reloads the index.php with modal still intact with my entries in it.
Here's my html, including the form and javascript filter input.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ProSys Component Lookup</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!--Custom CSS -->
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<!-- Wrapper -->
<div class="container-fluid">
<div class="col-xs-12">
<div class="col-xs-12">
<!-- Header -->
<div class="page-header">
<h1>ProSys Component Lookup</h1><br>
</div>
<!-- Main table content -->
<div class="container-fluid">
<button type="button" class="btn btn-primary btn-block" data-toggle="modal" data-target="#myModal">Add New Item</button><br>
<div class="modal fade" role="dialog" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Item</h4>
</div>
<div class="modal-body">
<form method="post" action="add-entry.php?go" role="form">
<div class="form-group">
<label for="location">Location:</label>
<input type="text" class="form-control" name="location">
</div>
<div class="form-group">
<label for="category">Category:</label>
<select class="form-control" name="category">
<option>Processor</option>
<option>Diode</option>
<option>Fuse</option>
<option>Regulator</option>
<option>Capacitor</option>
<option>Inductor</option>
<option>LED</option>
<option>Gate</option>
<option>Modem</option>
<option>Transceiver</option>
<option>Thermistor</option>
<option>Load Switch</option>
<option>Op Amp</option>
<option>Optocoupler</option>
<option>Line Driver</option>
<option>ESD Protection</option>
<option>ADC</option>
<option>RTC</option>
</select>
</div>
<div class="form-group">
<label for="manufacturer">Manufacturer:</label>
<input type="text" class="form-control" name="manufacturer">
</div>
<div class="form-group">
<label for="description">Description:</label>
<textarea type="text" class="form-control" name="description" rows="5"></textarea>
</div>
<div class="form-group">
<label for="packagesize">PackageSize:</label>
<input type="text" class="form-control" name="packagesize">
</div>
<div class="form-group">
<label for="category">Supplier:</label>
<select class="form-control" name="supplier">
<option>Farnell</option>
<option>RS</option>
<option>Rapid</option>
</select>
</div>
<div class="form-group">
<label for="suppliernumber">Supplier Number:</label>
<input type="text" class="form-control" name="suppliernumber">
</div>
<div class="form-group">
<label for="stock">Stock:</label>
<input type="text" class="form-control" name="stock">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Add</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Search box -->
<div class="col-md-3">
<form class="styled">
<input type="text" class="form-control" onkeyup="myFunctionOne()" id="myInput" placeholder="Search..">
</form><br>
</div>
<div class="panel">
<div class="panel-body">
<div class="row">
<div class="col-xs-12">
<table class="table table-hover" id="table_demo">
<thead>
<tr>
<th>Location</th>
<th>Manufacturer</th>
<th>Description</th>
<th>PackageSize</th>
<th>Supplier</th>
<th>SupplierNumber</th>
<th>Stock</th>
</tr>
</thead>
<tbody id="myTable">
<tr>
<!-- Database connect and display as table -->
<?php
include("dbconnect.php");
$result = mysql_query("SELECT DrawLocation, Manufacturer, Description, PackageSize, Supplier, SupplierNumber, Stock FROM complibrary");
while($complibrary = mysql_fetch_array($result))
{
echo"<td>".$complibrary['DrawLocation']."</td>";
echo"<td>".$complibrary['Manufacturer']."</td>";
echo"<td>".$complibrary['Description']."</td>";
echo"<td>".$complibrary['PackageSize']."</td>";
echo"<td>".$complibrary['Supplier']."</a></td>";
//IF statement adds in links for web search via SupplierNumber
if ($complibrary['Supplier'] == 'Farnell') {
echo"<td><a target='_blank' href='http://uk.farnell.com/search?st=".$complibrary['SupplierNumber']."'>".$complibrary['SupplierNumber']."</a></td>";
} elseif ($complibrary['Supplier'] == 'RS') {
echo"<td><a target='_blank' href='http://uk.rs-online.com/web/c/?sra=oss&r=t&searchTerm=".$complibrary['SupplierNumber']."'>".$complibrary['SupplierNumber']."</a></td>";
} elseif ($complibrary['Supplier'] == 'Rapid') {
echo"<td><a target='_blank' href='https://www.rapidonline.com/Catalogue/Search?query=".$complibrary['SupplierNumber']."'>".$complibrary['SupplierNumber']."</a></td>";
} else {
echo"<td>".$complibrary['SupplierNumber']."</td>";
}
//IF statement end
echo"<td>".$complibrary['Stock']."</td>";
echo "</tr>";
}
mysql_close($conn);
?>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<!-- Latest jQuery -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!-- Filtering script -->
<script>
function myFunctionOne() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[2];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</html>
And here's my add-entry.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
if (isset($_POST['location'])){
$hostname = "localhost";
$username = "root";
$password = "";
$dbname = "componentlookup";
$conn = mysql_connect($hostname, $username, $password);
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $conn);
$location = $_POST['location'];
$category = $_POST['category'];
$manufacturer = $_POST['manufacturer'];
$description = $_POST['description'];
$packagesize = $_POST['packagesize'];
$supplier = $_POST['supplier'];
$suppliernumber = $_POST['suppliernumber'];
$stock = $_POST['stock'];
$query = mysql_query("INSERT INTO 'complibrary' (ID, DrawLocation, Category, Manufacturer, Description, PackageSize, Supplier, SupplierNumber, Stock) VALUES ('NULL', '$location', '$category', '$manufacturer', '$description', '$packagesize', '$supplier', '$suppliernumber', '$stock')");
echo "Item added sucessfully. Click <a href='index.php'>HERE</a> to go back.";
mysql_close($conn);
}
?>
</body>
</html>
Any ideas?
I think you should put data-dismiss="modal" on the add button to close the window.
Also, I think you should not use mysql connection. Better, use mysqli or PDO.

Categories