My code won't render the PHP from a MySQL table - php

I've been working with this one page forever using MAMP and I can't get the PHP to render. It must be something with getting the info from the table but I can't figure out what. I'm pretty sure I have everything lined up correctly.
For a while it was just sending me back jibberish and then nothing but eventually I got it render the HTML through localhost by switching the while loop to a do-while loop so that it would run through once. So the issue must be with the connection to MySQL I'm thinking, but I don't know what.
<?php
$product_id = $_GET['id'];
$link = mysqli_connect('localhost', 'root', 'root', 'legend');
$result = mysqli_query($link, "SELECT * FROM test WHERE id=" . $product_id . "'");
while($row = mysqli_fetch_array($result)) {
?>
<html>
<head>
</head>
<body>
<div>
<p>Name: <?php echo $row['unitOne']; ?></p>
<p>Box Quantity: <?php echo $row['unitTwo']; ?></p>
</div>
</body>
</html>
<?php
}
mysqli_close($link);
?>

Try to structure your code this way and please consider all the comments below your first post. I also recommend reading this article that will clarify what prepared statements and bound parameters are: http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Remember to always construct your HTML markup correctly. There should never be more than one open and close tag for html, head and body. And if you do have more that can surely mess things up for you.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cart</title>
</head>
<body>
<?php
$query = "SELECT * FROM products WHERE product_id = ?"; //for security we will be using prepared statements
$stmt = $link -> mysqli -> prepare($query); //$link contains your database connection
$stmt -> bind_param('i', $id); //$id contains a product id the "i" will define it as an integer
$stmt -> execute();
$result = $stmt -> fetch_result();
while($row = $result -> fetch_assoc()){ //loop out the results
echo '<div>';
echo '<p>Name: '.$row['unitOne'].'</p>';
echo '<p>Box Quantity: '.$row['unitTwo'].'</p>';
echo '</div>';
}
?>
</body>
</html>

Related

Can't display table contents that contain URL's from database

I'm a student using NetBeans to create very basic webpage(s) using HTML, PHP and SQLite. So far, everything is fine. The problem I have is that images aren't displayed on the moviedetails.php page. Everything else including the titles, ratings and description for each table entry works fine. (I am retrieving rows from a database table.) Here is my code:
(This is very new to me, so if it's a simple mistake, sorry for wasting your time :/)
Index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$pdo = new PDO('sqlite:movies.db'); //Import SQLite database "movies.db" to a Var
$query = $pdo->query("SELECT * FROM movie");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
//For each id number in db, echo a hyperlink containing that ID's title and
echo '' . htmlentities($row['title']) . '';
echo '<br>';
}
?>
</body>
moviedetails.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$pdo = new PDO('sqlite:movies.db'); //Using movies.db
$query = $pdo->prepare("SELECT * FROM movie WHERE id=:id"); //Prepare this statement
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); //GET INPUT from Variable 'id' and FILTER anything which isn't a number
$query->bindParam(':id', $id, PDO::PARAM_INT); //Bind :name 'id' to a $id variable
$query->execute(); //Execute the prepared statement
$row = $query->fetch(PDO::FETCH_ASSOC); //Fetch next row of results
//var_dump($row);
//display title, description and rating
echo '<h1>'.htmlentities($row['title']).'</h1>'; //Echo 'Title' from db into a heading
echo ''; //Echo 'image from db into a link
echo '<p>'.htmlentities($row['description']).'</p>'; //Echo 'description' from db to paragraph
echo '<p>Rating: '. htmlentities($row['rating']).'</p>'; //Echo 'rating' from db to paragraph
?>
</body>
Here is my database in an image, as this is the easiest way to show you:
http://i.cubeupload.com/TBI5Fv.png
Here is one of the webpages that should diplay a link. However, it contains only the other table fields:
http://i.cubeupload.com/1tcfsU.png
The strange thing is, it doesn't give me any errors, so I don't know where I'm going wrong.
Hope someone can help :)
Your <a> tag is empty, so it's invisible.
echo '';
You should put some content that will be displayed as a link like this:
echo 'THIS IS LINK TO IMAGE';
If you want to display the image itself instead of a link, you should use <img> tag like this:
echo '<img src="'.htmlentities($row['image']).'"/>';

How to get data from a MySQL database and insert it into text

