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>
Related
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>";
}
}
?>
Hello i am new to working with PHP and for some reason, the code i have typed seems sound but it will not print out the result i want, can any one show me what is wrong? Thank you. The code is below:
<html>
<head>
<title></title>
</head>
<body>
<table>
<?php
require_once('DB.php');
$db = DB::connect("mysql://xxxxxxxxxx");
if(DB::iserror($db)){
die($db->getMessage());
}
$query = "select FacName from faculty where Department = 'Mathematics & Computer Science';";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
?>
</table>
</body>
</html>
The Connection works but fro security reasons i will not place the actual connection.
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
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.
this might be a really simple solution but I really can't figure it out. if i insert into my database I have to press the insert button twice for it to work.. My guess is that it has to do with my using of 2 forms in one file or just because I did it all in one file. please help me.
thanks
code:
<?php
/*require "link.php";*/
?>
<html>
<head>
<!--<link rel="stylesheet" type="text/css" href="css.css">--> <!-- verwijzing naar je css -->
<!--<script type="text/javascript" src="js.js"></script>-->
</head>
<header>
</header>
<article>
<div id="cards">
<?php
$host = "localhost";
$user = "root";
$pwd = "";
$db_name = "flashcards";
$link = mysqli_connect($host, $user, $pwd, $db_name)or die("cannot connect");
$array = array();
$IDarray = array();
ini_set('display_errors', 1);
error_reporting(E_ALL);
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{
echo "<tr id='".$rows['ID']."'><td>".$rows['Question']."</td><td><input type='text' name='Answer[]' id='V".$rows['ID']."'></input></td></tr>";
$array[] = $rows["Answer"];
$IDarray[] = $rows["ID"];
}
echo "</table><input type='submit' name='submit'></input></form>";
$i = 0;
$count = sizeof($IDarray);
if(!empty($_POST['Answer']))
{
foreach($_POST['Answer'] as $answer)
{
if (isset($_POST['Answer'])) {
if ($answer == $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='green'; document.getElementById('V".$IDarray[$i]."').value='".$array[$i]."'</script>";
}
elseif ($answer !== $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='red'; document.getElementById('V".$IDarray[$i]."').value='".$answer."'</script>";
$count = $count-1;
}
$i ++;
}
}echo $count." van de ".sizeof($IDarray)." goed";
if ($count == sizeof($IDarray))
{
header('Location: http://localhost:1336/php3/');
}
}
echo "</br></br>insert";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
echo "<tr><td>vraag</td><td><input type='text' name='vraag'></input></td><td>antwoord</td><td><input type='text' name='antwoord'></input></td></tr>";
echo "</table><input type='submit' name='submitinsert' value='insert'></input></form>";
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
?>
</div>
</article>
<footer>
</footer>
</html>
The problem is you're processing the form submission in the same script as the one that generates the form. Couple that to the fact that you firsT query the DB, generate a form with what you've already stored, and then add whatever data the user may have posted, you'll never see the data you've added show up the first time 'round you submit the form.
Either move the insert queries to the top (before generating the form), or separate concerns
Let me show you what I mean:
//don't OR DIE
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{//build form here
}
/*
CODE HERE
*/
if ($_POST['vraag'] != "") {
//insert here, after form is generated
}
So the data you query cannot, yet, contain the submitted form data.
There are some other issues with the code, though, like or die: don't do that. Be consistent with your coding style (allman brackets + K&R in the same script is messy). Properly indent your code and this:
if ($_POST['vraag'] != "") {
}
should be:
if (isset($_POST['vraag'])) {
}
You're comparing a key of an array that may not exist to an empty string, whereas you should check if that array key exists. Use isset.
I could go on a bit, but I'll leave it at that for now. Just one more thing: again -> separrate concerns! The presentation layer (the output: HTML and such) should not contain DB connection stuff. That should be done elsewhere.
Process your form either asynchronously (as whatever is submitted gets added to the table that is already there) using AJAX, or at least, use a separate script. Having 1 script doing all the work will soon leave you crying over a mess of spaghetti code
Its not submitting twice, actually its not loading the data after insertion,
Try adding
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
echo "are you sure?";
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
before
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or
die(mysqli_error($link));
this will select your records after the current record is saved.