Get data from database and use loop in php - php

I am working on college project and i am stuck at the moment.
I have a table and it have multiple records. Records are saved by user. I want to show all data stored by specific user on webpage (under a separate div).
I am able to fetch all data from database by using below code.
$prj= mysql_query("select * from project where uid=$uid");
$record= mysql_fetch_assoc($prj);
$project_name = "$record['project_name']";
$short_dis= "$record['short_dis']";
$poster= "$record['poster']";
mysql_close($prj);
Here are some php code.
<div class="media services-wrap55 wow fadeInDown">
<img class="img-responsive" src="uploads/poster/photo-original_827156899.jpg"><br>
<h4 class="media-heading">second project for testing</h4>
<p> by user</p>
<p> second project for testing second project for testing second project for testing second project for testing.</p>
<a class="" href="iska-link.html">More ... </a>
<p>
<div id="progressBar2" class="tiny-green"><div></div></div><p>
<div class="counter-inner"><div id=example1" data-countdown="07/02/2015 00:11:00"></div></div><p>
<div class="col-sm-11 text-right">
<div class="entry-meta">
<span><i class="fa fa-comment"></i> 2 Comments </span>
<span><i class="fa fa-thumbs-up"></i> 56 </span>
<span><i class="fa fa-thumbs-down"></i> 56 </span>
<span><i class="fa fa-star"></i> 56 Fav </span>
</div>
</div>
</div>
</div>
As you can see these are static data. I want to put dynamic data from database in this.
Is there any advise how to get the data in div by loop.
I can show one record by using echo. I am not looking for entire code just wanted database part and some sample while using it in php.

I didn't know your table structure, so a sample code is given so that you can take help of it and do accordingly:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('hostname','username','password','databasename');
$prj= mysqli_query($conn,"select * from project where uid=$uid") or die(mysqli_error($conn));
$record = array();
while($row = mysql_fetch_assoc($prj)){
$record[] = $row;
}
mysql_close($conn);
?>
<?php foreach($record as $rec){?>
<div class="media services-wrap55 wow fadeInDown">
<img class="img-responsive" src="uploads/poster/<?php echo $rec['image_path'];?>"><br> // assuming that image_path is the field in table where you putted image name
<h4 class="media-heading"><?php echo $rec['project_name'];?></h4>// assuming that project_name is the field in table where you putted project name
<p><?php echo $rec['user_name'];?></p>// assuming that user_name is the field in table where you putted user name
<p><?php echo $rec['project_description'];?></p>// assuming that project_description is the field in table where you putted project name
<!-- in the same way you can do for others also -->
<a class="" href="iska-link.html">More ... </a>
<p>
<div id="progressBar2" class="tiny-green"><div></div></div><p>
<div class="counter-inner"><div id=example1" data-countdown="07/02/2015 00:11:00"></div></div><p>
<div class="col-sm-11 text-right">
<div class="entry-meta">
<span><i class="fa fa-comment"></i> 2 Comments </span>
<span><i class="fa fa-thumbs-up"></i> 56 </span>
<span><i class="fa fa-thumbs-down"></i> 56 </span>
<span><i class="fa fa-star"></i> 56 Fav </span>
</div>
</div>
</div>
</div>
<?php } ?>
Note:- stop using mysql_*, it is officially deprecated. use mysqli_* or PDO.

First off, you should be using PDO to query your database instead of mysql_query(). You code as it is now allows for SQL injection.
Here's how I would do it:
$db = new PDO('mysql:host=CHANGE_THIS_TO_YOUR_HOST_NAME;
dbname=CHANGE_THIS_TO_YOUR_DATABASE',
'CHANGE_THIS_TO_YOUR_USERNAME',
'CHANGE_THIS_TO_YOUR_PASSWORD');
$sql='select * from project where uid = :uid';
$query = $db->prepare($sql);
$query->bindValue(':uid', $_REQUEST['uid']);
$query->execute();
$projects = $query->fetchAll();
Then to display it in a loop, do this:
foreach ($projects as $project) {
echo '<div class="project">';
echo '<span class="project-name">'. $project['project_name'] .'</span>';
echo '<span class="project-dis">'. $project['short_dis'] .'</span>';
echo '<span class="project-poster">'. $project['poster'] .'</span>';
echo '</div>';
}

