I'm trying to get a database to show up in a table according to an assignment(this is a college course). I have followed the instructions to the letter but I can't get the table to show up on the webpage. From what I can tell the database seems to be working properly and the Webpage shows up as intended but the table is empty. Right no the assignment is just setting up the early part of the program but the instructions say this should be working.
<?php
require_once 'login.php';
$pdo = new PDO($attr, $user, $pass, $opts);
// Get Pages via Get Request //
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
// Set Records to show per page //
$results_per_page = 5;
$stmt = $pdo->prepare('SELECT * FROM contacts ORDER BY c_id LIMIT :current_page, :results_per_page');
$stmt->bindvalue(':current_page', ($page-1)*$results_per_page, PDO::PARAM_INT);
$stmt->bindvalue(':results_per_page', $results_per_page, PDO::PARAM_INT);
$stmt->execute();
// Fetch the Records //
$contacts = $stmt->fetchALL(PDO::FETCH_ASSOC);
// Get the total contacts //
$num_contacts = $pdo->query('SELECT COUNT(*) FROM contacts')->fetchColumn();
?>
<!doctype html>
<html lang="en">
<head>
<title>Contact Directory</title>
<link href="./styles.css" rel="stylesheet" type="text/css">
<style>
<?php include "./styles.css" ?>
</style>
</head>
<body>
<header><img src="Diamonds.png" alt="Diamonds">My Contact List</header>
<nav>
<div class="navtable">
<ul id="navbar">
<li>Placeholder</li>
<li>Placeholder</li>
</ul>
</div>
</nav>
<content>
<div class="content">
<h2>Read Contacts
Create Contact
<table>
<thead>
<tr>
<td>#</td>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td>Title</td>
<td>Created</td>
<td></td>
</tr>
</thead>
<tbody>
<?php foreach($contacts as $contact): ?>
<tr>
<td><?php $contact['c_id']?></td>
<td><?php $contact['c_name']?></td>
<td><?php $contact['email']?></td>
<td><?php $contact['c_phone']?></td>
<td><?php $contact['title_id']?></td>
<td><?php $contact['created']?></td>
<td class="actions">
Edit
delete
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="page_advance">
<?php if ($page >1): ?>
Next->
<?php endif; ?>
<?php if ($page*$results_per_page < $num_contacts): ?>
<-Prev
<?php endif; ?>
</div>
</div>
</content>
<footer>
<div class="copyright">
<p>© Copyright 2022 by Ian Sikes-Cook, this site is for a class project</p>
</div>
</footer>
</body>
</html>
Related
I have a table on my website, which gets data from a database, in the table I have delete buttons on a row, I have just made the table searchable with jQuery, but now I can't figure out how to keep the delete buttons.
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta charset="utf-8">
<meta name="description" content="Inventar">
<meta name="author" content="Martin Eide Bjørndal">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="/src/css/style.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<button class="back" onclick="window.location='../'">
<img src="/src/icons/back.png">
</button> <!-- Tilbake knapp -->
<button class="ny_inventar" onclick="window.location='/admin/brukere/ny'">
<img src="/src/icons/add.png">
</button> <!-- Ny Bruker knapp -->
<div class="container-fluid" id="utskjekkcontainer">
<div class="row justify-content-center">
<div class="col-mv-10 bg-light mt-5 rounded p-3">
<h1 class="text-primary p-2">Brukere</h1>
<hr>
<div class="form-inline">
<label for="search" class="font-weight-bold lead text-dark">Søk</label>
<input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">
</div>
<hr>
<?php
include "../../src/fn/init.php";
$stmt=$conn->prepare("SELECT * FROM brukere");
$stmt->execute();
$result=$stmt->get_result();
?>
<table class="table table-hover table-light table-striped" id="table_data">
<thead>
<tr>
<th>#</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Utskjekket</th>
<th>Admin</th>
<th>Slett</th>
</tr>
</thead>
<tbody>
<?php while($row=$result->fetch_assoc()){ ?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["fornavn"]; ?></td>
<td><?php echo $row["etternavn"]; ?></td>
<td><?php echo $row["utskjekket"]; ?></td>
<td><?php echo $row["is_admin"]; ?></td>
<td>Slett</td>
</tr>
<?php }
$conn->close();
?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#search_text').keyup(function(){
var search = $(this).val();
$.ajax({
url:'action.php',
method:'post',
data:{query:search},
success:function(response){
$('#table_data').html(response);
}
});
});
});
</script>
</body>
</html>
action.php:
<?php
include "../../src/fn/init.php";
$output = "";
if(isset($_POST["query"])){
$search = $_POST["query"];
$stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
$stmt->bind_param("sss",$search, $search, $search);
} else {
$stmt=$conn->prepare("SELECT * FROM brukere");
};
$stmt->execute();
$result=$stmt->get_result();
if($result->num_rows>0){
$output = "<thead>
<tr>
<th>#</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Utskjekket</th>
<th>Admin</th>
<th>Slett</th>
</tr>
</thead>
<tbody>";
while($row=$result->fetch_assoc()){
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td>".Slett."</td>
</tr>";
};
$output .= "</tbody>";
echo $output;
} else {
echo "<h3>No match found!</h3>";
};
?>
This is the search script, the problem is in the while loop where the link is added, I can't figure out how to make it work.
The a tag is not added as a plain-text to the output string, you need to rewrite that line, concatenate strings parts to variables parts correctly.
Try replacing:
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td>".Slett."</td>
</tr>";
with:
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td><a href='delete.php?id=".urlencode($row['id'])."' onclick='return confirm('Er du sikker?');'>Slett</a></td>
</tr>";
To allow PHP to echo the id from the table result you need to just simply do a php echo
Slett
You don't have to url encode at this stage as you are just simply building the href of an a:link
You can use it
<?php
include "../../src/fn/init.php";
$output = "";
if(isset($_POST["query"])){
$search = $_POST["query"];
$stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
$stmt->bind_param("sss",$search, $search, $search);
} else {
$stmt=$conn->prepare("SELECT * FROM brukere");
};
$stmt->execute();
$result=$stmt->get_result();
if($result->num_rows>0){
$output = "<thead>
<tr>
<th>#</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Utskjekket</th>
<th>Admin</th>
<th>Slett</th>
</tr>
</thead>
<tbody>";
while($row=$result->fetch_assoc()){
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td>Slett </td>
</tr>";
};
$output .= "</tbody>";
echo $output;
} else {
echo "<h3>No match found!</h3>";
};
This is how I make a table of the files in a directory, they will be pdf or images, my first goal is to get just a part of title (which will be separated as I like lets say number_nam_company_color.pdf) and I have to take those informations to a table as links, when clicked they open in a window like with a button, and I'm not sure if I'm getting those files the right way.
<!DOCTYPE html>
<html>
<head>
<title>Aceuil</title>
<link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">
<link href="{{asset('css/style.css')}}" rel="stylesheet">
<script type="text/javascript" src="{{ URL::asset('js/jquery.js') }}"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div >
<div >
<table class="grey">
<tbody>
<tr>
<th>number</th>
<th>nam</th>
<th>company</th>
<th>color</th>
<th>date</th>
</tr>
<tr>
<?php
$dirname = 'myfiles';
$dir = opendir($dirname);
while($file = readdir($dir)) {
if($file != '.' && $file != '..' && !is_dir($dirname.$file)) {
?>
<td>
<?php
echo ''.$file.'';
?>
</td>
<td>
<?php
echo ''.$file.'';
?>
</td>
<td>
<?php
echo ''.$file.'';
?>
</td>
<td>
<?php
echo ''.$file.'';
?>
</td>
<td>
<?php
echo "filectime($dirname . '/' . $file))";
?>
</td>
</tr>
<?php
}
}
closedir($dir);
?>
</div>
</div>
</body>
</html>
t worked with this :
$data = "$file";
list($numero,$nom,$marque,$couleur) = explode("_", $data);
echo ''.$numero.'';//in the same way i can get anything i want from the title
echo ''.$nom.'';
and i want to open that pdf file in a window not with chrome?
I was tryin to create something quick to use data tables but I am having issues with jQuery I keep getting jQuery undefined and $ undefined. I thought I had put jQuery in the correct order. I am little stumped on what to do. I know it something simple so I will continue to figure it out.
Index.php
<div class="container">
<h1>Example List</h1>
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Equipment</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<?php
<?php
$db = new PDO('mysql:host=localhost;dbname=database;charset=utf8mb4', 'user', 'password');
$stmt = $db->query('SELECT * FROM table');
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{ ?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['equipment'];?></td>
<td><?php echo $row['qty'];?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php //script section ?>
<link rel="stylesheet" href="bootstrap.min.css">
<scriptsrc="jquery.js"></script>
<script src="jquery.dataTables.min.js"></script>
<script>
$('.table').DataTable();
</script>
Going for the low hanging apple here, but is <script src="jquery.js"></script> present as-is in your index? Seems to be a typing error.
The below code is connected to a local database that holds customer information. First, the page is supposed to display the customer name and country, but should display more information for that particular customer once the name is clicked.
The problem with this code below is that it will only always display the first customers information, no matter which name is clicked. Can anyone see where I might be going wrong? Do I need to create an ID for each button (customer name)? Bare in mind that there are a lot of customers in the database and I feel that an ID for each would be very difficult to implement, especially if the database gets modified.
<DOCTYPE html!>
<html>
<head>
<link rel="stylesheet" type="text/css" href="a3.css">
</head>
<body>
<div class="nav">
<?php include 'nav.php';
?>
</div>
<?php include 'dbconfig.php';
$sql ='SELECT * FROM `customers` ORDER BY `customers`.`country` ASC';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
?>
<div class = "main">
<table>
<?php while ($r = $q->fetch()): ?>
<tr>
<td><button onclick = "showCustomer();"/><?php echo ($r['customerName'])?></td>
<td><?php echo ($r['country'])?></td>
</tr>
<tr id ="extra" style="display:none">
<td><?php echo ($r['customerNumber'])?></td>
<td><?php echo ($r['contactLastName'])?></td>
<td ><?php echo ($r['contactFirstName'])?></td>
<td><?php echo ($r['phone'])?></td>
<td><?php echo ($r['addressLine1'])?></td>
<td><?php echo ($r['addressLine2'])?></td>
<td><?php echo ($r['city'])?></td>
<td><?php echo ($r['state'])?></td>
<td><?php echo ($r['postalCode'])?></td>
<td><?php echo ($r['salesRepEmployeeNumber'])?> </td>
<td><?php echo ($r['creditLimit'])?></td>
</tr>
<?php endwhile; ?>
</table>
</div>
<div class="foot">
<?php include 'foot.php'; ?>
</div>
<script>
function showCustomer() {
var showForm=document.getElementById('extra');
if (showForm.style.display="none") {
showForm.style.display ="";
alert('ok');
console.log(showForm);
}
else if (showForm.style.display=""){
showForm.style.display ="none";
}
}
</script>
</body>
</html>
</DOCTYPE>
All your <tr> have the same id="extra". As suggested, you need a different "id" for each of them, this is how : I created a variable $i (line 18), that is increased right after the while (line 20), inserted as parameter in the call for showCustomer (line 23), inserted at the end of the id "extra" (line 27), finally, on the bottom, where function showCustomer is declared, the parameter "index" is inserted at the end of the id "extra".
<DOCTYPE html!>
<html>
<head>
<link rel="stylesheet" type="text/css" href="a3.css">
</head>
<body>
<div class="nav">
<?php include 'nav.php';
?>
</div>
<?php include 'dbconfig.php';
$sql ='SELECT * FROM `customers` ORDER BY `customers`.`country` ASC';
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
?>
<div class = "main">
<table>
<?php $i = 0;
while ($r = $q->fetch()):
$i++; // UNIQUE INDEX FOR EACH CUSTOMER.
?>
<tr>
<td><button onclick = "showCustomer('<?php echo $i;?>');"/>
<?php echo ($r['customerName'])?></td>
<td><?php echo ($r['country'])?></td>
</tr>
<tr id ="extra<?php echo $i;?>" style="display:none">
<td><?php echo ($r['customerNumber'])?></td>
<td><?php echo ($r['contactLastName'])?></td>
<td ><?php echo ($r['contactFirstName'])?></td>
<td><?php echo ($r['phone'])?></td>
<td><?php echo ($r['addressLine1'])?></td>
<td><?php echo ($r['addressLine2'])?></td>
<td><?php echo ($r['city'])?></td>
<td><?php echo ($r['state'])?></td>
<td><?php echo ($r['postalCode'])?></td>
<td><?php echo ($r['salesRepEmployeeNumber'])?> </td>
<td><?php echo ($r['creditLimit'])?></td>
</tr>
<?php endwhile; ?>
</table>
</div>
<div class="foot">
<?php include 'foot.php'; ?>
</div>
<script>
function showCustomer( index ) { // UNIQUE INDEX AS PARAMETER.
var showForm=document.getElementById('extra' + index); // USING INDEX.
if (showForm.style.display="none") {
showForm.style.display ="";
alert('ok');
console.log(showForm);
}
else if (showForm.style.display=""){
showForm.style.display ="none";
}
}
</script>
</body>
</html>
</DOCTYPE>
I am using PHP & MySQL along with AJAX & jQuery to show contents from my database table.
PHP: serverside language as usual.
jQuery: to convert UTC time to local time based on user location. Thanks to jQuery localtime plugin :)
AJAX: to show contents of page2 into page1 on selecting a value from a drop down menu
Total no of pages: 2
Page1.php
I have an HTML table to which I show contents of all users. One of the values fetched from database is a UTC datetime variable.
To convert it into user's local time, I simply used a jQuery plugin. All that I had to do was add
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script type="text/javascript">$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");</script>
the above given files & then add a span <span class="localtime"> </span> in my table & echo the datetime variable into it. Viola! UTC time is now converted into user's local time.
In that same page, I have a dropdown menu showing list of all users from my database table. ANd on the onchange property of the drop down menu, I have called an AJAX function. This function will pass the username to page2.php & database opertaions are done in page2.php & results corresponding to that user is calculated & shown into an HTML table similar like to the HTML table I have in page1.php.
But in this table, UTC remains as such even though I tried adding the jQuery files in that page also. Why the jQuery localtime plugin didn't convert UTC time in page2 to localtime when it did the same in page1???
Here are two screen shots.
Page 1 before AJAX content loaded
Page1 after AJAX content loaded
Page1:
<html>
<head>
<title>Converting UTC time to Local time</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script type="text/javascript">$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");</script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script>
function value_pass_func(uname)
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()//callback fn
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showtable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","page2.php?variable="+uname,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$connection = mysqli_connect('localhost','root','','dummydb') or die(mysqli_error($connection));
$query="SELECT distinct(user) FROM pagination ORDER BY id ASC";
$res = mysqli_query($connection,$query);
$count = mysqli_num_rows($res);
?>
</br>
</br>
</br>
<select id="ddl" name="ddl list" onchange="value_pass_func(this.value);">
<option selected value="">select any</option>
<?php
if($count>0)
{
while($row=mysqli_fetch_array($res))
{
$now=$row['user'];
?>
<option value="<?php echo $now; ?>"><?php echo $now; ?></option>
<?php
}
}
?>
</select>
</br>
</br>
<?php
$query1="SELECT * FROM pagination ORDER BY id ASC";
$res1 = mysqli_query($connection,$query1);
$count1 = mysqli_num_rows($res1);
if($count1>0)
{
?>
<div id="showtable">
<table class="table table-bordered table-responsive table-striped" border="1">
<thead>
<tr >
<th>id</th>
<th>post</th>
<th>user</th>
<th>now</th>
</tr>
</thead>
<tbody>
<?php
while($row1=mysqli_fetch_array($res1))
{
$idd=$row1['id'];
$post=$row1['post'];
$username=$row1['user'];
$datetime=$row1['now'];
?>
<tr>
<td><?php echo $idd; ?></td>
<td><?php echo $post; ?></td>
<td><?php echo $username; ?></td>
<td><span class="localtime"> <?php echo $datetime; ?></span></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<?php } ?>
</body>
</html>
Page2:
<?php
$un=$_GET["variable"];
$connection = mysqli_connect('localhost','root','','dummydb') or die(mysqli_error($connection));
$query="SELECT * FROM pagination where user='".$un."' ORDER BY id ASC";
$res = mysqli_query($connection,$query);
$count = mysqli_num_rows($res);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script type="text/javascript">$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");</script>
<table class="table table-bordered table-responsive table-striped" border="1">
<thead>
<tr >
<th>id</th>
<th>post</th>
<th>user</th>
<th>now</th>
</tr>
</thead>
<tbody>
<?php
while($row=mysqli_fetch_array($res))
{
$idd=$row['id'];
$post=$row['post'];
$username=$row['user'];
$datetime=$row['now'];
?>
<tr>
<td><?php echo $idd; ?></td>
<td><?php echo $post; ?></td>
<td><?php echo $username; ?></td>
<td><span class="localtime"> <?php echo $datetime; ?></span></td>
</tr>
<?php
}
?>
</tbody>
</table>
You're loading jquery.. so I advise you to use it
The most simple answer to your question is to run this after your innerHTML replacement:
$.localtime.format(".localtime");
This will evaluate all of the elements again.
I suggest you do the following:
Use jquery's AJAX (link) to GET your table data.
Deliver your table data using JSON (link).
Personally I prefer to use Moment.js (link) to format my dates.
A basic jquery example..
Scripts on page1:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script>
$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");
function value_pass_func(uname)
{
$.ajax({
type: "GET",
url: "page2.php",
data: { variable: uname },
dataType: html
}).done(function(data) {
$("#showtable").innerHTML = data;
$.localtime.format(".localtime");
});
}
</script>
And drop those script tags in page2.
I haven't tested that localtime script but it probably does it's thing when fired