I'm making a class web-page that allow you to view class details by clicking a link associated with the class. I have a database loaded with classes,enrolled students as well as the assigned professor. Below I have the query in a for each loop creating a table from the results however I want to make the entries urls that direct to that class page. For example: "localhost/class?class_id=cs120". I can't just add a link below and have it parameterized to cs120 as all links would just go there. My understanding of SQLITE3, PHP and HTML is limited, Below is my code for this page.
<!DOCTYPE html>
<?php include("secure.php") ?>
<html lang= "en">
<head>
<title> Class Index </title>
<meta charset= "utf-8" />
<link rel="stylesheet" href="class_coverpage.css" />
</head>
<?php
//echo("Hello Retrieving Table");
$username = $_SESSION['user'];
//echo 'Hello: ' . $username;
$classquery = "SELECT DISTINCT Classes.Class_id, Classes.Section_id ,Classes.className, Classes.Subject, Classes.Location FROM Classes,StudentClasses,Students WHERE StudentClasses.Class_id = Classes.Class_id AND StudentClasses.Student_id = Students.Student_id AND StudentClasses.Section_id = Classes.Section_id AND Students.Username = '$username'; ";
//$teacherquery = "SELECT TeacherClasses.Teacher_id, TeacherClasses.Class_id FROM TeacherClasses";
//echo("Trimming Query");
trim($classquery);
//echo("Stripping Slashes");
$classquery = stripslashes($classquery);
//echo("Setting up Query");
$results = $db->query($classquery);
if (!$results){
echo("<h2>Error: The query could not be executed.</h2>");
$error = $db->lastErrorMsg();
echo("<p>$error<p>");
exit;
}
echo "<table><tr>";
echo "<td>Course ID:</td>";
echo "<td>Section ID:</td>";
echo "<td>Subject:</td>";
echo "<td>Location:</td></tr>";
echo("<tr>");
for($i=0;$i<$num_cols;$i++){
$head = $results->columnName($i);
echo("<th>$head</th>");
}
echo ("</tr>");
// Write rows into table
$ct = 0;
while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
echo ("<tr>");
foreach($row as $v){
// I want to Make this section down here create a link hopefully.
//echo ("<td><a href='class_detail.php?Class_id=$row['id']'> $v </a></td>");
}
$ct = $ct + 1;
echo ("</tr>");
}
echo
("</table>");
?>
Related
How would I output the selected data from the database over a certain amount of pages.
For example I'd like 20 result per page and it automatically adds the extra pages needed (bit like google search pages but no search is needed as I am getting everything from the database).
Sorry for a bad explanation and also badly indented code, new to stackoverflow. I've tried putting just the php, rest of the page isn't complete or I removed the unnecessary code, feel free to improve as well.
At the moment I am just calling all the data onto one page using very simple
code
<?php
session_start();
if(isset($_POST['logout'])) {
unset($_SESSION['Username']);
session_destroy();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="" style="min-width: 1024px; max-width: 1920px; margin: 0 auto; min-height: 1280px; max-height: 1080px;">
<?php
if (isset ($_SESSION['Username']))
{
?>
<button onclick="location.href = 'logout.php';">Logout</button>
<?php
if (isset ($_SESSION['Username']))
{
echo "";
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "request";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM request";
$result = $conn->query($sql);
$sql = "SELECT * FROM request ORDER BY id DESC";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
if (isset ($_SESSION['Username']))
{
?>
<div align="center">
<div class="requests">
<p><?php echo $row["Name"]; ?></p>
<p><?php echo $row["Number"]; ?></p>
<p><?php echo $row["Song"]; ?></p>
</div>
</div>
<?php
}else{
header("Location: index.php");
}
}
} else {
echo "0 requests";
}
}
mysqli_close($conn);
?>
Let's see an example of pagination in PHP. Before that, we need to understand what pagination is. Result pagination is quite simple.
We do a search on a certain DataBase table, and with the result of the search, we divide the number of records by a specific number to display per page.
Related: Data pagination in PHP and MVC
For example a total of 200 records, and we want to display 20 per page, we will soon have 200/20 = 10 pages. Simple, right? Well let's go to the code then.
First connect to MySQL:
<?php
$conn = mysql_connect("host","user","pass");
$db = mysql_select_db("database");
?>
Now let's create the SQL clause that should be executed:
<?php
$query = "SELECT * FROM TableName";
?>
Let's get to work ... Specify the total number of records to show per page:
<?php
$total_reg = "10"; // number of records per page
?>
If the page is not specified the variable "page" will take a value of 1, this will avoid displaying the start page 0:
<?php
$page=$_GET['page'];
if (!$page) {
$pc = "1";
} else {
$pc = $page;
}
?>
Let's determine the initial value of the limited searches:
<?php
$begin = $pc - 1;
$begin = $begin * $total_reg;
?>
Let's select the data and display the pagination:
<?php
$limit = mysql_query("$query LIMIT $begin,$total_reg");
$all = mysql_query("$query");
$tr = mysql_num_rows($all); // checks the total number of records
$tp = $tr / $total_reg; // checks the total number of pages
// let's create visualization
while ($dados = mysql_fetch_array($limit)) {
$name = $data["name"];
echo "Name: $name<br>";
}
// now let's create the "Previous and next"
$previous = $pc -1;
$next = $pc +1;
if ($pc>1) {
echo " <a href='?page=$previous'><- Previous</a> ";
}
echo "|";
if ($pc<$tp) {
echo " <a href='?page=$next'>Next -></a>";
}
?>
Ready, your pagination in PHP is created!
I have the following code and need some customizations. I need a line break after each mysql record and the capability for the webpage to load at the very bottom. Can this be possible? Thanks in advance. CODE:
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title> Food Orders </title>
<link rel="stylesheet" type ="text/css" href="default.css">
</head>
<body>
<?php
$server_name = "localhost";
$user_name = "root";
$password = "mysqlpW";
$database_name = "menuDB12";
$connection = new mysqli($server_name, $user_name, $password, $database_name);
if ($connection->connect_error) {
die("Connection Error: " . $connection->connect_error);
}
$attributes "SELECT tablenumber, food FROM clients";
$results = $connection->query($attributes);
if ($results->num_rows > 0) {
while ($rows = $results->fetch_assoc()) {
echo "Table Number: " . $rows["tablenumber"]. " Food Item: " . $rows ["food"].
"<br>";
}
} else {
echo "No Results";
}
$connection->close();
?>
</body>
</html>
if i understood right, you want to display your database results at the end of the page, for that you can try this
$table = ''; if ($results->num_rows > 0) {
while ($rows = $results->fetch_assoc()) {
$table .= "Table Number: " . $rows["tablenumber"]. " Food Item: " . $rows ["food"].
"<br>";
}
} else {
$table = "No Results";
}
and at the end of your page or where you want it to be displayed simply add
<?php echo $table; ?>
You write about line breaks in the original question, but in the comments you specify page breaks (for printing).
Also, I understand you want the content to be displayed at the bottom of the printed page.
If my understanding is correct (and it would help if you edited the question to be more precise), I'd suggest consulting the following:
Page breaks for printing on php page
It helped me some time ago when I was creating a web-based document for printing.
Just use echo "<br>"; for a new line.
And i would recommend ajax for refreshing
https://www.w3schools.com/xml/ajax_intro.asp
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm new to PHP so please have patience and explain it to me like I'm 5.
I have a page where it shows the content of a table from SQL, but whenever I update with php I have for force update my browser to make it display the new content of the table. I got the same problem as this guy but I didn't understand his solution:
Php won't update to show new sql content
This is my PHP code for updating the table:
<!-- html dok -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
</body>
</html>
<?php
$server = "localhost";
$brugernavn = "";
$kode = "";
$db = "";
mysql_connect($server , $brugernavn , $kode) or die(mysql_error());
echo "Forbundet til mysql server<br/>";
mysql_select_db($db)or die(mysql_error());
echo "Forbundet til databasen<br/><br/>";
$data = mysql_query("SELECT * FROM nyheder" ) or die(mysql_error());
while ($info = mysql_fetch_array($data))
{
echo "Nyhed: " . $info['nyhed']. "<br/><br/>";
}
// Update tabel
if (isset($_POST['update'])) {
$nyhed = $_POST['nyhed'];
$tabeldata = "UPDATE nyheder SET nyhed = '$nyhed' WHERE ID ='1'";
$resultat = mysql_query($tabeldata);
if($resultat) {
echo "Din nyhed blev opdateret" . "<a href=get.php>Videre</a>";
}
else {
echo "FEJL";
}
}
else {
echo "Ingen nyheder er blevet opdateret";
}
mysql_close();
?>
and this is my code for displaying the table content:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT nyhed FROM nyheder WHERE ID='1'";
$result = $conn->query($sql);
$link_address = 'form.php';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["nyhed"] . "<br><br>";
echo "<a href='$link_address'>Opdater</a>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
Thank you so much in advance! :)
If you want to use Php won't update to show new sql content's answer change below
if($resultat) {
echo "Din nyhed blev opdateret" . "<a href=get.php>Videre</a>";
}
to
if($resultat) {
echo "Din nyhed blev opdateret" . "Videre";
}
this will add current time to get.php as query string (will looks like get.php?time=1417626725) and every time you click the link browser sees get.php as new url and fetch the page again without load it from cache (if it's cached)
Hi i was trying to connect MySQL database to a simple html code given below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org
/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="result.php" method="POST">
S.No :
<input type="text" name="key">
<input type="submit" value="Search">
</form>
</body>
</html>
This html code passes the form input "key" to another php file whose code is given below.
<?php
$serial=$POST['key'];
if(!$serial){
echo 'Please go back and enter the correct value';
exit;
}
$db = new mysqli('localhost', 'root', '', 'demo_db', 'tbldem');
if(mysqli_connect_errno()) {
echo 'Connection lost.. please try again later !!';
exit;
}
$query = "select * from tbldem where".$serial."like'%".$serial."%'" ;
$result = $db->query($query);
$num = $result->num_rows;
for($i = 0; $i < $num; $i++) {
$row = $result->fetch_assoc();
echo"<p>Serial : </p>";
echo $row['Index'];
echo"<p>Name : </p>";
echo $row['Name'];
echo "<p>Course : </p>";
echo $row['Course'];
}
$result->free();
$db->close();
?>
Now when I try to pass a value in the form input in the my browser I get a php code as a result instead of the information in the database which was supposed to to be returned while passing the value in form input, which is also given below(the problem). I am trying to make a project which use this feature as a primary tool so please help as soon as possible.
query($query); $num = $result->num_rows;
for($i = 0; $i < $num; $i++) {
$row = result->fetch_assoc(); echo"
Serial :
"; echo $row['Index']; echo"
Name :
"; echo $row['Name']; echo "
Course :
"; echo $row['Course']; } $result->free(); $db->close(); ?>
I commented some wrong line in the code and i changed them, just follow it.
<?php
$serial=$_POST['key']; // change to $_POST['key'];
if(!$serial){
echo 'Please go back and enter the correct value';
exit;
}
$db = mysqli_connect('localhost','user_name','pass','demo_db'); // dont select your table in this line
mysqli_select_db($con,"tbldem"); // select your table here
if(mysqli_connect_errno()){
echo 'Connection lost.. please try again later !!';
exit;
}
$query = "select * from tbldem where serial LIKE '%$serial%';" ; // change $serial to serial like this line
$result = $db->query($query);
$num = $result->num_rows;
for($i=0;$i<$num;$i++){
$row = $result->fetch_assoc();
echo"<p>Serial : </p>";
echo $row['Index'];
echo"<p>Name : </p>";
echo $row['Name'];
echo "<p>Course : </p>";
echo $row['Course'];
}
$result->free();
$db->close();
?>
The only issue I see right off the top of my head is you wrote $POST['key']; when it should be $_POST['key']; don't forget the underscore. Visit the PHP manual to learn more, it also helps with debugging code.
On another note, for those hopefully learning from this question, it is good to point out that the code you are using to connect to the database is taking advantage of a work around that doesn't technically use the official Object Oriented method. This allows your PHP code to work in PHP versions prior to 5.2.9/5.3.0 when it was fixed. See the PHP manual for some great explanations on that.
Hope this helps.
I'm just learning PHP and MySQL, so I'm guessing my error is really obvious.
I have a DB Table called inventory and I'm trying to pull up information on the car named Mustang. That is the name of the car under the Make column.
The problem I'm having is that my first echo statement is not ending with what should be the closing " and the following ;. It is echo'ing everything that follows it in the code, down to the ?> at the end of the file.
Here is the code itself. Note this is just a database I threw together in 10 minutes in phpmyadmin and not anything official.
<!DOCTYPE html>
<html>
<head>
<title>Realistic Autos Inventory</title>
<script>
<?php
function GetInventory($CarName)
{
$user="Uhrmacher";
$host="localhost";
$password="";
$dbname="realistic autos";
$cxn= mysqli_connect($host, $user, $password, $dbname) or die("Failure to Communicate!");
$query = "SELECT * FROM inventory WHERE Make='$CarName'";
$result = mysqli_query($cxn, $query) or die ("Failure to Query!");
$index=1;
while($row=mysqli_fetch_query($result))
{
foreach($row as $colname => $value)
{
$array_multi[$index][$colname]=$value;
}
$index++;
}
return $array_multi;
}
?>
</script>
</head>
<body>
<?php
$CarName = "Mustang";
$CarInfo = GetInventory($CarName);
echo "<h1>{$type}s</h1>\n";
echo "<table cellspacing='15'>\n";
echo "<tr><td colspan='4'><hr /></td></tr>\n";
for ($i=1; $i<=sizeof($CarInfo); $i++)
{
$f_price = number_format($CarInfo[$i]['Price'], 2);
echo "<tr>\n
<td>$i.</td>\n
<td>{$CarInfo[$i]['StockNumber']}</td>\n
<td>{$CarInfo[$i]['Year']}</td>\n
<td>{$CarInfo[$i]['Make']}</td>\n
<td>{$CarInfo[$i]['Model']}</td>\n
<td>{$CarInfo[$i]['Package']}</td>\n
<td style='text-align: right'>\$$f_price</td>\n
<td>{$CarInfo[$i]['CurrentMiles']}</td>\n
<td>{$CarInfo[$i]['Engine']}</td>\n
<td>{$CarInfo[$i]['Transmission']}</td>\n
<td>{$CarInfo[$i]['DriveType']}</td>\n
<td>{$CarInfo[$i]['VIN']}</td>\n
<td>{$CarInfo[$i]['BoughtFrom']}</td>\n
<td>{$CarInfo[$i]['BoughtHow']}</td>\n
<td>{$CarInfo[$i]['LicensingFee']}</td>\n
<td>{$CarInfo[$i]['GasMileage']}</td>\n
</tr>\n";
echo "<tr><td colspan='4'><hr /></td></tr>\n";
}
echo "</table>\n";
?>
</body>
</html>
The following is the output.
\n"; echo "
\n"; for ($i=1; $i<=sizeof($CarInfo); $i++) { $f_price = number_format($CarInfo[$i]['Price'], 2); echo "\n $i.\n {$CarInfo[$i]['StockNumber']}\n {$CarInfo[$i]['Year']}\n {$CarInfo[$i]['Make']}\n {$CarInfo[$i]['Model']}\n {$CarInfo[$i]['Package']}\n \$$f_price\n {$CarInfo[$i]['CurrentMiles']}\n {$CarInfo[$i]['Engine']}\n {$CarInfo[$i]['Transmission']}\n {$CarInfo[$i]['DriveType']}\n {$CarInfo[$i]['VIN']}\n {$CarInfo[$i]['BoughtFrom']}\n {$CarInfo[$i]['BoughtHow']}\n {$CarInfo[$i]['LicensingFee']}\n {$CarInfo[$i]['GasMileage']}\n \n"; echo "
\n"; } echo "\n"; ?>
I wasn't sure how to search this, so sorry if this is a common problem.
Get that php out of those script tags! Put it all into one nice php block. Ideally you'd do something like have a "connect.php" page just for setting up your db connection then do an but it'll work on your page you have now.
Get rid of all those "\n"s. Those arnt helping anything. You dont need to have lines in your html, your browser will understand. (i'm assuming thats why you put them in). You had a bunch of crazy stuff going on when you created your table. Maybe you need it so its formatted pretty. I took it out. Lets get basic functionality working first. Table structure goes as follows: Table-head-row definition-closingTableTag.
Edit: Also i dont know why you had characters before and but make sure those are gone. And make sure you're saving your file as .php and not .html.
Try this, get back to us.
<!DOCTYPE html>
<html>
<head>
<title>Realistic Autos Inventory</title>
</head>
<body>
<?php
$user="Uhrmacher";
$host="localhost";
$password="";
$dbname="realistic autos";
$cxn= mysqli_connect($host, $user, $password, $dbname) or die("Failure to Communicate!");
function GetInventory($CarName){
$query = "SELECT * FROM inventory WHERE Make='$CarName'";
$result = mysqli_query($cxn, $query) or die ("Failure to Query!");
$index=1;
while($row=mysqli_fetch_query($result))
{
foreach($row as $colname => $value)
{
$array_multi[$index][$colname]=$value;
}
$index++;
}
return $array_multi;
}
$CarName = "Mustang";
$CarInfo = GetInventory($CarName);
echo "<h1>{$type}s</h1>";
echo "<table>";
//table header for every column you have. You could write a for loop to simplify
echo "<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th></tr>";
for ($i=1; $i<=sizeof($CarInfo); $i++)
{
$f_price = number_format($CarInfo[$i]['Price'], 2);
echo "<tr>
<td>$i.</td>
<td>{$CarInfo[$i]['StockNumber']}</td>
<td>{$CarInfo[$i]['Year']}</td>
<td>{$CarInfo[$i]['Make']}</td>
<td>{$CarInfo[$i]['Model']}</td>
<td>{$CarInfo[$i]['Package']}</td>
<td>$f_price</td> //DONT GET FANCY YET, JUST MAKE SURE IT WORKS
<td>{$CarInfo[$i]['CurrentMiles']}</td>
<td>{$CarInfo[$i]['Engine']}</td>
<td>{$CarInfo[$i]['Transmission']}</td>
<td>{$CarInfo[$i]['DriveType']}</td>
<td>{$CarInfo[$i]['VIN']}</td>
<td>{$CarInfo[$i]['BoughtFrom']}</td>
<td>{$CarInfo[$i]['BoughtHow']}</td>
<td>{$CarInfo[$i]['LicensingFee']}</td>
<td>{$CarInfo[$i]['GasMileage']}</td>
</tr>";
}
echo "</table>";
?>
</body>
</html>