I'm trying to build a comment system
this is my code
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<style>
.back_glob{width: 350px}
</style>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(function(){
$( ".tombol_login" ).click(function() {
var txt = $("[name=comment]").val();
$("#comment").submit();
})});
</script>
<style>
.back_glob{width: 450px}
</style>
</head>
<body>
<div class = "back_glob">
<div class="tableC">
<img src="img\back.png" alt="back" height="42" width="42">
<div class ="back_header">
<h4>comment</h4>
</div>
<div class= "table">
<form id="comment" name="comment" action="contet2.php" method="post">
<div class="row">
<div class="col">comment</div>
<div class="col">:</div>
<div class="col"><textarea name="comment" rows ="10" cols="40"></textarea></div>
</div>
<div class="tom">
<button type="button" class="tombol_login">Submit</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
$servername = "localhost";
$dbname = "databaseform";
$username = "root";
$password = "";
session_start();
$page = 2;
$conn = new PDO("mysql:host =$servername ; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT form.Username, comment.Comment, comment.time FROM
form, comment WHERE
form.pkey=comment.pkey AND
comment.page=$page
ORDER BY comment.time DESC";
$result = $conn->query($query);
$hasil = $result->fetchAll();
$Comment = $_POST['comment'];
try
{
// injec
$query = "INSERT INTO comment (pkey,Comment,time,page)
VALUES (:Username,:Comment,NOW(),:page)";
$sql = $conn->prepare($query) ;
$sql->BindValue(':Username',reset($_SESSION['txt_login']));
$sql->BindValue(':Comment',$Comment);
$sql->BindValue(':page',$page);
$sql->execute();
$query = "SELECT form.Username, comment.Comment, comment.time FROM
form, comment WHERE
form.pkey=comment.pkey AND
comment.page=$page
ORDER BY comment.time DESC";
$result = $conn->query($query);
$hasil = $result->fetchAll();
echo '<div class="back_glob">';
echo '<div class = "table">';
echo '<div class = "tableC">';
echo '</div>';
}
catch(PDOException $e)
{
echo $query . "<br>" . $e->getMessage();
}
for($i = 0 ; $i < count($hasil);$i++)
{
echo'<div class="row">';
echo '<div class="col2">'.$result[$i]['Username'].'</div>';
echo '<div class="col2">'.$result[$i]['Comment'].'</div>';
echo '<div class="col2">'.$result[$i]['time'].'</div>';
echo'</div>';
}
?>
but the php part won't recognize the $_POST['comment'] before the submit button , i can't show the previous comment unless I click the submit button.
Is there any solution to correct this ??
I am really confused about your way of asking a question. I think you should have to read this tutorial of Smashing Magazine. So you can better understand of code and comment system.
I hope it will help you.
Related
This is my second question on php. I'm trying to query mysql database and show it on my page.
Currently, I'm doing it on php page and the code is as below.
<?php
$host = "localhost";
$dbUserName = "myUserId";
$dbPassword = "MyPwd";
$dbname = "MyDBName";
try
{
$conn = new mysqli($host, $dbUserName, $dbPassword, $dbname);
}
catch(Exception $ex)
{
echo 'Error : ' . $ex->getMessage();
}
$SELECT = "SELECT * FROM OpenPositions";
$result = mysqli_query($conn, $SELECT);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="wrap">
<div class="welcome-two">
<div class="container">
<div class="welcome-detail">
<div class="row">
<div class="col">
<h2>Open <b>one</b></h2>
<div class="tabs">
<?php
while ($row = mysqli_fetch_assoc($result))
{ ?>
<div class="tab">
<input type="radio" id="rd<?php echo $row['JobId']; ?>" name="rd">
<label class="tab-label" for="rd<?php echo $row['JobId']; ?>"><?php echo $row['Title']; ?></label>
<div class="tab-content">
<?php echo $row['JobDescription']; ?><br/>
<p><button id="myBtn">Open Modal</button>
</p>
</div>
</div>
<?php
} ?>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var accItem = document.getElementsByClassName('accordionItem');
var accHD = document.getElementsByClassName('accordionItemHeading');
for (i = 0; i < accHD.length; i++) {
accHD[i].addEventListener('click', toggleItem, false);
}
function toggleItem() {
var itemClass = this.parentNode.className;
for (i = 0; i < accItem.length; i++) {
accItem[i].className = 'accordionItem close';
}
if (itemClass == 'accordionItem close') {
this.parentNode.className = 'accordionItem open';
}
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
Using this, I'm able to retrieve my data and display it. But, This is working when I save it as php.
Here I've 2 questions.
How can I separate the code and have HTML displaying data and php doing db related tasks?
When I click on the button, how can I pass the id and show it in the modal?
Thanks
You can't really separate all of the php and HTML thing. But you can do something like this:
first create 2 file:
db_connection_function.php
index.php // Yeah, you can't escape from .php file extension.
relocate your database connection and query to file db_connection_function.php
<?php
$host = "localhost";
$dbUserName = "myUserId";
$dbPassword = "MyPwd";
$dbname = "MyDBName";
try
{
$conn = new mysqli($host, $dbUserName, $dbPassword, $dbname);
}
catch(Exception $ex)
{
echo 'Error : ' . $ex->getMessage();
}
$SELECT = "SELECT * FROM OpenPositions";
$result = mysqli_query($conn, $SELECT);
?>
And this content of file index.php
<?php include 'db_connection_function.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="wrap">
<div class="welcome-two">
<div class="container">
<div class="welcome-detail">
<div class="row">
<div class="col">
<h2>Open <b>one</b></h2>
<div class="tabs">
<?php
while ($row = mysqli_fetch_assoc($result))
{ ?>
<div class="tab">
<input type="radio" id="rd<?php echo $row['JobId']; ?>" name="rd">
<label class="tab-label" for="rd<?php echo $row['JobId']; ?>"><?php echo $row['Title']; ?></label>
<div class="tab-content">
<?php echo $row['JobDescription']; ?><br/>
<p><button id="myBtn">Open Modal</button>
</p>
</div>
</div>
<?php
} ?>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
var accItem = document.getElementsByClassName('accordionItem');
var accHD = document.getElementsByClassName('accordionItemHeading');
for (i = 0; i < accHD.length; i++) {
accHD[i].addEventListener('click', toggleItem, false);
}
function toggleItem() {
var itemClass = this.parentNode.className;
for (i = 0; i < accItem.length; i++) {
accItem[i].className = 'accordionItem close';
}
if (itemClass == 'accordionItem close') {
this.parentNode.className = 'accordionItem open';
}
}
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
About how to pass id to your modal is like this:
first, put your data 'id' in the attribute of modal button
...
<p><button class="myBtn" data-id="<?php echo $row['JobId']; ?>" data-toggle="modal" data-target="#myModal">Open Modal</button>
...
must change "myBtn" to class, because id can't be used to many data.
And this is for your modal
$(".myBtn").click(function(){
JobId = $(this).data('id')
// put the id into modal
$('div#myModal div.modal-content p').html(JobId)
})
I am currently trying to build a "ToDo-App" which lets me INSERT text into a database, which will then be displayed. There is a "feature" to delete content based on their ID.
If I input two tasks into my application, I get two table records with ID 1 and 2. When I delete record 1, the record with ID 2 still exists. Thus, the record with ID 2 is listed as the first item in the to-do list.
I have to enter "2" in the "delete input field" to delete the first item from the list! How can I get this to be in sync? Is the ID field appropriate for maintaining the logical / application level order of the tasks?
<!doctype HTML>
<html>
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
</head>
<?php
$con = mysqli_connect("","root","","todo");
$sql = "SELECT text FROM work";
$res = mysqli_query($con, $sql);
if(isset($_POST["text"]))
{
$eingabe = $_POST["text"];
$query = "INSERT INTO work(text) VALUES('$eingabe')";
mysqli_query($con, $query);
header("Refresh:0");
}
else
{
echo "";
}
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
else
{
echo "";
}
?>
<body>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<form action="index.php" method="post">
<input class="lil-input" name="text" type="text">
<input type="submit" class="lil-button-green" value="Hinzufügen">
</form>
<ol id="liste" class="lil-list">
<?php
while($dsatz = mysqli_fetch_assoc($res))
{
echo "<li>" .$dsatz["text"] ."</li>";
}
?>
</ol>
<form id="form" action="index.php" method="post">
<input class="lil-input" name="del" type="text">
<input type="submit" class="lil-button-red lil-button-small" value=" Löschen ">
</form>
</div>
</div>
</div>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
var anzahl = $("#liste li").length;
if(anzahl < 1)
{
$("#form").hide();
}
else
{
$("form").show();
}
</script>
</body>
</html>
The pictures:
HTML Output
MySQL Dashboard
As discussed in the comment, you can have multiple checkboxes forming an array parameter: <input name="theName[1]"> with explicit key and name="theName[]" with implicit keys.
Further more, you should use prepared statements to prevent SQL injection attacks. Imagine an attacker sends a request with a single quote ' in the field, i.e. he terminates the SQL string delimiter, and adds arbitrary SQL code. Prepared statements use placeholders and the parameters are sent separately.
You should also handle errors. In the code below errors are output as HTML, however, you should define your own logger function rather than just echo into the stream. This can output HTML on development servers but log to disk on production servers.
This is a working example tested on PHP7.3 with MariaDB 10:
<!DOCTYPE HTML>
<html lang="de">
<head>
<meta charset="utf-8">
<title>ToDo-APP</title>
<link rel="stylesheet" href="css/Lil-Helper.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/webfonts/all.css">
<link rel="stylesheet" href="css/own.css">
<style>
#frm-tasks button
{
padding: 0 18px;
}
</style>
</head>
<body>
<?php
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$con = new mysqli('localhost', 'testuser', 'testpasswd', 'testdb');
$action = $_POST['action'] ?? 'list';
if(!empty($_POST["text"]))
{
$eingabe = $_POST["text"];
try
{
$stmt = $con->prepare('INSERT INTO work(text) VALUES(?)');
$stmt->bind_param('s', $_POST["text"]);
$stmt->execute();
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
if('del' === $action && isset($_POST['rows']) && is_array($_POST['rows']))
{
try{
$stmt = $con->prepare('DELETE FROM `work` WHERE `work`.`id` = ?');
$stmt->bind_param('i', $row);
foreach ($_POST['rows'] as $row)
{
$stmt->execute();
if($e = $stmt->error)
echo "<div>DB Error: $e</div>";
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $msg;</div>";
}
}
?>
<header class="lil-menu lil-flex lil-flex-center align-center">
<a href="index.html" class="lil-brand">
<h3>To-Do</h3>
</a>
<a class="lil-menu-item currentLink" href="index.html">ToDo</a>
<a class="lil-menu-item" href="#archive">Archiv</a>
<a class="lil-menu-item" href="#Sprachen">Sprachen</a>
</header>
<div class="main">
<div class="lil-box">
<h3 class="lil-font-rot lil-big-font lil-space lil-font-style" style="font-size: 4rem;">ToDo</h3>
<div class="lil-box">
<!--form action="index.php" method="post"-->
<form id="frm-tasks" action="" method="post">
<input class="lil-input" name="text" type="text">
<button type="submit" class="lil-button-green" name="action" value="add">Hinzufügen</button>
<?php
try
{
$res = $con->query('SELECT id, text FROM work');
if(0 < $res->num_rows)
{
?>
<table>
<thead>
<tr>
<th></th><th>ID</th> <th>Aufgabe</th>
</tr>
</thead>
<tbody>
<?php
while($dsatz = mysqli_fetch_object($res))
{
?>
<tr>
<td><input type="checkbox" name="rows[]" value="<?php echo $dsatz->id;?>"></td><td><?php echo $dsatz->id;?></td> <td><?php echo $dsatz->text;?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<button type="submit" class="lil-button-red lil-button-small" name="action" value="del">Löschen</button>
<?php
}
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error processing statement: $e->msg;</div>";
}
?>
</form>
</div>
</div>
</div>
<!-- not needed atm script src="js/jquery-3.3.1.min.js"></script-->
<h2>POST</h2>
<?php
var_dump($_POST);
}
catch (mysqli_sql_exception $e)
{
$msg = $e->getMessage();
echo "<div>Error connecting DB: $msg;</div>";
}
?>
</body>
</html>
The key of the list is the 'th' in the database so just fixing limits
Replace
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` WHERE `work`.`id` = $del";
mysqli_query($con, $sql2);
header("Refresh:0");
}
With
if(isset($_POST["del"]))
{
$del = $_POST["del"];
$res = mysqli_query($con, $sql);
$sql2 = "DELETE FROM `work` LIMIT 1 OFFSET ".array_search($del, mysqli_fetch_assoc($res));
mysqli_query($con, $sql2);
header("Refresh:0");
}
I have an backend website setup that displays all the users on my site in an organised table, I should be able to edit and delete the users from the php page. However I cannot get the delete function to work, here is the code.
Data_Display.php
<?php
include('session.php');
?>
<?php include ("db.php"); ?>
<?php
$sql = "SELECT * FROM username ORDER BY UserNameID DESC";
$query = mysql_query($sql) or die(mysql_error());
if (isset($_GET['UserNameID'])) {
$id = mysql_real_escape_string($_GET['UserNameID']);
$sql_delete = "DELETE FROM users WHERE id = '{$UserNameID}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/ico" href="favicon.ico">
<title>Network TV - All Records</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body >
<div class="container">
<div class="content">
<h1>Network TV Users and User control panel</h1>
<br>
<div class="toolbar">
Add New Person
Home
</div>
<br>
</div>
</div>
<div class="container">
<div class="content">
<?php if (mysql_num_rows($query)) { ?>
<?php while ($rows = mysql_fetch_assoc($query)) { ?>
<div class="separator"></div>
<h2><b>User reference:</b> <?php echo $rows['UserNameID']; ?></h2>
<h2><b>Name:</b><?php echo $rows['name']; ?></h2>
<h2><b>Email address:</b> <?php echo $rows['email']; ?></h2>
<h2><b>Gender:</b> <?php echo $rows['sex']; ?></h2>
<h2><b>Profile Picture:</b> <?php echo $rows['imagelink']; ?></h2>
<div class="toolbar">
Edit
Delete
</div>
<?php } /* End Loop */ ?>
<div class="separator"></div>
<?php } else { ?>
<div class="separator"></div>
<h2>There are no records to display</h2>
<div class="separator"></div>
<?php } /* End Rows Checking */?>
</div>
</div>
<div class="container">
<br>
<br>
<br>
<br>
<br>
</div>
<script>
function confirmDelete ( message, url )
{
var confirmation = confirm ( message );
if ( confirmation == true ) {
window.location = url;
} else {
return false;
}
}
</script>
</body>
</html>
Session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "Oliver");
// Selecting Database
$db = mysql_select_db("users", $connection);
if(!isset($_SESSION)){session_start();}
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from username where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: home.php'); // Redirecting To Home Page
}
?>
db.php
<?php
$connection = mysql_connect('localhost', 'root', 'Oliver');
mysql_select_db('users', $connection) or die(mysql_error());
?>
Information
When I click the delete button in data_display.php, I do receive the javascript alert to confirm that I do want to delete the user from the database, but nothing actually happens.
if (isset($_GET['recordId'])) {
$id = mysql_real_escape_string($_GET['recordId']);
$sql_delete = "DELETE FROM users WHERE id = '{$id}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
You are sending recordId as parameter.
I tried to make a search engine in order to search between 2 dates $dateFrom to $dateTo.
Here what i have tried.:
Index.php:
<?php
require_once 'Connection.simple.php';
$tutorialTitle = "Using Ajax to search a Record with PHP, MySQL and jQuery (Look and Feel by Bootstrap)";
$conn = dbConnect();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title><?php echo $tutorialTitle;?></title>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<meta name="copyright" content="BEHSTANT SOFTWARE | Datasoft Engineering 2013"/>
<meta name="author" content="Reedyseth"/>
<meta name="email" content="ibarragan at behstant dot com"/>
<meta name="description" content="<?php echo $tutorialTitle;?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel=stylesheet href="css/style01.css">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="wrapper">
<div class="page-header ">
<div class="panel panel-default">
</div>
</div>
<div class="mainContent">
<form class="form-horizontal" role="form" method="get">
<div class="form-group">
<label class="col-sm-2 control-label" for="minimum date">employee_id</label>
<div class="input-group col-sm-9">
<input id="DateFrom" name="DateFrom" type="date" class="form-control" placeholder="Type the name" />
<input id="DateTo" name="DateTo" type="date" class="form-control" placeholder="Type the name" />
<span class="input-group-btn">
<button type="button" class="btn btn-default btnSearch">
<span class="glyphicon glyphicon-search"> Search</span>
</button>
</span>
</div>
</div>
</form>
<div class="col-sm-2"></div>
<div class="col-sm-8">
<!-- This table is where the data is display. -->
<table id="resultTable" class="table table-striped table-hover">
<tbody></tbody>
</table>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-1.10.2.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.btnSearch').click(function(){
makeAjaxRequest();
});
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});
function makeAjaxRequest() {
$.ajax({
url: 'search.php',
type: 'get',
DateFrom: {DateFrom: $('input#DateFrom').val()},
DateTo: {DateTo: $('input#DateTo').val()},
success: function(response) {
$('table#resultTable tbody').html(response);
}
});
}
});
</script>
</body>
</html>
Search.php:
<?php
require_once 'Connection.simple.php';
$conn = dbConnect();
$OK = true;
if (isset($_GET['DateFrom']) && isset($_GET['DateTo'])) {
$dateFrom = $_GET['DateFrom'];
$dateTo = $_GET['DateTo'];
$sql = "SELECT * FROM attendance WHERE date >= '". $dateFrom ."' AND date <= '". $dateto ."' ";
}
if(empty($rows)) {
echo "<tr>";
echo "<td colspan='4'>There were not records</td>";
echo "</tr>";
}
else {
foreach ($rows as $row) {
echo "<tr>";
echo "<td>".$row['emp_id']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['day']."</td>";
echo "<td>".$row['time_in']."</td>";
echo "<td>".$row['time_out']."</td>";
echo "<td>".$row['worked']."</td>";
echo "<td>".$row['overtime']."</td>";
echo "<td>".$row['less_hours']."</td>";
echo "<td>".$row['transport_in']."</td>";
echo "<td>".$row['Transport_out']."</td>";
echo "</tr>";
}
}
?>
EDIT 1:
$sql = "SELECT * FROM attendance WHERE date >= '". $dateFrom ."' AND date <= '". $dateto ."' ";
// we have to tell the PDO that we are going to send values to the query
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(array($dateFrom, $dateTo));
// Extract the values from $result
$rows = $stmt->fetchAll();
$error = $stmt->errorInfo();
******I added that to make execute the query but still not working******
<?php
function dbConnect (){
$conn = null;
$host = 'localhost';
$db = 'payroll';
$user = 'root';
$pwd = '';
try {
$conn = new PDO('mysql:host='.$host.';dbname='.$db, $user, $pwd);
//echo 'Connected succesfully.<br>';
}
catch (PDOException $e) {
echo '<p>Cannot connect to database !!</p>';
echo '<p>'.$e.'</p>';
exit;
}
return $conn;
}
?>
******* This is my code for DBconnection*******
My database name is payroll and the table is attendance.
You need to name the parameters inside SQL code.
Please, use the correct case for the columns names. You spelled "less_hours", while in your database this column is called "Less_Hours". And this gave a notice: "Undefined index: less_hours".
I put the output code inside the 1-st if, otherwise $rows will always be undefined for the first time.
This code worked for me:
if (isset($_GET['DateFrom']) && isset($_GET['DateTo'])) {
$dateFrom = $_GET['DateFrom'];
$dateTo = $_GET['DateTo'];
$sql = "SELECT * FROM attendance WHERE
date >= :date_from AND date <= :date_to ";
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(
array('date_from' => $dateFrom, 'date_to' => $dateTo));
// Extract the values from $result
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(empty($rows)) {
echo "<tr>";
echo "<td colspan='4'>There were not records</td>";
echo "</tr>";
}
else {
foreach ($rows as $row) {
echo "<tr>";
echo "<td>".$row['emp_id']."</td>";
echo "<td>".$row['Date']."</td>";
echo "<td>".$row['Day']."</td>";
echo "<td>".$row['Time_In']."</td>";
echo "<td>".$row['Time_Out']."</td>";
echo "<td>".$row['Worked']."</td>";
echo "<td>".$row['Overtime']."</td>";
echo "<td>".$row['Less_Hours']."</td>";
echo "<td>".$row['Transport_In']."</td>";
echo "<td>".$row['Transport_Out']."</td>";
echo "</tr>";
}
}
}
I am trying to make tabs that contain information about student, these information is stored in the database. I want the first tab to show the information of all students. and the the second tab to show the information of the students that thier grade is A and the the third tab to show the information of the students that thier grade is B.
I made this code but just the first tab shows the information of the students but the second and third tabs don't show anything.
what is wrong with the code?
<html>
<head>
<title>students table</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
</head>
<body>
<div id="tabs">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<?php
$connection = mysql_connect("","","");
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("", $connection);
$result = mysql_query("SELECT * FROM studentTable");
while($row = mysql_fetch_array($result))
{
?>
<div id="tabs-1">
<?php
echo "Student id: '" . $row["id"];
echo "Student name: '" . $row["name"];
echo "Student grade: '" . $row["grade"];
echo '</table>';
}
?>
</div>
<?Php
$result2 = mysql_query("SELECT * FROM studentTable WHERE grade = 'A'");
while($row = mysql_fetch_array($result2))
{
?>
<div id="tabs-2">
<?php
echo "Student id: '" . $row["id"];
echo "Student name: '" . $row["name"];
echo "Student grade: '" . $row["grade"];
echo '</table>';
}
?>
</div>
<?php
$result3 = mysql_query("SELECT * FROM studentTable WHERE grade = 'B'");
while($row = mysql_fetch_array($result3))
{
?>
<div id="tabs-3">
<?php
echo "Student id: '" . $row["id"];
echo "Student name: '" . $row["name"];
echo "Student grade: '" . $row["grade"];
echo '</table>';
}
?>
</div>
</div>
</body>
</html>
I think your issue is because you have your tabs-# <div> opening tags inside your while() loops.
$result = mysql_query("SELECT * FROM studentTable");
while($row = mysql_fetch_array($result))
{
?>
<div id="tabs-1"> //this here needs to be above/outside while($row = mysql_fetch_array($result)){
This is creating n number of <div id="tabs-1">,<div id="tabs-2">,<div id="tabs-3">, without matching closing tags </div>, so now <div id="tabs-2"> & <div id="tabs-3"> are nested in <div id="tabs-1"> and jQuery doesn't know which one to bind tabs to.
try moving them before the while() loops -
<div id="tabs-1">
<?php
$result = mysql_query("SELECT * FROM studentTable");
while($row = mysql_fetch_array($result))
{
...
}
?>
</div>
<div id="tabs-2">
<?php
$result2 = mysql_query("SELECT * FROM studentTable WHERE grade = 'A'");
while($row = mysql_fetch_array($result2))
{
...
}
?>
</div>
<div id="tabs-3">
<?php
$result3 = mysql_query("SELECT * FROM studentTable WHERE grade = 'B'");
while($row = mysql_fetch_array($result3))
{
...
}
?>
</div>
Also, you have echo '</table>'; at the end of each tab div. May want to remove those if you don't actually have a table.
In your script you are trying to use Jquery's tab method.
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
This is looking in the HTML for
<div id='tabs'>
You're tabs in here
</div>
Assuming that your SQL statments is not returing "NULL" then I would say you're issue is that you named you're div's tab-1, tab-2, tab-3. With ID's. This means that Jquery can't find anything to turn into tab's.
Change your jquery call to something like this
<script>
$(function() {
$( ".tabsclass" ).tabs();
});
</script>
and instead of using id's use classes.
<div class='tabsclass' id='tab-1'>
You're tabs in here
</div>
<div class='tabsclass' id='tab-2'>
You're tabs in here
</div>
<div class='tabsclass' id='tab-3'>
You're tabs in here
</div>