Everything in mysql is printing to only one cell in html table - php

When I print the data from mysql, everything is going into one cell in the first row instead of being spread out through the whole html table.
I've included below all of the code I've written, but the problem is in the get_input.js and get_input.php files at the bottom of this page.
How can I fix this?
vocab_input.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="vocab_input.js"></script>
<script type="text/javascript" src="get_input.js"></script>
<style>
th {
text-align: center;
}
td {
text-align: center;
}
form {
margin-top: 50px;
}
</style>
</head>
<body>
<!-- INPUT -->
<div class="container">
<h1></h1>
<form action="vocab_input.php" method="post" id="input_form">
<label>Word:</label>
<input type="text" name='word'>
<label>POS:</label>
<input type="text" name='pos'>
<label>Translation:</label>
<input type="text" name='trans'>
<label>Definition:</label>
<input type="text" name='definition'>
<label>Sentence:</label>
<input type="text" name='sen'>
<input type="submit">
</form>
</div>
<!-- BUTTONS -->
<div class="btn-group btn-group-justified" role="group" aria-label="..." style="margin-top: 50px;">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" id="list">Vocab List</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Matching</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Scrambled</button>
</div>
</div>
<!-- OUTPUT -->
<table class="table">
<tr>
<th>Word</th>
<th>Part of Speech</th>
<th>Translation</th>
<th>Definition</th>
<th>Sentence</th>
</tr>
<tr>
<td id="mytable"></td>
</tr>
</table>
</body>
</html>
vocab_input.js
$(function() {
$('#input_form').on('submit', function(e) {
var data = $("#input_form :input").serialize();
$.ajax({
type: "POST",
url: "vocab_input.php",
data: data,
});
e.preventDefault();
});
});
vocab_input.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "vocab";
$word = $_POST['word'];
$pos = $_POST['pos'];
$trans = $_POST['trans'];
$definition = $_POST['definition'];
$sen = $_POST['sen'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert data
$sql = "INSERT INTO user_input (word, pos, trans, definition, sen)
VALUES ('$word', '$pos', '$trans', '$definition', '$sen')";
$conn->query($sql);
$conn->close();
?>
Here is where the problem is:
get_input.js
$(document).ready(function(){
$("#list").click(function(){
$.ajax({
type: 'GET',
url: 'get_input.php',
success: function(data) {
$("#mytable").text(data);
}
})
})
})
get_input.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "vocab";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM user_input";
$result = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
foreach($row as $field) {
echo htmlspecialchars($field);
}
}
$conn->close();
?>

Change html to :
<table class="table">
<tr>
<th>Word</th>
<th>Part of Speech</th>
<th>Translation</th>
<th>Definition</th>
<th>Sentence</th>
</tr>
<tr id="mytable">
</tr>
</table>
And PHP :
while ($row = mysqli_fetch_assoc($result)) {
echo '<td>'.htmlspecialchars($row[0]).'</td>';
echo '<td>'.htmlspecialchars($row[1]).'</td>';
echo '<td>'.htmlspecialchars($row[2]).'</td>';
echo '<td>'.htmlspecialchars($row[3]).'</td>';
}

Related

Filling boostrap cards with data from a mySQL database

