Can't make MySQL queries in PHP webpage - php

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

Related

Output database results over multiple pages

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'm trying to call a PHP function inside a echo

i'm trying to call getMensClothing() function from function.php to header.php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "khaki";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function getMensClothing(){
global $conn;
$sql = "SELECT * FROM men_clothing";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<li><a href='#' class='hvr-grow'>". $row['men_clo_items']." </a></li>";
}
}
}
header.php file looks like this
<?php include 'functions.php'; ?>
<?php
echo'
<div class="col-sm-2"><br>
<p> <b>Men\'s Clothing</b></p>
<ul>
'.getMensClothing().'
</ul>
</div>'
?>
function is called but the items aren't displayed where it has to everything is show at the top of the page . How to display the items inside the div ??
Use below Code
$html = "";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$html .= "<li><a href='#' class='hvr-grow'>". $row['men_clo_items']."</a></li>";
}
}
return $html;
into your function.php file
create a class like
class support{
//inside goes codes and functions
}
while calling into another file.
include it above file then create
$a=new support()
$a->functionname();
this should do the trick
What happens is that you use echo with parameters, that are evaluated to be printed.
You use concatenation with your arguments to echo.
You have one parameter contructed with the concatenation of three arguments.
The result of this concatenation is printed. One of these arguments is the returned value of the getMensClothing() function.
During the evaluation of getMensClothing() you print some data.
Consequently, the data printed in your function getMensClothing() gets printed before the end of the call to echo statement in header.php.
As other people pointed out, you should reconsider your technique as your code could be more easy to use if you separate the job of retrieving and constructing your data and the job of displaying it. Have a look to MVC for instance.

PHP - Secure member-only pages with a login system

Hello, I've been stumped by the PHP code I've written. I've stared at this for hours with no success, please help find any errors I've apparently gone over.
What I want this script to do is from a html form page, to query a database table ('users') to make sure their password and username are correct, then in a separate table ('tokens') insert a random token (the method I used before, it works) into the 'tk' column, and the users general auth. code pulled from the 'users' table into the 'gauth' colum, in the 'tokens' table.
The reason for the additional general auth is so I can pull their username and display it on all the pages I plan on "securing"
Sorry if I'm confusing, this is the best I can refine it. Also, I'm not that good at formatting :). I'm going to add some html later, that's why the tags are there.
MySQL Tables:
Users Example:
cols: username | password | email | classcode | tcode | genralauth |
hello | world | hello.world#gmail.com | 374568536 | somthin | 8945784953 |
Tokens Example:
cols: gauth | tk |
3946893485 |wr8ugj5ne24utb|
PHP:
<html>
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "-------";
$password = "-------";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql1 = "SELECT username FROM users";
$data1 = $conn->query($sql1);
if ($conn->query($sql1) === TRUE) {
echo "";
}
?>
<?php
$sql2 = "SELECT password FROM 'users'";
$data2 = $conn->query($sql2);
if ($conn->query($sql2) === TRUE) {
echo "";
}
?>
<?php
$bytes = openssl_random_pseudo_bytes(3);
$hex = bin2hex($bytes);
?>
<?php
if($_POST['pss'] == $data2 and $_POST['uname'] == $data1) {
$correct = TRUE;
}
else {
$correct = FALSE;
}
?>
<?php
if ($correct === TRUE) {
$sql3 = "SELECT generalauth FROM users WHERE password='".$_POST['pss']."'";
$result3 = $conn->query($sql3);
}
?>
<?php
if ($correct === TRUE) {
$sql4 = "INSERT INTO tokens (tk,gauth) VALUES (".$hex."' , '".$result3."')";
if ($conn->query($sql4) === TRUE) {
echo "New token genrated.";
} else {
echo "Error: " . $conn->error;
}
}
?>
<?php
if ($correct === TRUE) { ?>
<p>Succesfuly loged in!</p><br/>
<button>Continue</button><br/>
<?php
}
elseif ($correct === FALSE) { ?>
<p>Incorrect, please try again.</p><br/>
<button>Back</button><br/>
<?php
}
?>
<?php
if ($correct === TRUE) {
$_SESSION['auth'] = $hex;
$_SESSION['logstat'] = TRUE;
}
?>
<?php
if ($correct === FALSE) {
$_SESSION['logstat'] = FALSE;
}
$conn->close();
?>
This is the PHP I'm going to use on most pages for token auth, howver it dosn't actually check the database 'tokens', also I need a way to display signed in users username using the general auth.
PHP:
<html>
<h1 class="title">Virtual Work Sheets!</h1>
<p class="h_option">[Log In / Register]</p><hr/>
<div class="body">
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "root20";
$password = "jjewett38";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql = "SELECT tk FROM tokens";
$data = $conn->query($sql);
?>
<?php
if (!$_GET['tk'] == $data) {
echo "
<p>Invalid token, please consider re-logging.</p>
";
}
else {
?>
<?php
switch ($_GET['view']) {
case teacher:
?>
Teacher page html here...
<?php
break;
case student:
?>
Student page html here...
<?php
break;
default:
echo "Please login to view this page.";
}
}?>
</html>
I suggest that you change your approach.
Although at first glance these example files looks like a lot, once you study them you'll see it's really much more simple and logical approach than the direction you are now headed.
First, move the db connect / login stuff into a separate file, and require or include that file at top of each PHP page:
INIT.PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Might as well also load your functions page here, so they are always available
require_once('fn/functions.php');
?>
Now, see how we use it on the Index (and Restricted) pages?
INDEX.PHP
<?php
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<!-- Examples need jQuery, so load that... -->
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<!-- and our own file we will create next... -->
<script type="text/javascript" src="js/index.js"></script>
<div id="pageWrap">
<div id="loginDIV">
LoginID: <input type="text" id="liID" /><br>
LoginPW: <input type="password" id="liPW" /><br>
<input type="button" id="myButt" value="Login" />
</div>
</div>
JS/INDEX.JS
$(function(){
$('#myButt').click(function(){
var id = $('#liID').val();
var pw = $('#liPW').val();
$.ajax({
type: 'post',
url: 'ajax/login.php',
data: 'id=' +id+ '&pw=' +pw,
success: function(d){
if (d.length) alert(d);
if (d==1) {
window.location.href = 'restricted_page.php';
}else{
$('#liID').val('');
$('#liPW').val('');
alert('Please try logging in again');
}
}
});
});//END myButt.click
}); //END document.ready
AJAX/LOGIN.PHP
<?php
$id = $_POST['id'];
$pw = $_POST['pw'];
//Verify from database that ID and PW are okay
//Note that you also should sanitize the data received from user
if ( id and password authenticate ){
//Use database lookups ot get this data: $un = `username`
//Use PHP sessions to set global variable values
$_SESSION['username'] = $un;
echo 1;
}else{
echo 'FAIL';
}
RESTRICTED_PAGE.PHP
<?php
if (!isset($_SESSION['username']) ){
header('Location: ' .'index.php');
}
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<h1>Welcome to the Admin Page, <?php echo $_SESSION['username']; ?>
<!-- AND here go all teh restricted things you need a login to do. -->
More about AJAX - study the simple examples