// database query to get result
$result = mysqli_query($conn, "select * from project where uid=$uid")
// new array for all rows
$rows = array();
// run mysql_fetch_assoc() in a loop (iterate) to get all rows from
// the whole result set and reassign them to the prepared and
// empty $rows array
// so that you can later iterate rows again to output your divs
while($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
mysql_close($conn);
// now iterate the $rows array to output data for each $row
<?php foreach($rows as $row){ ?>
// debug output to see what data is in a row
var_dump($row);
// print value of a key from the row array
echo $row['some_keyname'];
// use stringconcatenation to build your html output, e.g. div
echo '<div>' . $row['some_keyname'] . '</div>';
<?php } ?>

Related

Codeigniter 3 - fetch data from another table where current ID

I'm working on helpdesk system.
I created two tables contacts and contacts_comments.
Now I fetch contacts details by contact ID in view page - this working correct.
and now from view page I insert comments to second table contacts_comments.
To contacts_comments I insert message and current contact(ticket) ID.
And now I try display all this comments for current ticket ID.
<?php foreach ($comments as $comment): ?>
<div class="d-flex mb-4">
<div class="flex-shrink-0">
<img src="<?php echo base_url(); ?>assets/c_admin/assets/images/users/avatar-8.jpg" alt="" class="avatar-xs rounded-circle" />
</div>
<div class="flex-grow-1 ms-3">
<h5 class="fs-13"><?php echo $comment->ticket_client; ?> <small class="text-muted"><?php echo $comment->created_at; ?></small></h5>
<p class="text-muted"><?php echo $comment->comments_message; ?></p>
<i class="mdi mdi-reply"></i> Reply
</div>
</div>
<?php endforeach; ?>
But this function display for me all comments from table contacts_comments.
I try build function:
//get comments by id
public function get_comments_by_id($id)
{
$id = clean_number($id);
$this->db->where('ticket_id', $id);
$query = $this->db->get('contacts_comments');
return $query->row();
}
Can anyone help me how to add to this query in CI3 with result somelike:
DB WHERE contacts.id == contacts_comments.ticket_id

How to fix `Get all images from database`

PHP code is:
class Gallery{
public function get_images(){
global $pdo;
$query = $pdo->prepare('SELECT * FROM gallerys order by id desc');
$query->execute();
return $query->fetchAll(PDO::FETCH_ASSOC);
}
public function fetch_data($pid){
global $pdo;
$query = $pdo->prepare('SELECT * FROM gallerys where id = ? order by id desc');
$query->BindValue(1,$pid);
$query->execute();
return $query->fetch();
}
}
HTML code is:
$post = new Gallery;
$check = new Gallery;
$galery = $post->get_images();
<?php foreach($galery as $post){?>
<div class="fw-carousel fl-wrap full-height lightgallery">
<div class="slick-slide-item">
<div class="box-item">
<img src="../asset/<?php echo $post['image'];?>" alt="">
<i class="fa fa-search" ></i>
</div>
</div>
</div>
<?php }?>
Database structure:
---id---name---user---post_date---image---
When user post something and put 3 images into table gallerys on column user```` will be places$_SESSION['user_id'];and with that i will retrieve images byuser_id``` now i get only 1 image not all example 3 or 5 or 10...
When user upload example 3 or 5 images into database and want to view his upload, with this code they will get only 1 image, not all image what he upload. I don't get where is the problem in this script.
Any help?
You're generating a carousel/gallery/slider for each of your three images, overlapping each other. What you want is to create one carousel/gallery/slider with your three images inside. Replace
<?php foreach($galery as $post){?>
<div class="fw-carousel fl-wrap full-height lightgallery">
<div class="slick-slide-item">
<div class="box-item">
<img src="../asset/<?php echo $post['image'];?>" alt="">
<i class="fa fa-search" ></i>
</div>
</div>
</div>
<?php }?>
with
<div class="fw-carousel fl-wrap full-height lightgallery">
<?php foreach($galery as $post){?>
<div class="slick-slide-item">
<div class="box-item">
<img src="../asset/<?php echo $post['image'];?>" alt="">
<i class="fa fa-search" ></i>
</div>
</div>
<?php }?>
</div>

How to display the datas from two tables using search query?

I need to display datas from particular based on the results.
I have two tables movies_info => has all movies info & tv_shows_info => has TV shows info. I have search box if i enter the search it should search from both the table and display the datas but the condition in the results if it has movie_id, it should show movie details and if the result has tv_show_id it should show tv-show details.
as of now i have used basic search to fetch datas from one table and i have tried of using two but its not working.
<?php
// sql query for retrieving data from database
$sql_query = "SELECT * FROM `movies_info`";
$result = mysqli_query($connection, $sql_query);
// SQL Query for filter
if(isset($_POST['search_button']))
{
$value_to_search = $_POST['value_to_search'];
// search in all table columns
// using concat mysql function
$search_query = "SELECT * FROM `movies_info` WHERE CONCAT(`movie_name`, `movie_original_name`, `release_year`, `movie_genre`, `movie_country`, `movie_stars`, `movie_director`) LIKE '%".$value_to_search."%'";
//$search_query = "SELECT * FROM `movies_info`,`tv_shows_info` WHERE CONCAT(`movie_name`, `release_year`, `movie_genre`, `movie_country`, `tv_show_name`) LIKE '%".$value_to_search."%' GROUP BY `movie_id`";
//$search_query = "SELECT * FROM `movies_info` UNION ALL `tv_shows_info` WHERE CONCAT(`movie_name`, `release_year`, `movie_genre`, `movie_country`, `tv_show_name`) LIKE '%".$value_to_search."%'";
//$search_query2 = "SELECT * FROM `tv_shows_info` WHERE CONCAT(`tv_show_name`, `tv_show_start_year`, `tv_show_end_year`, `tv_show_genre`, `tv_show_country`) LIKE '%".$value_to_search."%'";
//$search_query .= $search_query2;
$search_result = filterTable($search_query);
}
else {
$search_query = "SELECT * FROM `movies_info`";
$search_result = filterTable($search_query);
//echo 'No Search Results Found';
}
?>
<!-- /w3l-medile-movies-grids -->
<div class="general-agileits-w3l">
<div class="w3l-medile-movies-grids">
<!-- /movie-browse-agile -->
<div class="movie-browse-agile">
<!--/browse-agile-w3ls -->
<div class="browse-agile-w3ls general-w3ls">
<div class="tittle-head">
<h4 class="latest-text">Search Results for : "<?php echo $value_to_search ?>"</h4>
<div class="container">
<div class="agileits-single-top">
<ol class="breadcrumb">
<li>Home</li>
<li class="active" style="text-transform:Capitalize;">Search Results </li>
</ol>
</div>
</div>
</div>
<div class="container">
<div class="browse-inner">
<?php
echo $search_result;
$rowcount = mysqli_num_rows($search_result);
for($i=1;$i<=$rowcount;$i++){
$row=mysqli_fetch_array($search_result);
?>
<div class="col-md-2 w3l-movie-gride-agile">
<a href="movie.php?movie_id=<?php echo $row['movie_id']; ?>" class="hvr-shutter-out-horizontal"><img src="<?php echo $row['movie_image']; ?>" title="<?php echo $row['movie_name']; ?>" alt=" " />
<div class="w3l-action-icon"><i class="fa fa-play-circle" aria-hidden="true"></i></div>
</a>
<div class="mid-1">
<div class="w3l-movie-text">
<h6><?php echo $row['movie_name']; ?></h6>
</div>
<div class="mid-2">
<p><?php echo $row['release_year']; ?></p>
<div class="block-stars">
<ul class="w3l-ratings">
<li>
<span>IMDB <i class="fa fa-star" aria-hidden="true"></i> <?php echo $row['movie_rating']; ?> </span>
</li>
</ul>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="ribben two">
<p>NEW</p>
</div>
</div> <?php } ?>
</div>
as of now i can get the values from one table.,
My exact need is it can be Movie or TV-Show but i should get the datas from both the table if it is a movie it should show some particular info and if thats a TV-show it should show someother info.
First, you need to use prepared statements which you can use even if you are using the LIKE function in MySQL. Then you need to add spaces between the column names to prevent the values from being blended together like "star warsstar wars". This will cause a movie like "star wars to be a result when a user searches for "ss" which would be inaccurate.
$search_result = array();
$search_query = "SELECT * FROM `movies_info` WHERE CONCAT(`movie_name`,' ', `movie_original_name`,' ',`release_year`,' ',`movie_genre`,' ',`movie_country`,' ',`movie_stars`,' ',`movie_director`) LIKE CONCAT('%',?,'%')";
if($stmt = $db->prepare($search_query)){
$stmt->bind_param('ii',$_SESSION['iidn_reference'],$o['parent_ref_id']);
if($stmt and $stmt->execute()){
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$search_result[] = $row;
}
}
}
After that, you could combine these tables with MySQL UNION but I strongly recommend just searching both tables and aliasing the table names to match.
SELECT 'movie' as `type`, `movie_id` as `id`, `movie_name` as `name`...
SELECT 'show' as `type`, `show_id` as `id`, `show_name` as `name`...

How to pass extracted values from mysql data base from one php file to another

I want to pass the specific extracted userID for each instance to another php file full_details.php so it generates a page dynamically
$stmt = $DB_con->prepare('SELECT userID, userDate, userName, userAge, userSex, userPic, userLocation, userStatus, userDetails FROM tbl_users ORDER BY userID DESC');
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<div class="col-sm-4 col-xs-6">
<div class="single-product">
<figure>
<img src="user_images/<?php echo $row['userPic']; ?>" />
<figcaption>
<div class="read-more">
<i class="fa fa-angle-right"></i> Full Details
</div>
</figcaption>
</figure>
<h4><?php echo $row['userName']." / "."age :".$row['userAge']; ?></h4>
<h5><?php echo $row['userStatus'] ?></h5>
</div> <!-- end .single-product -->
</div> <!-- end .grid-layout -->
Not easy to understand what you are asking...
I want to pass the specific extracted userID for each instance to another php file full_details.php so it generates a page dynamically
You would need to pass that ID in the URI for that href then right? Something like this:
<div class="read-more">
<i class="fa fa-angle-right"></i> Full Details
</div>
Then on full_details.php you can retrieve that GET parameter like so:
$userId = (isset($_GET['user_id')) ? $_GET['user_id'] : null;
Does that help?

Some HTML tags disappear when i use PHP

I'm trying to generate dynamic contents fill from mysql db
here is my php code:
<?php
include 'header.php';
error_reporting(1);
$user = "root";
$pass = "";
$dbName = "haimi";
mysql_connect('localhost', $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($dbName);
$sql = "SELECT * FROM Projects ";
$result = mysql_query($sql);
?>
<?php
while ($line = mysql_fetch_array($result)) {
?>
<li class="filter" data-filter=".cat<?php echo $line['Category'];?>"><?php echo $line['Category'];?></li>
<?php
}
?>
The li displays correctly, but the following does not:
<div class="row projects m0">
<?php
while ($line = mysql_fetch_array($result)) { ?>
<div class="project mix catHouses">
<div class="tint"></div>
<a href="images/projects/".<?php echo $line['ProjectImage1']; ?> data-
lightbox="project" data-title="Central Hospital (building)">
<img src="images/projects/".<?php echo
$line['ProjectImage1']; ?> alt="<?php echo $line['ProjectTitle'];?>"
class="projectImg"> </a>
<div class="projectDetails row m0">
<div class="fleft nameType">
<div class="row m0 projectName"><?php echo $line['ProjectTitle'];?></div>
<div class="row m0 projectType"><?php echo $line['ProjectType'];?></div>
</div>
<div class="fright projectIcons btn-group" role="group">
<a href="images/projects/<?php echo $line['ProjectImage1']; ?>" data-lightbox="project" data-title="Central Hospital (building)" class="btn btn-default">
<i class="fa fa-link"></i></a>
<i class="fa fa- search"></i>
</div>
</div>
</div>
<?php
}
?>
</div>
It data in the divs doesn't appear.
You're making a single call, but trying to loop through it twice. To do so, you need to reset the pointer back to the beginning:
//Add this after the first loop, but before the second
mysql_data_seek( $result, 0 );
The way you have it now, it's while($line = mysql_fetch_array($result)), but the second loop is never entered since it has already reached the end. Since the loop is ended, it never displays the contents.
Important Note
The mysql_* functions are deprecated, and is removed in PHP 5.5. You should use Mysqli or PDO. They have better protections against mysql injections (see Bobby Tables).
You have some HTML mistakes here:
<a href="images/projects/".<?php echo $line['ProjectImage1']; ?>
First, there is no need to use . operator (as you are in HTML, not PHP),
Also you shoud put your <?php ?> tag inside the href quotations, here is the correct code:
<a
href="images/projects/<?php echo $line['ProjectImage1']; ?>"
data-lightbox="project"
data-title="Central Hospital (building)"
>
<img
src="images/projects/<?php echo $line['ProjectImage1']; ?>"
alt="<?php echo $line['ProjectTitle']; ?>"
class="projectImg"
>
</a>
You will get older fast writing code like that ;)
How about this:
while ($line = mysql_fetch_array($result)) {
$category = $line['Category'];
echo <<< LOB
<li class="filter" data-filter="$category">$category</li>
LOB;
}
Like what Mr #matthew said
I was making a single call, and I was trying to loop through it twice.
The problem solved with this code before the while loop:
$result = mysql_query($sql);

Categories