php and mysql, how to sort inside while loop - php

I need to sort while loop by row named 'sort' or $udaj[5] My code below.
<?php
$query = "SELECT * FROM yees where category = 1";
$vysledek = mysqli_query($my_link, $query);
while ($udaj = mysqli_fetch_array($vysledek)):
echo "<a href='detail.php?id=" . $udaj[0] . "' class='yee'>";
echo "<img src='" . $udaj[3] . "' alt='' class='avatar'>";
echo "<div class='basic-info'>";
echo "<div class='name'>" . $udaj[1]."</div>";
echo "<div class='tagline'>" . $udaj[6] . "</div>";
echo "</div>";
echo "<img src='" . $udaj[4] . "' alt='' class='cover'>";
echo "<div class='clear'> </div>";
echo "</a>";
endwhile;
?>
I tried this, but doesnt work.
$query = "SELECT * FROM yees where category = 1 ORDER BY sort ASC";
Could the problem be that my col is called "sort" which is not allowed since its a keyword??

You should go back to using the SQL to sort for you. I don't think there's anything wrong there.
It is also cleaner to use the proper row names, as mysqli_fetch_array will return the values in an associated array as well as a numbered index array.
Also print HTML out in heredoc format; its much easier to read than multiple echo statements
echo <<<EOF
<a href='detail.php?id={$udaj['col0']}' class='yee'>
<img src='{$udaj['col3']}' alt='' class='avatar'>
<div class='basic-info'>
<div class='name'>{$udaj['col1']}</div>
<div class='tagline'>{$udaj['col6']}</div>
</div>
<img src='{$udaj['col4']}' alt='' class='cover'>
<div class='clear'> </div>
</a>
EOF;

Related

Returning SQL data within an image tag using PHP

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>';
}

Div not looping correctly

I'm trying to get my code to display multiple divs. But seems to only display one div correctly.
<?php
// database connection
//$result = mysqli_query($con,"SELECT * FROM test WHERE field5='Cohen'");
echo " <div id='1'>";
while($row = mysqli_fetch_array($result))
{
echo "<div class='tutorName'>" . $row['field1'] . "</div>";
echo "<div class='tutorPrice'>" . $row['field2'] . "</div>";
echo "<div class='tutorInstitution'>" . $row['field3'] . "</div>";
echo "<div class='tutorLocale'>" . $row['field4'] . "</div>";
echo "<div class='tutorPhone'>" . $row['field5'] . "</div>";
}
echo "</div>";
mysqli_close($con);
?>
I want the following to loop and over using the fields above (field1, feild2, etc):
<div id='' name='' class="column threecol">
<div class="course-preview premium-course">
<div class="course-image">
<img src="img.png" />
<div class="course-price">
<div class="corner-wrap">
<div class="corner"></div>
<div class="corner-background"></div>
</div>
<div class="price-text"><span class="amount">PerHour</span></div>
</div>
</div>
<div class="course-meta">
<header class="course-header">
<h5 class="nomargin">TutorName </h5>
<div class='gender'>Gender: </div>
<div class='price-range'>Price Range: </div>
<div class='institute'> Institute: </div>
</header>
</div>
</div>
</div>
Is your $result line really commented out in the real code? Or did you just add that comment for the example? If it's commented-out in the code you're testing, then that's probably the issue.
you want this? , 1 div wrap all content like table tr
$i=1;
while($row = mysqli_fetch_array($result))
{
echo " <div id='{$i}'>";
echo "<div class='tutorName'>" . $row['field1'] . "</div>";
echo "<div class='tutorPrice'>" . $row['field2'] . "</div>";
echo "<div class='tutorInstitution'>" . $row['field3'] . "</div>";
echo "<div class='tutorLocale'>" . $row['field4'] . "</div>";
echo "<div class='tutorPhone'>" . $row['field5'] . "</div>";
echo "</div>";
$i++;
}

getting MySQL ID from URL to display information on page

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..-->

Php foreach echo issue

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
}
}

while inside of another while in PHP using MySQL

I need to do the following - get the list of all artists from the database and print them on a page. But besides of that, I need to make another query to the "albums" table and get the albums of each artist and print the images under each artist description. The code I've written is as follows:
require('db.php');
$query = "SELECT * FROM artists";
$result = mysql_query($query);
$artist_id = $result[id];
$artist_name = $result[name];
$artist_surname = $result[surname];
$artist_email = $result[email];
$artist_about = $result[about];
$artist_photo = $result[photo];
while(list($artist_id, $artist_name, $artist_surname, $artist_email, $artist_about, $artist_photo) = mysql_fetch_row($result)) :
print "<div class='row'>";
print "<div class='artists_left'>";
print "<div class='gallery_cont'><a href='#'><img src='timthumb.php?src=images/artists/$artist_photo&w=240&h=318' alt='$artist_name' /></a></div>";
print "</div>";
print "<div class='artists_right'>";
print "<div class='artist_title_cont'><span class='model'>Художник:</span><span class='name'>$artist_name $artist_surname</span><span class='mypage'>Личная почта:</span><a href='#' class='mypage'>$artist_email</a></div>";
print "<div class='artist_title_cont' style='margin-top:20px;'><span class='name'>$artist_about</span></div>";
print "<ul class='artists'>";
$albums_query = "SELECT id, title_photo, dirname FROM albums WHERE master = $artist_id";
$albums_result = mysql_query($albums_query);
$album_id = $albums_result[id];
$album_photo = $albums_result[title_photo];
$album_dirname = $albums_result[dirname];
while(list($album_id, $album_photo, $album_dirname) = mysql_fetch_row($result)) :
print "<li><a href='#'><img src='galleries/$album_dirname/$album_photo' alt='image' /></a></li>";
endwhile;
print "</ul>";
print "<a href='#' class='seemore_portfolio'>все работы мастера ></a>";
print "</div>";
print "</div>";
endwhile;
mysql_close($connect);
The outer query works fine, but the inner one - does not. Could anybody help me to figure this out?
Thanks in advance.
Change the second $result to $albums_result
You can also consider writing the whole thing like this...
<?
require('db.php');
$query = "SELECT * FROM artists";
$result = mysql_query($query);
while(list($artist_id, $artist_name, $artist_surname, $artist_email, $artist_about, $artist_photo) = mysql_fetch_row($result))
{
$li = '';
$albums_query = "SELECT id, title_photo, dirname FROM albums WHERE master = $artist_id";
$albums_result = mysql_query($albums_query);
while(list($album_id, $album_photo, $album_dirname) = mysql_fetch_row($albums_result))
{
$li .= "<li><a href='#'><img src='galleries/$album_dirname/$album_photo' alt='image' /></a></li>";
}
echo "<div class='row'>
<div class='artists_left'>
<div class='gallery_cont'><a href='#'><img src='timthumb.php?src=images/artists/$artist_photo&w=240&h=318' alt='$artist_name' /></a></div>
</div>
<div class='artists_right'>
<div class='artist_title_cont'><span class='model'>Художник:</span><span class='name'>$artist_name $artist_surname</span><span class='mypage'>Личная почта:</span><a href='#' class='mypage'>$artist_email</a></div>
<div class='artist_title_cont' style='margin-top:20px;'><span class='name'>$artist_about</span></div>
<ul class='artists'>
$li
</ul>
<a href='#' class='seemore_portfolio'>все работы мастера ></a>
</div>
</div>";
}

Categories