Publishing MySQL data into PHP Columns [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
im working on a project for basically my friends and i to use. Maybe to use it for other games as well. SpeedRunning! i have made and was able to POST the Data into MySQL with THIS information
<?php include_once('include/action_page.php');?>
<!DOCTYPE HTML>
<meta charset="UTF-8">
<html>
<head>
<title>Roleplayer's Tavern Home</title>
<link href="/style/style.css" rel="stylesheet" type="text/css">
<script src="/include/jquery-1.11.2.min.js"></script>
<?php include_once('/include/rpt_site_no_script.php');?>
</head>
<body onload="">
<div class="page_container" name="page_container">
<div id="page_header">
<!-- The title of the webpage -->
<div style="max-width:250px; overflow:hidden">
<span id="header_title"><img src="style/logo.png" style="width:225px; height:67px;"/></span>
</div>
</div>
<!-- Left side bar -->
<div id="page_container_left">
<h3 id="page_content_header">Submit your data!</h3>
<?php include('include/submit_data.php');?>
</div>
<div id="page_container_right"
style="overflow-y: auto; max-height: 100%">
<h3 id="page_content_header">Donations for website?</h3>
<?php
?>
</div>
<!-- Main Content -->
<div id="page_content_container_main_page">
<div class="page_content_container">
<h2 id="page_content_container_header">Leaderboard WOO WOO</h2>
<hr>
<p id="page_content_container_content">
<h2>Players That Have Beaten Mad Pack 2</h2>
<?php include('include/leaderboard.php');?>
</div>
</div>
<br>
<!-- Footer -->
<div id="page_footer">
<ol id="footer_list">
<li>Copyright © Roleplayer's Tavern 2015-2016 - All Rights Reserved</li>
<li style="font-size:12px">Your IP address <?php echo $_SERVER['REMOTE_ADDR']; ?> will be logged for security reasons.</li>
</ol>
</div>
</div>
<script type="text/javascript">
var element=document.getElementsByName('page_container')[0];
var applyTo=document.getElementById('page_container_left');
var applyTo2=document.getElementById('page_container_right');
applyTo.style.height = (element.offsetHeight - 2) + "px";
applyTo2.style.height = (element.offsetHeight - 2) + "px";
window.onresize = function(event) {
var element=document.getElementsByName('page_container')[0];
var applyTo=document.getElementById('page_container_left');
var applyTo2=document.getElementById('page_container_right');
applyTo.style.height = (element.offsetHeight - 2) + "px";
applyTo2.style.height = (element.offsetHeight - 2) + "px";
}
</script>
</body>
</html>
as this is the HTML format.
Action_page.php is the page for submitting the information
<?php
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$mysqlDatabaseName = "SpeedRun";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $mysqlDatabaseName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$sql = "INSERT INTO MineCraftRecords (MineCraftName, LevelSeed, Day, Time)
VALUES ('$_POST[MinecraftName]', '$_POST[LevelSeed]', '$_POST[Day]', '$_POST[Time]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Turtle Mode Activated";
$conn->close();
?>
<meta http-equiv="Location" content="https://rptavern.org/SpeedRun/">
and im having trouble on getting the page to LOAD the information provided into the leaderboard.php as this is what i have so far.
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$mysqlDatabaseName = "SpeedRun";
$query="SELECT * FROM MineCraftRecords";$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;while ($i < $num) {CODE$i++;}
$variable=mysql_result($result,$i,"fieldname");
$field1-name=mysql_result($result,$i,"MineCraftName");
$field2-name=mysql_result($result,$i,"LevelSeed");
$field3-name=mysql_result($result,$i,"Day");
$field4-name=mysql_result($result,$i,"Time");
$field5-name=mysql_result($result,$i,"id");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $mysqlDatabaseName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Turtle Mode Activated";
?>
Im basically trying to base it off this website http://www.speedrun.com/mc but not as technical. Just to show the SpeedRunning time and have the TIME the top of the list.
Any help is awesome, as im very new to creating stuff like this. i will take the time to read everyone's comments and suggestions that you all can provide :D
I suggest cleaning up your code. Some thing that can be done is that you can separate the dB connect details into a separate file. This will optimize your code and will it make sure to change the details later on as your project grows.
If you would ever consider using PDO here is a code example that will help you out. I'm not sure if mySQLi is similar to PDO but have a look anyway. It's super easy to use and implement in as many pages as possible!
HTML/PHP (displaying data in table):
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
</head>
<body>
<?php
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
require_once("../DAL/db_functions.php");
//Run query on branch table
readQuery("M_Branch");
//If there are any details in branch table continue
if($numRecords === 0){
echo "<p>No Branches Found!</p>";
}
else{
$arrRows = NULL;
//Create table and headings
echo "<table id='mavis' border='1' width='100%'>";
echo "<tr>";
echo "<th>Branch Code</th>";
echo "<th>Branch Name</th>";
echo "<th>Manager</th>";
echo "<th>Branch Address</th>";
echo "<th>Suburb</th>";
echo "<th>State</th>";
echo "<th>Post Code</th>";
echo "<th>Phone Number</th>";
echo "<th>Fax Number</th>";
echo "<th></th>";
echo "</tr>";
while($arrRows = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
echo "<td>".$arrRows['Branch_Code']."</td>";
echo "<td>".$arrRows['Branch_name']."</td>";
echo "<td>".$arrRows['Manager']."</td>";
echo "<td>".$arrRows['Branch_Address']."</td>";
echo "<td>".$arrRows['Suburb']."</td>";
echo "<td>".$arrRows['State']."</td>";
echo "<td>".$arrRows['Post_code']."</td>";
echo "<td>".$arrRows['Phone']."</td>";
echo "<td>".$arrRows['Fax']."</td>";
//Cannot delete already created records - Foreign key constraint fails
//If phpMyadmin were to delete one then other tables will incur problems
echo "<td><a href='edit_branch.php?ID=$arrRows[Branch_Code]'>Edit</a>";
echo "<br /><a href='../BLL/delete_confirm.php?TYPE=Branch&ID=$arrRows[Branch_Code]' onClick='return checkDelete()'>Delete</a></td></tr>";
}
echo "</table>";
echo "<form action='../DAL/add_branch.php' method='post'>";
echo "<input type='submit' value='Add a New Branch' />";
echo "</form>";
echo "<p></P><P>$numRecords Records Returned</P>";
}
?>
</body>
Here is my connect and readQuery function located in ../Db_functions.php
I have created functions that are reusable and can be used with multiple DB tables.
//Database connection Variables
$localhost = "localhost";
$user = "root";
$password = "root";
$db = "Mavis";
$dsn = "mysql:host=$localhost;dbname=$db";
//Declare Global Variables
$dbConnection = NULL;
$stmt = NULL;
$numRecords = NULL;
//This connect database function can be used to connect anywhere
function connect(){
//These are variables from the other file (dblibary) - global allows access to these variables
global $user, $password, $dsn, $dbConnection; //Required to access the global variables.
try{
$dbConnection = new PDO($dsn, $user, $password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $error){
//display error message if connection doesnt work
echo "The following error occured: " . $error->getMessage();
}
}
Read Query:
function readQuery($table){
global $numRecords, $dbConnection, $stmt;
connect();
$sqlStr = "SELECT * FROM " . $table.";";
try{
$stmt = $dbConnection->query($sqlStr);
if($stmt === false){
die("Error executing the qquery: $sqlStr");
}
}
catch(PDOException $error){
echo "An Error occured: " . $error->getMessage();
}
$numRecords = $stmt->rowCount();
//Close the DB connection
$dbConnection = NULL;
}

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