I've been working on a website of mine- it's a shop for different items (it's also my first website). I just got done with the HTML/CSS part of the website but I want to make it more dynamic and easier to edit without having to change multiple pages at once. One way I figured I could do this and also make it easier to implement a website search is by having the names and prices of the items in a database and having PHP code retrieve the name and price and insert it underneath the image of the item. Unfortunately, I have absolutely no idea how to go about this. I've tried looking for other people with similar questions but none of them seem to be specifically what I'm looking for. I'll put my PHP code below and then I'll put some html code that shows where I want to put the information.
<?php
$servername = "localhost";
$username = "root";
$password = "testpw";
$dbname = "testdb";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
}
$sql = "SELECT id, name, price FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo " " .$row["id"]. " " .$row["name"]. " " .$row["price"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
So that's the PHP code that I use to get the information for each item. The problem though is that it gets the information for every item and displays it at once. I want the code to check for the ID of the item and then retrieve the stats about it and display them. This means if I want to rearrange items in the shop I only have to change the ID- which makes it much much easier for me to manipulate the shop and the items in it. Below is the HTML code for the items.
<div id="images">
<figure>
<img class="gunimage" id="(THIS IS THE ID USED TO GET THE INFO)" src="idk.png" width="225" height="190" alt="">
<figcaption><h3>Name: (INSERT NAME HERE USING PHP) </h3></figcaption>
<figcaption><h5>Price: (INSERT OTHER PRICE HERE)/month</h5></figcaption>
<figcaption><div id="tfbutton5"><form action="buy.html"><input type="submit" value="Rent" class="tfbutton5"></form></figcaption>
</div>
</figure>
</div>
I labeled where I want the info to go, and I want to have the ID thing so the PHP code knows what item it is. I know both codes work separately, as I've tested both of them many times. Sorry if my question is really long, I wanted to make it as specific as possible so it's clear what my problem is. Please excuse if my code requires a lot of changes to make applicable in the situation I'm describing, as I only could figure out how to make something that lists out the info for every item. Any help would be appreciated. Thank you.
If you wanted to do something more you could put in a file called
'connection.php' or something more descriptive
try {
$servername = 'localhost';
$username = 'root';
$password = 'testpw';
$dbname = 'testdb';
$db = new mysqli($servername, $username, $password, $dbname);
} catch(Exception $e) {
echo $e->error_list;
exit;
}
function execute_query($con, $query, $variables) {
$stmt = $con->prepare($query);
$stmt->execute($variables);
return $stmt;
}
you could split these the top part in a connection.php while the function in a function.php file if you have more than one function.
include ('connection.php');
$id_number = $_GET['id'];
# !! NOTICE if grabbing | my understanding another page |
// filter if grabbing from GLOBAL Variable $_GET
$id = filter_var($id_number, FILTER_SANITIZE_NUMBER_INT); //take out
if not grabbing from outside source.
$con = $db;
try {
$query = 'SELECT t.id as id , t.name as name, t.price as price
FROM items as t
WHERE t.id = :id';
$variables[':id'] = $id;
$items = execute_query($con, $query, $variables);
}catch(mysqli_error_list $e) {
echo $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="images"><!-- i am guessing you want it within this div-->
<?php if(isset($item)) { ?>
<?php foreach ( $items as $item) { ?>
<figure>
<img class="gunimage" id="<?php echo $item['id']; ?>"
src="idk.png" width="225" height="190" alt="<?php echo $item['name'];
?>">
<figcaption><h3>Name: <?php echo $item['name']; ?> </h3>
</figcaption>
<figcaption><h5>Price: <?php echo $item['price']; ?> </h5>
</figcaption>
<figcaption>
<!-- instead of a id tfbutton5 needs to be a class otherwise your
going to have an issue here when it loops, you will have an error-->
<div class="tfbutton5"><form action="buy.html"><input
type="submit" value="Rent" class="tfbutton5"></form>
<!--also, not sure why you have an Id and a class named exactly
identical but it is bad practice. sorry do not do it. -->
</figcaption>
</div>
</figure>
<?php } ?>
<?php } ?>
</div>
</body>
</html>
if you wanted an image source, you would need to enter that into a database and connect your Items table to an Image table with that table having say..rows id, image, and item-id. then use the item-id as a point between the item and the image

MySQL returning broken images

over the last couple of days I've been working on a application that let's a user upload a image and store the image in my filesystem and the file path in my database. I'm almost done but i have come across a brick wall.
The image gets uploaded to my filesystem and the file path stored in my database just fine. put when i go to the page that displays the images. it returns them as
"broken images"
here's the code that is giving me trouble
<?php
error_reporting (E_ALL ^ E_NOTICE);
session_start();
$uname = $_SESSION['username'];
$userid = $_SESSION['id'];
?>
<!DOCTYPE html>
<html>
<head>
<title>OurFile's Page</title>
</head>
<body>
<?php
require("pdoconn.php");
//img_path is the column in my DB that holds the image URL.
$stmt = $conn->prepare("SELECT img_path FROM ourimages");
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_BOTH))
{
echo '<br><img src="' . $result['img_path'] . '" />';
}
$conn = null;
?>
</body>
</html>
any help would be appropriated.
Thank you for your future responses
i edited the code. using ed and jay's suggestions...but its still
output the same result
You can't do this:
<img src="<?php echo $value; ?>" />
because you're using $value to loop over every column in the table. The src attribute needs to be a URL, but I'm guessing only one column in your ourimages table holds a URL. You're outputting an image for every column thanks to this:
$stmt = $conn->prepare("SELECT * FROM ourimages"); // gets every column
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_BOTH);
foreach ($result as $value) // uses every column
{
The simple fix is to change your SQL:
$stmt = $conn->prepare("SELECT whateverColumnHasTheURL FROM ourimages");
Then use that column like this:
<img src="<?php echo $result->whateverColumnHasTheURL; ?>" />
Or, you can use the SELECT * ..., but just use the one column in the <img> tag:
$stmt = $conn->prepare("SELECT * FROM ourimages");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_BOTH);
echo "<br>";?> <img src="<?php echo $result->whateverColumnHasTheURL; ?>" /><?php
Note: If you're actually trying to loop over the rows, you need to put $stmt->fetch in a loop, as in while ($result = $stmt->fetch(PDO::FETCH_BOTH);) { echo... }
Using a foreach loop to output the results of the query is an interesting way of doing things. Most folks use a while loop like this:
while($result = $stmt->fetch(PDO::FETCH_BOTH))
{
echo '<br><img src="' . $result['column_with_image_path'] . '" />';
}
Since you're selecting all of the columns from your table you need to be specific about the identifier you use in the image tag.

