I have a products page where 8 product images are in a list which is being populated by images stored in a MySQL database. The images all have associated ID's in which a price, product name, and description is also associated with the same ID.
The idea behind what I am trying to do is; When a user clicks on one of the 8 product images, they will be redirected to a "checkout" page which will display the same image, plus all the information that is also stored under that ID in the database.
As of right now, I have the checkout page URL including the ID of the image (url.com/checkout.php?id=1) and I was hoping to find a way to get all the information stored under that ID in the URL to be displayed where called on the page.
Here is my php code that displays the images in the list on the products page:
// Grab the data from our template table
$sql = "select * from templates";
$result = mysql_query($sql) or die ("Could not access DB: " . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<li>";
echo "<a class=\"caption\" href=\"purchase.php?id=\"" . $row['id'] . ">";
// Note that we are building our src string using the ID from the database
echo "<img src=\"http://URL-REMOVED.com/file_display.php?id=" . $row['id'] . "\" />";
echo "<span>";
echo "<big>" . $row['name'] . "</big>";
echo $row['description'];
echo "</span>";
echo "</a>";
echo "</li>";
}
Here is the php code that is supposed to gather the information of the clicked product (but doesn't):
if (isset($_GET['id']))
$id=$_GET['id'];
else
$id=1;
if (isset($_GET['action']))
$action=$_GET['action'];
else
$action="empty";
switch($action){
case "add":
if($_SESSION['cart'][$id])
$_SESSION['cart'][$id]++;
else
$_SESSION['cart'][$id]=1;
break;
case "remove":
if($_SESSION['cart'][$id])
{
$_SESSION['cart'][$id]--;
if($_SESSION['cart'][$id]==0)
unset($_SESSION['cart'][$id]);
}
break;
case "empty":
unset($_SESSION['cart']);
break;
}
//Display Cart
if(isset($_SESSION['cart'])) {
$total=0;
foreach($_SESSION['cart'] as $id => $x) {
$result=mysql_query("select image,name,price,description from templates WHERE id=$id");
$myrow=mysql_fetch_array($result);
$image=$myrow['image'];
$name=$myrow['name'];
$price=$myrow['price'];
$description=$myrow['description'];
}
}
And here is the actual HTML/PHP where the information is supposed to be displayed:
<a class="caption" href="checkout.php">
<img src="http://URL-REMOVED.com/file_display.php?id=<?php $myrow['id'] ?>"/>
<span>
<big>
<strong><?php $myrow['name'] ?></strong>
</big>
<div class="price"><?php $myrow['price'] ?></div>
</span>
</a>
</div>
<div id="info_form_container">
<div class="product_info">
<div class="control-group">
<strong>Template Name:</strong>
<?php $myrow['name'] ?>
</div>
<div class="control-group">
<strong>Template Description:</strong>
<?php $myrow['description'] ?>
</div>
<div class="control-group">
<strong>Template Price: </strong>
<?php $myrow['price'] ?>
</div>
</div>
I guess I'm not really sure if this is even the best method to take? But I definitely want to have the images stored in the database and I definitely want to call them using the ID...
How can I achieve this? Where am I wrong in my code?
EDIT: I do not think I understood your question the first time. Try using this to generate your list of products, updating the connection information. If this works, use the methods below to sanitize your variables and store your connection information elsewhere
<?php
$mysqli_connection = new mysqli("localhost", "username", "password", "database");
$sql = "SELECT * FROM templates";
$result = $mysqli_connection->query($sql);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
echo '<li>';
echo '<a href="purchase.php?id='.$id.'" class="caption">';
echo '<img src="http://URL-REMOVED.com/file_display.php?id='.$id.'" />';
echo '<span>';
echo '<big>'.$name.'</big>';
echo $description;
echo '</span>';
echo '</a>';
echo '</li>';
}
?>
OG Answer:
I think what you are doing is just fine.. It is the method I use (although mine seems a little neater). Run your PHP functions to query your MySQL database using the ID you get, and just start dumping the information you get into your site. To help with readability and cut down on spelling confusions, it might help to assign your $myrow['whatever'] results into variables to echo out, but that is more cosmetic to me than anything.
To fix up your MySQL things and use mysqli, try out the following:
$sql = "SELECT * FROM templates";
$result = $mysqli_connection->query($sql);
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo "<li>";
echo "<a class=\"caption\" href=\"purchase.php?id=\"" . $row['id'] . ">";
// Note that we are building our src string using the ID from the database
echo "<img src=\"http://URL-REMOVED.com/file_display.php?id=" . $row['id'] . "\" />";
echo "<span>";
echo "<big>" . $row['name'] . "</big>";
echo $row['description'];
echo "</span>";
echo "</a>";
echo "</li>";
}
And try to sanitize your information using:
$my_stuff = mysqli_connection->real_escape_string($row['that_stuff']);
Also, you know you can use single quotes ('') around your echo statements if you want to, right? May make it easier that escaping all of the double quotes..
So in full, this is probably a rough example of what I would do but I would split it up into functions and maybe create some global variables (such as the connection itself):
<?php
$mysqli_connection = new mysqli("localhost", "username", "password", "database");
$sql = "SELECT * FROM templates WHERE id=$id";
$result = $mysqli_connection->query($sql);
// I'm assuming there is only one entry, so no while loop for me
$row = $result->fetch_array(MYSQLI_ASSOC);
$your_title = $mysqli_connection->real_escape_string($row['title']);
$path_to_image = $mysqli_connection->real_escape_string($row['image']);
$description = $mysqli_connection->real_escape_string($row['description']);
$price = $mysqli_connection->real_escape_string($row['price']);
?>
<html>
<head></head>
<body>
<h3><?php echo $your_title; ?></h3>
<img src="<?php echo $path_to_image; ?>" />
<ul>
<li>Description: <?php echo $description; ?></li>
<li>Price: <?php echo $price; ?></li>
<!-- etc..-->
Related
When I run the following file I get the database data i.e it prints it out on the website so I know my connections are good.
<html>
<?php include 'config.php'?>
<?php include 'header.php'?>
<?php
$sql = "SELECT name, image FROM images";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo $row["name"], $row["image"];
}
?>
</div>
</html>
However when I try and format the results like below
<html>
<?php include 'config.php'?>
<?php include 'header.php'?>
<?php
$sql = "SELECT name, image FROM images";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo <div id = "bookbar">
<img src= "$row['image']" alt = "image">
<p> $row['name'] </p>
</div>
}
?>
</div>
</html>
it doesn't work. Can anyone help me fix the code?
Maybe try this your code didn't close/open the php tags properly also don't echo like that
<?php include 'config.php'?>
<?php include 'header.php'?>
<?php
$sql = "SELECT name, image FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<div id = "bookbar">
<img src= "<?php echo $row['image'] ?>" alt = "image">
<p><?php echo $row['name']; ?></p>
</div>
<?php
}
}
$conn->close();
?>
If you want to echo something out
Its better to close on open the php tags like so
PHP goes here
?>
HTML goes here
<?php
PHP goes here
And if you want to echo something inside the HTML just do this
<span> <?php echo "something" ?> </span>
much easier and makes the code easier to read.
change your echo statement to -
echo '<div id = "bookbar"><img src= "' . $row['image'] . '" alt = "image"><p>'. $row['name'] .'</p>'
Your issue is a syntax problem - you can't use echo like that, it has to echo a string variable. You should be seeing an error message about it.
You could keep the echo statement and put all the HTML inside a string, and concatenate (or interpolate) the PHP data into it. But IMO the easiest thing here in terms of readability and maintenance is to step out of the PHP tags, print the HTML, embed some PHP tags in it for the variables, and then step back in again to continue with the code. It makes the HTML far easier to understand:
?>
<div id="bookbar">
<img src="<?php echo $row['image'] ?>" alt="image">
<p><?php echo $row['name'] ?></p>
</div>
<?php
When you are in php mode you should echo strings as php variables wrapped with single quotes:
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo '<div id = "bookbar">';
echo '<img src="' . $row['image'] . '" alt = "image">';
echo '<p>' . $row['name'] . '</p>';
echo '</div>';
}
I am hoping someone can assist with a dynamic query in PHP. The first page below is a page which displays a number of items from MySQL. Once an item is clicked on it goes to another page which queries the database to bring up the selected product details. The page displaying the items a user can select from works fine, but the page displaying the item clicked on only works if I remove the WHERE clause, but of course it is no longer dynamic then. The error statement is suggesting that the syntax is not right for the version, yet it works on the other page. Using MySQL 5.6.17 and PHP 5.5.12.
Can anyone see where it is that I have gone wrong here please?
---------------------------------
Main Page (functions as expected)
<?php
ini_set('display_errors', '0');
$message = '';
$db=new MySQLi('localhost', 'someone', 'xxx','abc');
if ($db->connect_error) {
$message = $db->connect_error;
} else {
$sql = 'SELECT * FROM items';
$result = $db->query($sql);
if ($db->error) {
$message = $db->error;
}
}
?>
<!--other parts of the site--->
<?php if ($message) { ?>
<h2 class="inline_block">Sorry, there seems to be a problem.</h2>
<?php } else { ?>
<div>
<?php
$i = 0;
while ($row = $result->fetch_assoc()) {
if ($i % 4 === 0) { ?>
<div>
<ul>
<?php } ?>
<li> <a href="includes/details.php?id=<?php echo $row['itemID']; ?>"> <img src="img/<?php echo $row['image']; ?>" alt="<?php echo $row['alt']; ?>" height="150" width="150">
<p><?php echo $row['product']; ?></p>
<p class="reset">From $<?php echo $row['water']; ?></p></a> </li>
<?php $i++;
if ($i % 4 === 0) { ?>
</ul>
</div>
<?php } // end if
} // end of loop ?>
</div>
</div>
<?php } // end of page ?>
</div>
<!--other parts of the site--->
-----------------------------------------------------------------
Dynamic Page (returns an SQL error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1". Line 1 is the same first line as showing below. This is also used in the previous page without issue. When the WHERE clause is removed from the SQL query it works but is no longer dynamic. )
<?php
ini_set('display_errors', '0');
$message = '';
$db=new MySQLi('localhost', 'someone', 'xxx','abc');
if ($db->connect_error) {
$message = $db->connect_error;
} else {
$sql = 'SELECT * FROM items WHERE xitemID=' . $db->real_escape_string($_GET['xitemID']);
$result = $db->query($sql);
if ($db->error) {
$message = $db->error;
} else {
$row = $result->fetch_assoc();
}
}
?>
<!--other parts of the site--->
<ul>
<li>Home</li>
<li>Things</li>
<li>Mixeda</li>
<li><?php echo $row['product']; ?></li>
</ul>
</div>
<div id="col_1" role="main">
<?php if ($message) { ?>
<p> ERROR</p>
<?php echo "<p>$message</p>";
} else { ?>
<h2 class="inline_block"><?php echo $row['product']; ?></h2>
<p class="figure"><img src="../img/<?php echo $row['image']; ?>" alt="<?php echo $row['alt']; ?>" width="200" height="200">Price from $<?php echo $row['product']; ?></p>
</div>
<div id="col_2">
<h3>Details</h3>
<p><?php echo $row['details']; ?></p>
</div>
<?php } ?>
<!--other parts of the site--->
Note you need to put single quotes around the item in xitemID='itemHere':
$sql = "SELECT * FROM items WHERE xitemID='" . $db->real_escape_string($_GET['xitemID']) . "'";
That should fix your problem as long as $_GET['xitemID'] is defined.
You are concatenating an escaped
value outside your string.
$sql = 'SELECT * FROM items WHERE xitemID=' .
$db->real_escape_string($_GET['xitemID']);
This looks like a valid action however when xitemID is a character value, you still need to enclose it in quotes yourself.
Better is to use a prepared statement:
You are using MySQLi already, so:
$sql="SELECT * FROM items WHERE xitemID=?";
$pstmt=$db->prepare_statement($sql);
$pstmt->bind_param("s",$_GET['xitemID']);
$results=$pstmt->execute();
That way php takes care of any quoting etc and prevents eventual sql injection.
I have user information coming from database on a profile page using a while loop. I want to be able to write stuff like this, $username's profile. I can't seem to figure it out. Here is my code.
<?php
//open database connection
include 'page-start.php';
include 'core/init.php';
?>
<?php
$myQuery = ("SELECT user_id, username, profile, city FROM `users` WHERE user_id = '" . mysql_real_escape_string($_GET['ID']) . "' ") or die(mysql_error());
//run query
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($result));
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
} ?>
<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/studentsupport/defines.php'; ?>
<?php include_once("head.php");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo '<div class="sixteen columns" id="user-profile">';
echo'<h2 class="username"> ' . $row['username'] . ' </h2> ';//bob's Profile
echo'<p>' . $row['city'] . '</p>'; //city: london
echo '<div class="eight columns" id="user-profile-img">';
echo'<img src="'. $row['profile'] . '"/>';
echo '</div>';
echo '</div>';
}
?>
edit: sorry I didn't explain it very well.
I want to be able to have some information come from the database and some information just as standard html for example:
<p><?php echo $username; ?>'s profile </p>
<p>city: <?php echo $city; ?> </p>
During each loop in the while, $row['username'] will have a username.
If you want to be able to get all the usernames later, add the following:
$users[] = $row['username'];
Now, Everywhere in your script $users[0] will have the 1st username, $users[1] will have the second, etc.
If you are beginner than i wil say You should use easy method now it seems okay
like You make Whole page of profile like you want
like
then you can Take your data in Variables in while Loop like that
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$profile = $row['profile'];
$name = $row['name'];//you can take as many variables as you want
$city = $row['city'];
}
then you can use these variables in html simply
<div class="sixteen columns" id="user-profile">
<h2 class="username"><?php echo $name; ?> </h2>
</div>
start like that next step like above will get easy to u :)
This may do it.
<?php include_once("head.php");
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{ ?>
<div class="sixteen columns" id="user-profile">
<h2 class="username"><?php echo $row['username']; ?></h2>
<p><?php echo $row['city']; ?></p>
<div class="eight columns" id="user-profile-img">
<img src="<?php echo $row['profile']; ?>"/>
</div>
</div>
<? } ?>
I like to catch the id of below tag in show.php file
once the link is clicked... I have already got the href name in show.php
<?php
if (isset($_GET['submit'])) {
$choice=$_GET['prod'];
$dbc=mysqli_connect('localhost','root','','online_shopping') or die('Connection Error');
$query1="SELECT name, id from ".$choice; $result1=mysqli_query($dbc,$query1) or die('Error querying Database');
echo "<h1>List of available products in your category</h1><hr>";
while($row = mysqli_fetch_array($result1)) {
$id=$row['id'];
?>
<a style="font-size:18px; text-decoration:none; text-align:center; color:#09F;" href="show.php?ref=<?php echo $row['name'];?>" id="<?php echo $id;?>"><?php echo $id;echo '.'.$row['name']; echo '</a>';
The id attribute is only used client side, so short of using JavaScript to modify the URL — you can't.
Put the data in the URL in the first place … and exercise some safety over adding data to URLs and HTML.
<a href="show.php?ref=<?php
echo htmlspecialchars(urlencode($row['name']));
?>&id=<?php
echo htmlspecialchars(urlencode($id));
?>"
id="<?php
echo htmlspecialchars($id);
?>"><?php
echo htmlspecialchars($id) . '.' . htmlspecialchars($row['name']);
?></a>
I believe you're looking for $_GET.
<?php
//show.php?ref=5&id=10
echo $_GET['ref'];
//5
echo $_GET['id'];
//10
?>
<?php echo $_GET["id"]; ?>
I have this code which produces me a number which is equal to the number of id's i've got in my database of star rating system.
This code generates me a five star voting for each id i've got, but the problem is, it generates them all in a div, while i need them specifically in different div's. let's suppose i print out in a div information for each hostess i've got, i print out their photo and name with the following code:
$sql =" select * from hostess";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo "<div id='photo'>";
echo "<div id='picture'>";
echo "<div id='scotch'><img src='images/Scotch.png'></div>";
echo "<td> <img src=foto/photo1/".$row['photo'] . "></td>";
echo "</div>";
echo "<div id='text'>";
echo '<td>'. $row['first_name_en']." ". $row['family_name_en']."</td>";
echo "</div>";
echo "</div>";
echo "<div id='photo2'>";
echo "<div id='picture'>";
echo "<div id='notes'>";
echo '<form action="index.php" method="post" >';
echo "<label>Notes</label></br><textarea>".$row['courrent_occupation'] . "</textarea></br>";
echo '<input type="submit" value="edit" name="edit"></div>';
echo "</div>";
echo "<div id='notes'>";
echo "<label>profile</label></br><textarea>".$row['profile_en'] . "</textarea>";
echo "</div>";
echo "</div>";
}
?>
</div>
Now, i've got this other php which generates me all the star ratings for all hostess id's
<?php
// include update.php
include_once 'update.php';
// get all data from tabel
$arr_star = fetchStar();
?>
<?php
// start looping datas
foreach($arr_star as $star){ ?>
<h2>Star Rater - <?php echo $star['id'];?></h2>
<ul class='star-rating' id="star-rating-<?php echo $star['id'];?>">
<?php /* getRating($id) is to generate current rating */?>
<li class="current-rating" id="current-rating-<?php echo $star['id'];?>" style="width:<?php echo getRating($star['id'])?>%"><!-- will show current rating --></li>
<?php
/* we need to generate 'id' for star rating.. this 'id' will identify which data to execute */
/* we will pass it in ajax later */
?>
<span class="ratelinks" id="<?php echo $star['id'];?>">
<li>1</li>
<li>1.5</li>
<li>2</li>
<li>2.5</li>
<li>3</li>
<li>3.5</li>
<li>4</li>
<li>4.5</li>
<li>5</li>
</span>
</ul>
<?php } ?>
What i need is to assign each hostess profile i print their system rating.
I try to insert the foreach inside the first script but it then shows me just one profile, not all profiles.
The fetchstar() code is:
function fetchStar(){
$sql = "select * from `hostess`";
$result=#mysql_query($sql);
while($rs = #mysql_fetch_array($result,MYSQL_ASSOC)){
$arr_data[] = $rs;
}
return $arr_data;
}
First, you probably shouldn't use SELECT *. That aside I would combine the two queries you have to return a multidimensional array with MySQL and then use nested for each loops to echo out the data you want.
Someone answered a similar question for me here.
Looping through MySQL left join in php vs. 2 separate queries
$sql =" select * from hostess";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
if ($lastID <> $row['id']) {
$lastID = $row['id'];
$hostess[$lastID] = array('id' => $row['id'],
'first_name_en' => $row['first_name_en'],
etc
'arr_star' => array() );
}
$hostess[$lastID]['arr_star'][] = array('star_id' => $row['star_id'] etc);
}
Then you would use nested for each statements
for each($row as $rows){
//echo your hostess information
for each ($arr_star as $star){
//echo your star rating information
}
}