I am trying to fill bootstrap cards with data from a database.
I am very close.
I have the mainphp file called project.php
A file with a function called component to fill them, called component.php.
And a connectDB.php file, that connect the DB and extracts the information from a table.
I am aware this is alot of code so I highlighted 2 areas the problem is definitely in...Apologies if too much, I can remove the function if necessary as it works..
here is an extract from project.php
<?php
require_once('connect/connectDB.php');
require_once('component.php');
?>
<!doctype html>
<html lang="en">
<head>
<title>The Wild Music Shop</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!--Font awesome-->
<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" />
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<!-- i have no idea why it won't link -->
<!-- <link type="text/css" rel="stylesheet" href="myCSS/somecss.css"> -->
<link rel="stylesheet" href="myCSS/somecss.css">
</head>
<body>
<!-- the cards -->
<div class = "container" id="thecards">
<div class = "row text-center py-5">
//Definite problem here
<?php
$result = getData();
while ($row = mysqli_fetch_assoc($result)){
component($row['InstName'], $row['Price'], $row['ProductImg'], $row['description']);
}
?>
</div>
</div>
</html>
This component definitely works as I tested it
<?php
function component($pInstName, $pPrice, $pProductImg, $pdescription){
$element = "
<div class=\"col-md-3 col-sm-6 my-3 my-md-0\">
<form action=\"index.php\" method=\"post\">
<div class=\"card shadow\">
<div>
<img src=\ $pProductImg\" alt=\"Image1\" class=\"img-fluid card-img-top\">
</div>
<div class=\"card-body\">
<h5 class=\"card-title\">Our $pInstName</h5>
<h6>
<i class=\"fas fa-star\"></i>
<i class=\"fas fa-star\"></i>
<i class=\"fas fa-star\"></i>
<i class=\"fas fa-star\"></i>
<i class=\"far fa-star\"></i>
</h6>
<p class=\"card-text\">
$pdescription
</p>
<h5>
<span class=\"price\">$$pPrice</span>
</h5>
<button type=\"submit\" class=\"btn btn-warning my-3\" name=\"add\">Add to Cart </button>
</div>
</div>
</form>
</div>
";
echo $element;
}
?>
and finally here is the connectDB.php
<?php
//Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$dbname = "g00398295";
$connection = mysqli_connect($dbhost,$dbuser,$dbpassword,$dbname);
//Test if connection occoured
if(mysqli_connect_errno()){
die("DB connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
if (!$connection)
{
die('Could not connect: ' . mysqli_error());
}
$sql = "select * from Instruments where itemno = 1; ";
$result = mysqli_query($connection,$sql);
$row=mysqli_fetch_assoc($result);
echo "Pls work".$row['InstName'];
mysqli_close($connection);
//get product from Database
//Definite problem here
function getData(){
$sql = "select * from $this->tablename";
$result = mysqli_query($this->con,$sql);
if(mysqli_num_rows($result) > 0){
return $result;
}
}
?>
I am awar the problem is somewhere in the connection step. I am very new to php in general and have been at this very long, I would appreciate help!
You have a function getData() that has "$this->table". Dont copy paste the codes without understanding what it does.
Clean up your connectDB.php:
<?php
//Create a database connection
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$dbname = "g00398295";
$connection = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
//Test if connection occoured
if(mysqli_connect_errno()){
die("DB connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
In project.php:
<div class = "row text-center py-5">
//Definite problem here
<?php
$sql = "select * from Instruments where itemno = 1; ";
$result = mysqli_query($connection,$sql);
while ($row = mysqli_fetch_assoc($result)){
component($row['InstName'], $row['Price'], $row['ProductImg'], $row['description']);
}
?>
</div>

php ajax, how to display dynamic values on dynamic select boxes

i am looking for a help
I have taken a code of adding muliple rows in bootstrap, in which i am trying to get values from select boxes, using php inside a javascript, using ajax it is getting value from a database, it works fine for the first row, but when it comes to the muliple rows, it just get value and again adds to first row, what i need is to get value on same row from where it was picked here is the code
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags-->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="au theme template">
<meta name="author" content="Hau Nguyen">
<meta name="keywords" content="au theme template">
<!-- Title Page-->
<title>Dashboard 3</title>
<!-- Fontfaces CSS-->
<link href="css/font-face.css" rel="stylesheet" media="all">
<link href="vendor/font-awesome-4.7/css/font-awesome.min.css" rel="stylesheet" media="all">
<link href="vendor/font-awesome-5/css/fontawesome-all.min.css" rel="stylesheet" media="all">
<link href="vendor/mdi-font/css/material-design-iconic-font.min.css" rel="stylesheet" media="all">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- Bootstrap CSS-->
<link href="vendor/bootstrap-4.1/bootstrap.min.css" rel="stylesheet" media="all">
<!-- Vendor CSS-->
<link href="vendor/animsition/animsition.min.css" rel="stylesheet" media="all">
<link href="vendor/bootstrap-progressbar/bootstrap-progressbar-3.3.4.min.css" rel="stylesheet" media="all">
<link href="vendor/wow/animate.css" rel="stylesheet" media="all">
<link href="vendor/css-hamburgers/hamburgers.min.css" rel="stylesheet" media="all">
<link href="vendor/slick/slick.css" rel="stylesheet" media="all">
<link href="vendor/select2/select2.min.css" rel="stylesheet" media="all">
<link href="vendor/perfect-scrollbar/perfect-scrollbar.css" rel="stylesheet" media="all">
<!-- Main CSS-->
<link href="css/theme.css" rel="stylesheet" media="all">
</head>
<?php
$connection = mysqli_connect('localhost','root','','quotation');
?>
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$mail = $_POST['mail'];
$phone = $_POST['phone'];
$name1 = count($_POST['name']);
$mail1 = count($_POST['mail']);
$phone1 = count($_POST['phone']);
print_r($name);
echo "<br>";
print_r($mail);
echo "<br>";
print_r($phone);
echo "<br>";
echo $name1;
echo $mail1;
echo $phone1;
}
?>
<br>
<div class="container">
<div class="row">
<div class="col col-sm6">
<a href="#">
<img src="images/icon/Omni_logo_for_web2.png" alt="CoolAdmin" />
<p style="color:gray;"><i>Transforming People and Business</i></p>
</a>
<p>
A-242, Sardar Ali Sabri Rd. <br>
Block-2, Gulshan-e-Iqbal <br>
Karachi. <br>
Phone: 021-3498OMNI(6664) Mobile: 0312-2169325, 0337-7222191
<br> SNTN : S0529023-6
<br>
TaxpayerName : OMNI ACADEMY
</p>
</div>
<div class="col col-sm6">
<h2 style="color:gray">Quotations</h2>
<p>
DATE 2018-12-17
<br>
RFQ# 0308-2018
<br>
Karachi. <br>
Phone: 021-3498OMNI(6664) Mobile: 0312-2169325, 0337-7222191
<br> SNTN : S0529023-6
Customer ID 408
<br>
Customer NTN/SNTN NA
<br>
<br>
Customer Lakson Group
<br>
Valid until: 28-Nov-2018
<br>
Prepared by: FIN-03
</p>
</div>
</div>
</div>
<br>
<form method="post">
<div class="container">
<table id="myTable" class=" table order-list">
<thead>
<tr>
<td>Name</td>
<td>Gmail</td>
<td>Phone</td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr>
</tr>
</tfoot>
</table>
</div>
<input type="submit" name = 'submit' value="Subm">
</form>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><select onchange = "myfunc(this.value)" name="name[]" class="form-control" ' + counter + '" ><?php $select_courses = "select * from courses";
$run_select = mysqli_query($connection,$select_courses);
while($row = mysqli_fetch_assoc($run_select)){
$name = $row["name"];
$course_id = $row["course_id"];
?><option value="<?php echo $course_id ?>"><?php echo $name; ?></option> <?php } ?></select></td>';
cols += '<td id="getdata" ' + counter + '"></td>';
cols += '<td><input type="text" class="form-control" name="phone[]' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="price"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
function myfunc(datavalue)
{
$.ajax({
url:'getdata.php',
type:'post',
data:{
datapost:datavalue
},
success:function(result){
$('#getdata').html(result);
}
});
}
</script>
<?php include('include/footer.php'); ?>
<!-- end document-->
getdata.php
<?php
$connection = mysqli_connect('localhost','root','','quotation');
?>
<?php
$name_id = $_POST['datapost'];
$q = "select * from courses where course_id = '$name_id'";
$result = mysqli_query($connection,$q);
$rows = mysqli_fetch_assoc($result);
?>
<input type="text" name = "phone[]" value="<?php echo $rows['name']; ?>">
You can do as follows:
Set unique id to your select and getdata.
<select id="select'+counter+'">
<td id="getdata'+counter+'"></td>
You can call change function of select separately or pass id to myfunc and parse it from there.
$(document).on('change', 'select[name="name[]"]', function(){
idName = $(this).attr('id'); //finding id of the element
id = idName.substring(6, idName.length); //finding id number
var datavalue = $(this).val();
myfunc(datavalue, id);
});
Change your myfunc as follows.
function myfunc(datavalue, id) {
$.ajax({
url:'getdata.php',
type:'post',
data:{
datapost:datavalue
},
success:function(result){
$('#getdata'+id).html(result);
}
});
}
And also you need to be careful on maintaining unique ids when deleting rows. You can check here how to dynamically add and remove rows.

Displaying value from Mysql db to Html5 bootstrap using PHP/Jquery

Here's my codes
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Control Panel</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link href="css/font-awesome.min.css" rel="stylesheet">
<!-- NProgress -->
<link href="css/nprogress.css" rel="stylesheet">
<!-- iCheck -->
<link href="css/green.css" rel="stylesheet">
<!-- Datatables -->
<link href="css/dataTables.bootstrap.min.css" rel="stylesheet">
<link href="css/buttons.bootstrap.min.css" rel="stylesheet">
<link href="css/fixedHeader.bootstrap.min.css" rel="stylesheet">
<link href="css/responsive.bootstrap.min.css" rel="stylesheet">
<link href="css/scroller.bootstrap.min.css" rel="stylesheet">
<!-- Custom Theme Style -->
<link href="css/custom.min.css" rel="stylesheet">
</head>
<body class="nav-md">
<div class="container body">
<div class="main_container">
<div class="col-md-12 left_col">
<div class="left_col scroll-view">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_content">
<table id="datatable-buttons" class="table table-striped table-bordered">
<thead>
<tr>
<th>S/N</th>
<th>Date</th>
<th>IP Address</th>
<th>Activation</th>
</tr>
</thead>
<tbody>
<tr>
<td>get data from db</td>
<td>get data from db</td>
<td>get data from db</td>
<td>get data from db</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="js/bootstrap.min.js"></script>
<!-- FastClick -->
<script src="js/fastclick.js"></script>
<!-- NProgress -->
<script src="js/nprogress.js"></script>
<!-- iCheck -->
<script src="js/icheck.min.js"></script>
<!-- Datatables -->
<script src="js/jquery.dataTables.min.js"></script>
<script src="js/dataTables.bootstrap.min.js"></script>
<script src="js/dataTables.buttons.min.js"></script>
<script src="js/buttons.bootstrap.min.js"></script>
<script src="js/buttons.flash.min.js"></script>
<script src="js/buttons.html5.min.js"></script>
<script src="js/buttons.print.min.js"></script>
<script src="js/dataTables.fixedHeader.min.js"></script>
<script src="js/dataTables.keyTable.min.js"></script>
<script src="js/dataTables.responsive.min.js"></script>
<script src="js/responsive.bootstrap.js"></script>
<script src="js/dataTables.scroller.min.js"></script>
<script src="js/jszip.min.js"></script>
<script src="js/pdfmake.min.js"></script>
<script src="js/vfs_fonts.js"></script>
<!-- Custom Theme Scripts -->
<script src="js/custom.min.js"></script>
</body>
</html>
PHP
<?php
$servername = "remotedbIP";
$username = "root";
$password = "Password";
$dbname = "installation";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, date, ip, activate FROM software";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - date: " . $row["date"]. " - ip: " . $row["ip"]. " - activate: " . $row["activate"]. " <br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I am trying to display the data retrieved by the php file using the html table format with bootstrap. I am not sure how to do that. I tried to follow a few guidelines but I couldn't figure out. Any direction towards the right guideline or help would be really appreciated.
Also I am trying to hide the ID from the mysql db and instead show a locally displayed serial number, is it possible to achieve that, if yes how?
Thank you so much.
Step 1 .Put your database connection codes in database_connection.php
$servername = "remotedbIP";
$username = "root";
$password = "Password";
$dbname = "installation";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Step 2. Than include the connection in header of index page
include("database_connection.php");
Step 3. add these php code inside table tbody And remove the previous codes
<?php
$sql = "SELECT id, date, ip, activate FROM software";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td> $row['id'] </td>";
echo "<td> $row['date'] </td>";
echo "<td> $row['ip'] </td>";
echo "<td> $row['activate'] </td>";
echo "</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>

Issue with foreach loop updating every record, rather than the ones just selected in a checkbox

I have a page with a dropdown box at the top populated from the database, when I select an item from the dropdown it gives a list of results with a checkbox at the end of each line, I want to be able to select, using each checkbox, any number of results, and submit a value back into a field in the database for each result selected.
I sort of have this working, but it submits the value to every field in the database, rather than just the ones selected
<?php
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="favicon.ico">
<title>Stock Items</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- bootstrap theme -->
<link href="css/bootstrap-theme.css" rel="stylesheet">
<!--external css-->
<!-- font icon -->
<link href="css/elegant-icons-style.css" rel="stylesheet" />
<link href="css/font-awesome.min.css" rel="stylesheet" />
<!-- full calendar css-->
<link href="assets/fullcalendar/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet" />
<link href="assets/fullcalendar/fullcalendar/fullcalendar.css" rel="stylesheet" />
<!-- easy pie chart-->
<link href="assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen"/>
<!-- owl carousel -->
<link rel="stylesheet" href="css/owl.carousel.css" type="text/css">
<link href="css/jquery-jvectormap-1.2.2.css" rel="stylesheet">
<!-- Custom styles -->
<link rel="stylesheet" href="css/fullcalendar.css">
<link href="css/widgets.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/style-responsive.css" rel="stylesheet" />
<link href="css/xcharts.min.css" rel=" stylesheet">
<link href="css/jquery-ui-1.10.4.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<script src="js/lte-ie7.js"></script>
<![endif]-->
</head>
<body>
<!-- container section start -->
<section id="container" class="">
<?php include("navigation.php"); ?>
<!--main content start-->
<section id="main-content">
<section class="wrapper">
<!--overview start-->
<div class="row">
<div class="col-lg-12">
<h3 class="page-header"><i class="fa fa-lightbulb-o"> </i>Stock</h3>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i>Home</li>
<li><i class="fa fa-lightbulb-o"></i>Stock</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<section class="panel">
<header class="panel-heading">
All Stock
</header>
<div class="panel-body">
<form class="form-horizontal" method="post" action="">
<div class="form-group">
<div class="col-lg-8">
<select name="search" class="form-control" required >
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `description` FROM `stock_templates`";
$stock_templates = mysql_query($query);
echo "<option value=''>Select Stock Template</option>";
while ($description=mysql_fetch_assoc($stock_templates)) {
echo "<option value='" . $description['id'] . "'>" . $description['description'] . "</option>";
}
?>
</select>
</div>
<div class="col-lg-1">
<input type="submit" name="filter" value="Search" class="btn btn-success" />
</div>
</div>
</form><br><br>
<?php
if(isset($_POST['formSubmit']))
{
$aDoor = $_POST['check_list'];
if(empty($aDoor))
{
echo("<p>You didn't select any items to add to lease.</p>\n");
}
else
{
$N = count($aDoor);
echo("<p>You selected $N item(s) to add to lease: ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
echo("</p>");
}
}
function IsChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
?>
<?php
ob_start( );
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
$query = mysql_query("UPDATE stock SET lease_id = $lease_id");
$result2 = mysql_query($query);
// check if sent
if ($result2) {
?>
<div class="alert alert-success fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Well done!</strong> Your lease items have been successfully saved.
</div>
<?php
} else {
?>
<div class="alert alert-block alert-danger fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>Oh snap!</strong> We could not save your lease items.
</div>
<?php
}
}
}
?>
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
// Extract filter information
$count = 0;
$search = mysql_escape_string(#$_POST['search']);
// select data from the database
$query2 = "SELECT * FROM `stock_templates` ORDER BY `stock_templates`.`id` DESC LIMIT 0";
// Perform Logic
if (array_key_exists("filter", $_POST)) {
// query based on search term
$query2 = "SELECT * FROM `stock` WHERE $search=stocktemplate_id AND lease_id=0";
}
$result2 = mysql_query($query2);
// Result
if (mysql_num_rows($result2) < 1) {
echo "<div align='center'><h2>Please select a stock template above and click search</h2></div>";
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" class="form-horizontal" name="check_list[]">
<div class="form-group">
<label class="control-label col-lg-1" for="lease_id">Lease Number *</label>
<div class="col-lg-10">
<select name="lease_id" class="form-control">
<?php
// connect to the database
require_once('models/db-settings.php');
$conn = mysql_connect($db_host, $db_user, $db_pass, $db_name) or die("Error " .mysql_error($conn));
mysql_select_db($db_name);
$query = "SELECT `id`, `leasenumber` FROM `lease`";
$leases = mysql_query($query);
echo "<option value=''>Select Lease..........</option>";
while ($lease=mysql_fetch_assoc($leases)) {
echo "<option value='" . $lease['id'] . "'>" . $lease['leasenumber'] . "</option>";
}
?>
</select>
</div>
</div>
<table class="table table-hover">
<thead>
<tr>
<th>Item ID</th>
<th>Description</th>
<th>Barcode</th>
<th>Serial</th>
<th>Add To Lease</th>
</tr>
</thead>
<?php
while ($row = mysql_fetch_array($result2))
{
$id = $row["id"];
$lease_id = $row["lease_id"];
$barcode = $row["barcode"];
$serial = $row["serial"];
$stocktemplate_id = $row["stocktemplate_id"];
$qa = 0;
?>
<tbody>
<tr>
<td><?php print $id ?></td>
<td><?php $q = mysql_query("SELECT description FROM stock_templates WHERE id = '$stocktemplate_id'"); while ($row = mysql_fetch_array($q)){$qa = $row["description"];} print $qa ?></td>
<td><?php print $barcode ?></td>
<td><?php print $serial ?></td>
<td><input type="checkbox" name="check_list[]" value="<?php print $id ?>" /></td>
<td></td>
</td>
</tr>
</tbody>
<?php
}
?>
</table>
<input class="btn btn-danger" type="submit" name="formSubmit" value="Add Selected To Lease" />
</div>
</form>
</section>
</div>
</div>
</section>
</section>
<!--main content end-->
</section>
<!-- container section end -->
<!-- javascripts -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- nice scroll -->
<script src="js/jquery.scrollTo.min.js"></script>
<script src="js/jquery.nicescroll.js" type="text/javascript"></script>
<!-- jquery ui -->
<script src="js/jquery-ui-1.9.2.custom.min.js"></script>
<!--custom checkbox & radio-->
<script type="text/javascript" src="js/ga.js"></script>
<!--custom switch-->
<script src="js/bootstrap-switch.js"></script>
<!--custom tagsinput-->
<script src="js/jquery.tagsinput.js"></script>
<!-- colorpicker -->
<!-- bootstrap-wysiwyg -->
<script src="js/jquery.hotkeys.js"></script>
<script src="js/bootstrap-wysiwyg.js"></script>
<script src="js/bootstrap-wysiwyg-custom.js"></script>
<!-- ck editor -->
<script type="text/javascript" src="assets/ckeditor/ckeditor.js"> </script>
<!-- custom form component script for this page-->
<script src="js/form-component.js"></script>
<!-- custome script for all page -->
<script src="js/scripts.js"></script>
</body>
</html>
No worries. Just put the code of insert query inside foreach() loop. Like this:
foreach($_POST['check_list'] as $item)
{
$sql="INSERT/UPDATE Query";
//for example
$sql = "INSERT INTO table_demo (field_1, TARGET_FIELD, field_2, field_3) VALUES (val_1, $item, val_2, val_3)";
$insert = mysqli_query($connection,$sql);
}
//next code of your choice
That is really Easy to give a go.
See this is same as you want.
In this link the first answer by Sean Valsh is your solution.
Giving the array as name of every checkbox will give you only chacked option's id in array while submitted.
https://stackoverflow.com/a/4997271/6834980
Ask if still have the problem. Happy to help.

How to add 3 attempts in a login page

hello everyone i just wanna ask on how to add three attempts in my login page here is the code
<?php
include 'connect.php';
?>
<?php
if(isset($_POST) && !empty($_POST))
{
session_start();
include("config_DB.php"); //including config.php in our file
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = mysql_real_escape_string(stripslashes(md5($_POST['password'])));
$user_type= $_GET['user_type'];
$match = "select * from $table where username = '".$username."' and password = '".sha1($password)."';";
$qry = mysql_query($match);
$row=mysql_fetch_array($qry);
$num_rows = mysql_num_rows($qry);
if($num_rows >= 1){
$_SESSION['user']= $_POST["username"];
$_SESSION['name'] = $row['empName'];
$_SESSION['position'] = $row['empPosition'];
$_SESSION['user_type'] = $row['user_type'];
header("location:index.php/index_controller/home");
} else {
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = mysql_real_escape_string(stripslashes($_POST['password']));
include("config_DB.php"); //including config.php in our file
$match = "select * from $table where username = '".$username."' and password = '".sha1($password)."';";
$qry = mysql_query($match);
$row=mysql_fetch_array($qry);
$num_rows = mysql_num_rows($qry);
$attemps =0;
if($num_rows <= 0){
echo
"<script type=\"text/javascript\">".
"window.alert('Invalid username/password!');".
'window.location.href="index.php";'.
"</script>";
exit;
}
$_SESSION['user']= $_POST["username"];
$_SESSION['name'] = $row['empName'];
$_SESSION['position'] = $row['empPosition'];
$_SESSION['user_type'] = $row['user_type'];
header("location:index.php/index_controller/home");
}
}else{
?>
<!DOCTYPE HTML>
<html lang="en-US">
<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>City Planning and Development Office--Login</title>
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/bootstrap.min.css"/>
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/login-style.css"/>
<link rel="stylesheet/less" href="<?php echo base_url();?>assets/less/icons.less"/>
<!-- Load JavaScript Libraries -->
<script src="<?php echo base_url();?>assets/js/jquery/jquery-1.11.1.min.js"></script>
<script src="<?php echo base_url();?>assets/js/jquery/jquery-ui.js"></script>
<script src="<?php echo base_url();?>assets/js/jquery/jquery.widget.min.js"></script>
<!-- Load Metro JavaScript -->
<script src="<?php echo base_url();?>assets/js/load-metro.js"></script>
<script src="<?php echo base_url();?>assets/js/metro.min.js"></script>
<script src="<?php echo base_url();?>assets/js/metro-calendar.js"></script>
<script src="<?php echo base_url();?>assets/js/metro-datepicker.js"></script>
<!-- Load Bootstrap JavaScript -->
<script src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script>
<script src="<?php echo base_url();?>assets/js/validate.js"></script>
<script src="<?php echo base_url();?>assets/js/condition.js"></script>
<!-- Login parallax -->
<style type="text/css">
body{
background:#000;
}
input.info{
color:#000 !important;
}
.vertical-offset-100{
padding-top:100px;
}
.login{
background:#ed1c24;
color:#fff;
}
body{
background: url(img/back.png);
background-color: #444;
background: url(/cpdo_ci/assets/images/pinlayer2.png),url(/cpdo_ci/assets/images/pinlayer1.png),url(/cpdo_ci/assets/images/back.png);
}
.vertical-offset-100{
padding-top:100px;
}
</style>
</head>
<body>
<script src="<?php echo base_url();?>assets/js/TweenLite.min.js"></script>
<div class="container" >
<div class="row vertical-offset-100">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row-fluid user-row">
<center><img src="/cpdo_ci/assets/images/malolos.png" height="200" width="200" alt="CPDO"></center>
</div>
</div>
<div class="panel-body">
<form accept-charset="UTF-8" id="login" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" name="login" class="form-signin" role="form">
<fieldset>
<div class="form-group">
<input class="form-control info" placeholder="Username" name="username" id="username" required type="text">
</div>
<div class="form-group">
<input class="form-control info" placeholder="Password" name="password" id="password" required type="password" value="">
</div>
<label>
<div style=" font-size:90%" >
</div>
</label>
<input class="btn btn-lg btn-success btn-block" type="submit" value="Login">
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(document).mousemove(function(e){
TweenLite.to($('body'),
.5,
{ css:
{
backgroundPosition: ""+ parseInt(event.pageX/8) + "px "+parseInt(event.pageY/'12')+"px, "+parseInt(event.pageX/'15')+"px "+parseInt(event.pageY/'15')+"px, "+parseInt(event.pageX/'30')+"px "+parseInt(event.pageY/'30')+"px"
}
});
});
});
</script>
</body>
<?php
}
?>
</html>
</html>
Try this to the back-end which receives the login parameters.
if($_POST["password"]) !== $password_stored_in_db) {
if($attempts == 3) {
header('Location: login.php?max_attempt=exceeded');
}
} else if (isset($attempts)) {
$attempts = ++ $attempts;
} else {
$attempts = 0;
}
header('Location: login.php?attempt=' . $attempts);
Also add this to login.php to determine if user has exceeded max attempts:
Make sure that login.php is set to check for max_attempt=exceeded by adding:
if(isset($_GET["max_attempt"])) {
if($_GET["max_attempt"] == "exceeded") {
// Error message
// Use $_SESSION to record the time and to stop user from trying again for a while because if you use cookies, it maybe overridden or re-set.
}
}
You really should store the information of attempts on the DB, but some quick hack by storing the data on the session would be
<?php
include 'connect.php';
if(isset($_POST) && !empty($_POST))
{
session_start();
include("config_DB.php"); //including config.php in our file
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = mysql_real_escape_string(stripslashes(md5($_POST['password'])));
$user_type= $_GET['user_type'];
$match = "select * from $table where username = '".$username."' and password = '".sha1($password)."';";
$qry = mysql_query($match);
$row=mysql_fetch_array($qry);
$num_rows = mysql_num_rows($qry);
if($num_rows >= 1){
$_SESSION['attemps'] = 0;
$_SESSION['user']= $_POST["username"];
$_SESSION['name'] = $row['empName'];
$_SESSION['position'] = $row['empPosition'];
$_SESSION['user_type'] = $row['user_type'];
header("your_home_page");
} else {
$_SESSION['attemps'] ||= 0;
$_SESSION['attemps'] += 1;
if ($_SESSION['attemps'] > 3) {
header("location:/access_denied.php");
}
$display_warning = true;
}
}else{
?>
<!DOCTYPE HTML>
<html lang="en-US">
<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>City Planning and Development Office--Login</title>
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/bootstrap.min.css"/>
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/login-style.css"/>
<link rel="stylesheet/less" href="<?php echo base_url();?>assets/less/icons.less"/>
<!-- Load JavaScript Libraries -->
<script src="<?php echo base_url();?>assets/js/jquery/jquery-1.11.1.min.js"></script>
<script src="<?php echo base_url();?>assets/js/jquery/jquery-ui.js"></script>
<script src="<?php echo base_url();?>assets/js/jquery/jquery.widget.min.js"></script>
<!-- Load Metro JavaScript -->
<script src="<?php echo base_url();?>assets/js/load-metro.js"></script>
<script src="<?php echo base_url();?>assets/js/metro.min.js"></script>
<script src="<?php echo base_url();?>assets/js/metro-calendar.js"></script>
<script src="<?php echo base_url();?>assets/js/metro-datepicker.js"></script>
<!-- Load Bootstrap JavaScript -->
<script src="<?php echo base_url();?>assets/js/bootstrap.min.js"></script>
<script src="<?php echo base_url();?>assets/js/validate.js"></script>
<script src="<?php echo base_url();?>assets/js/condition.js"></script>
<!-- Login parallax -->
<style type="text/css">
body{
background:#000;
}
input.info{
color:#000 !important;
}
.vertical-offset-100{
padding-top:100px;
}
.login{
background:#ed1c24;
color:#fff;
}
body{
background: url(img/back.png);
background-color: #444;
background: url(/cpdo_ci/assets/images/pinlayer2.png),url(/cpdo_ci/assets/images/pinlayer1.png),url(/cpdo_ci/assets/images/back.png);
}
.vertical-offset-100{
padding-top:100px;
}
</style>
</head>
<body>
<script src="<?php echo base_url();?>assets/js/TweenLite.min.js"></script>
<div class="container" >
<div class="row vertical-offset-100">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<div class="row-fluid user-row">
<center><img src="/cpdo_ci/assets/images/malolos.png" height="200" width="200" alt="CPDO"></center>
</div>
</div>
<div class="panel-body">
<form accept-charset="UTF-8" id="login" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" name="login" class="form-signin" role="form">
<fieldset>
<div class="form-group">
<input class="form-control info" placeholder="Username" name="username" id="username" required type="text">
</div>
<div class="form-group">
<input class="form-control info" placeholder="Password" name="password" id="password" required type="password" value="">
</div>
<label>
<div style=" font-size:90%" >
</div>
</label>
<input class="btn btn-lg btn-success btn-block" type="submit" value="Login">
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
<?php if defined($display_warning) : ?>
window.alert('Invalid username/password!');
<?php endif; ?>
$(document).mousemove(function(e){
TweenLite.to($('body'),
.5,
{ css:
{
backgroundPosition: ""+ parseInt(event.pageX/8) + "px "+parseInt(event.pageY/'12')+"px, "+parseInt(event.pageX/'15')+"px "+parseInt(event.pageY/'15')+"px, "+parseInt(event.pageX/'30')+"px "+parseInt(event.pageY/'30')+"px"
}
});
});
});
</script>
</body>
</html>
</html>

Categories