Warning: mysqli_query(): Couldn't fetch mysqli [duplicate]

This question already has an answer here:
mysqli_query(): Couldn't fetch mysqli error [duplicate]
(1 answer)
Closed 2 years ago.
I am new to PHP and not familiar with many of its rules, so this could possibly be a stupid question.
I have a database with top level categories and subcategories combined into one table. I want to first print out all the top-level categories, and then printout the subcategories associated with that category.
Here is my code:
<?php
session_start();
include_once "/mysqli_connect.php";
$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
mysqli_close($conn);
?>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<div id="wrap" class="animate">
<?php
while ($categories = mysqli_fetch_array($categories0, MYSQLI_ASSOC)) {
$catecory_name = $categories['category'];
echo '
<div class="content">
<div class="content_container no_padding">
<div class="content_container header">
<p>'.$categories['category'].'</p>
</div>
';
$subcategories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'subcategory'");
while ($subcategories = mysqli_fetch_array($subcategories0, MYSQLI_ASSOC)) {
echo $subcategories['category'];
//mysqli_free_result($subcategories0);
}
echo '
</div>
</div>
';
}
?>
</div>
</div>
</body>
</html>
Here is the connection script:
<?php
DEFINE ('DB_USER', '*');
DEFINE ('DB_PASSWD', '*');
DEFINE ('DB_HOST', '*');
DEFINE ('DB_NAME', '*');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWD, DB_NAME);
if(!$conn){
die('Database connection error');
}
echo '<!-- Connected to database -->'
?>
It returns the following error:
Warning: mysqli_query(): Couldn't fetch mysqli
When both queries are above the doctype everything is fine, but when the second query is below the doctype the error occurs.
The first query always runs without problems, it is the second one that returns the error.
I can't seem to figure out what is going on, if anyone can help me that would be appreciated.
You forget to close your while loop. check comment in line where you need to close it.
<?php
$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
?>
<!DOCTYPE html>
<?php
while ($categories = mysqli_fetch_array($categories0, MYSQLI_ASSOC)) {// need to close your loop
$catecory_name = $categories['category'];
echo '
<div class="content">
<div class="content_container header">
<p>'.$categories['category'].'</p>
</div>
';
}// close here
$subcategories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'subcategory'");
// The above line is where the error occurs
while ($subcategories = mysqli_fetch_array($subcategories0, MYSQLI_ASSOC)) {
echo $subcategories['category'];
}
?>
UPDATED
Remove close connection from top because after it your query will not execute. Your connection variable is vanished after your connection is closed.
<?php
session_start();
include_once "/mysqli_connect.php";
$categories0 = mysqli_query($conn, "SELECT * FROM categories WHERE type = 'category'");
?>
Today I have phased the same problem. But There is little mistake that you did in code.
You are trigger select statement this:
See. You are now closing the connection with mysqli_close($conn);
and then in while loop you are fetching data. If connection has been closed then how can php take data from mysql table?
Just remove mysqli_close($conn); statement and run.
In the last line you can put this code. After all the operation.

