Simple PHP script connected to MYSQL Database - php

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

Related

Can't make MySQL queries in PHP webpage

So I'm working on a website where I need to pull data from a MySQL server and show it on a webpage. I wrote a simple PHP script to read data from the database depending upon an argument passed in the URL and it works just fine.
Here is the script:
<?php
function updator($item)
{
$servername = "localhost";
$username = "yaddvirus";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$table = "inventory";
//$item = "Rose Almonds";
$sql = "SELECT * FROM $table WHERE item = '$item'";
$result = $conn->query($sql);
while($data=$result->fetch_assoc()){
echo "<h1>{$data['item']}</h1><br>";
echo "<h1>{$data['item_desc']}</h1><br>";
echo "<h1>{$data['price125']}</h1><br>";
echo "<h1>{$data['price250']}</h1><br>";
}
//echo "0 results";
$conn->close();
}
if (defined('STDIN')) {
$item = $argv[1];
} else {
$item = $_GET['item'];
}
//$item = "Cherry";
updator($item);
?>
This script works exactly as expected. I call it using http://nutsnboltz.com/tester.php?item=itemname and it pulls and shows the data just fine.
P.S You can test it out by using Cherry or Blueberry as items.
The problem is, when I'm trying to put this data in my productpage.php file, I can't get the data to show up. Here's how the file hierarchy goes:
<php
*Exact same php script as above*
?>
<html>
<head>
Header and navbar come here
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-4">
<h1> RANDOM TEXT BEFORE </h1>
<?php
while($data=$result->fetch_assoc()){
echo "<h1>{$data['item']}</h1><br>";
echo "<h1>{$data['item_desc']}</h1><br>";
echo "<h1>{$data['price125']}</h1><br>";
echo "<h1>{$data['price250']}</h1><br>";
}
?>
</div>
<div class="col-8">
<H!> MORE RANDOM TEXT</h1>
</div>
</div>
</div>
</body>
<footer>
footer here
scripts etc
</footer>
</html>
So the script above the footer prints everything just fine. However, down where the HTML is, nothing is printed after the PHP code. It only shows my Navbar and the H1 tag saying "RANDOM TEXT BEFORE" and that's about it. My footer is gone along with everything else.
What exactly is the issue here and how do I fix this?
The problem seems to be that you're declaring $result inside the updator function, so it's not available when you're attempting to call it later.
The best thing to do might be to return $result from the function and assign that to a variable - something like this:
function updator($item)
{
// ... some code ...
$sql = "SELECT * FROM $table WHERE item = '$item'";
$result = $conn->query($sql);
// ... some more code ...
return $result;
}
<-- HTML CODE HERE -->
<?php
$item = !empty($_GET['item']) ? $_GET['item'] : false;
// yes I know it's a bit hacky to assign the variable
// within the 'if' condition...
if($item && $result = updator($item)) {
while($data=$result->fetch_assoc()){
echo "<h1>{$data['item']}</h1><br>";
echo "<h1>{$data['item_desc']}</h1><br>";
echo "<h1>{$data['price125']}</h1><br>";
echo "<h1>{$data['price250']}</h1><br>";
}
}
?>

Create a Clickable Link from a Table made from Database Results

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>");
?>

php update new SQL content [closed]

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)

'Trying to get property of non-object' error when attempting ->num_rows on inner join statement

I'm trying to print out both Product_Name from the product table and Order_Date from the order table but keep getting the error on line 35 the "num_rows line".
<?php
$servername = "localhost";
$username='root';
$password = "";
$dbname = "login";
?>
<html><<html>
<head>
<title>Cart</title>
<link rel="stylesheet" href="tabMenu.css" type="text/css">
</head>
<body>
</body>
</html>
<?php
$mysqli = new mysqli($servername,$username, Null, $dbname);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
session_start();
$results="Select orderline.Order_Date,p.Product_Name"
. "from orderline"
. "inner join product p"
. "on orderline.Product_ID=p.Product_ID";
$num=$mysqli->query($results);
if ($results->num_rows)
{
while ($row=$results->fetch_object())
{
echo "{$row->Order_Date} {$row->Product_ID} <br>";
}
}
else
{
echo "No Results";}
Thanks in advance any help would be great.
$results is a string, strings are not objects in PHP (at least not normally).
You need to look at the num_rows property of the results object:
$resultSet = $mysqli->query($results);
$numRows = $resultSet->num_rows;
if ($numRows > 0) {
while ($row = $resultSet->fetch_object()) {
echo "{$row->Order_Date} {$row->Product_ID} <br>";
}
}
Here is some documentation

DB Retrieval code displaying the code itself instead of the query results

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>

Categories