PHP - How to Create Dynamic URLs?

I've scoured the web for a tutorial about this simple task, but to no avail. And so I turn to you helpful comrades. Here's what I need to do:
I have a MySQL database with an Events table. I need to create a PHP web page with a list of the Event titles, and each title must be a link to the full details of the Event. But I want to avoid having to create a static page for each event, primarily because I don't want the data entry volunteer to have to create these new pages. (Yes, I realize that static pages are more SEO friendly, but I need to forego that in this case for the sake of efficiency.)
I've seen PHP url syntax with something like this:
pagename.php?id=20
but I don't know how to make it work.
Any and all help greatly appreciated.
Thanks!
Kip
This is basic php. You would simply query the DB for the event details before the page headers are written and write the html accordingly.
The first thing I would ask you is if you know how to connect to your database. From there, you query based on the $_GET['id'] value and use the results to populate your html.
Not to be rude, but the question itself suggests you're new to PHP, right? So in order to provide a solution that works we might want to know just how far you got.
Also, you can rewrite your dynamic urls to appear like static ones using apache's mod_rewrite. It's probably a novice level thing if you're interested in "pretty" url's.
MODIFIED ANSWER:
In your loop you would use the id from the query result (assuming your primary key is id)...
while($field = mysql_fetch_array($result)) {
echo "<p class='date'>";
echo $field['month']." ".$field['day'].", ".$field['year'];
echo "</p>";
echo "<h3>";
echo ''.$field['event_name'].'';
echo "</h3>";
}
Then on somepage.php you would use the get var id to pull the relevant info...
$result = mysql_query("SELECT * FROM `calendar` WHERE `id` = '".mysql_real_escape_string($_GET['id'])."');
don't forget to look into mysql_real_escape_string() for cleaning entries.
It's wise to take extra care when you are using $_GETvariables, because them can be easily altered by a malicious user.
Following with the example, you could do:
$foo = (int)$_GET['id'];
So we are forcing here the cast of the variable to a integer so we are sure about the nature of the data, this is commonly used to avoid SQL injections.
lets say you have the php file test.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("db", $conn);
$id = $_GET['id'];
$sql = "select * from table where id = $id";
$result = mysql_query($sql, $conn);
if ($result){
$row = mysql_fetch_row($result);
$title = $row[0];
$content = $row[1];
}
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $title ?></h1>
<p><?php echo $content ?></p>
</body>
</html>
a dynamic page would be something like that..
Here is the pertinent code for extracting a list of events in November from a table named calendar, with each event having a link to a page called event.php and with the event's id field appended to the end of the url:
$result = mysql_query("SELECT * FROM calendar WHERE sort_month='11'");
while($row = mysql_fetch_array($result))
{echo
"<a href='event.php?id=".$row['id']."'>".$row['event_name']."</a>"
;}
And here is the pertinent code on the event.php page. Note the row numbers in brackets depends on the placement of such in your table, remembering that the first row (field) would have the number 0 inside the brackets:
$id = $_GET['id'];
$sql = "select * from calendar where id = $id";
$result = mysql_query($sql, $con);
if ($result){
$row = mysql_fetch_row($result);
$title = $row[12];
$content = $row[7];
}
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $title ?></h1>
<p><?php echo $content ?></p>
</body>
</html>
This works for me, thanks to the help from those above.
$foo=$_GET['id'];
in your example $foo would = 20

Categories