hi i got a sql database table which has some images and some description. i need to be able to display everything but is not working properly. i got 2 different pages. where all the database staff is and the index page. here is the function from the first page
function get_image() {
global $db;
$query = 'SELECT * FROM table ';
try {
$statement = $db->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$statement->closeCursor();
return $result;
} catch (PDOException $e) {
$error_message = $e->getMessage();
display_db_error($error_message);
}
Here is index.php:
//on the index page i set up an array to display all the images but all i get is a 404 not found. this is the index page
<?php
require_once('model/database.php');
require_once('model/image_db.php');
// Set the array to display the images
$image_ids = array(1,2,3,4,5);
$images = array();
foreach ($image_ids as $image_id) {
$image = get_image();
$images[] = $image; // add images to array
}
// Display the home page
include('home_view.php');
?>
and on the home page i display everything but is not showing.. any ideas
<table>
<?php foreach ($images as $image) :
// Get image data
$imaget_price = $image['Price'];
$description = $image['description'];
// Get first paragraph of description
$description = add_tags($description);
$i = strpos($description, "</p>");
$description = substr($description, 3, $i-3);
?>
<tr>
<td id="image_column">
<img src="images/<?php echo $image['ID']; ?>.jpg"
alt=" ">
</td>
</tr>
<?php endforeach; ?>
</table>
?>
Edit:
You are binding values to a query that takes no values.
$statement->bindValue(1, $image_id);
You probably want something like this:
$query = 'SELECT * FROM table WHERE image_id = ?';
Related
I already have modal where I fetched the image path from the database and it is shown in the modal.
The PHP code to display images:
<?php
include_once '../../php/connection.php';
$query = "SELECT * FROM img_info LEFT JOIN estate_infos ON img_info.estate_infos_id = estate_infos.id
where img_info.estate_infos_id = $mdoalid";
$stmt = $dbcon->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
$datas = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($datas as $key => $data)
{
$pic = $data['image'];
?>
<img src="../<?php echo $pic ?>" width="360" height="150">
<a data-toggle="modal" data-target="#delete-modal" data-imgid="<?php echo $data['img_id']; ?>">
<i class="far fa-times-circle fa-2x" aria-hidden="true" style="color:red"></i>
</a>
<?php
}
?>
The Output of the above code is
How can I implement this in AJAX?
PS: I just need to display the image, not upload and display.
You can achieve your purpose by creating a script to find and return the data. After getting the data you can build your list with javascript.
<?php
include_once '../../php/connection.php';
$query = "SELECT * FROM img_info LEFT JOIN estate_infos ONimg_info.estate_infos_id = estate_infos.id where img_info.estate_infos_id = $mdoalid";
$stmt = $dbcon->prepare($query);
$stmt->execute();
$count = $stmt->rowCount();
$datas = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Turning your array into json
echo json_encode($datas);
?>
On this following page, you can understand how to display your data with javascript.
https://jsfiddle.net/onury/kBQdS/
I cannot figure out why my image is not displaying in my index.php page.
I use PDO to connect and use the database, but I faced some weird problem that has never happened to me before. The image that I stored in my database as blob type is not displaying in my index.php page.
Here's my code:
<?php
$dsn = 'mysql:host=localhost;dbname=website;charset=utf8mb4';
$pdo = new PDO($dsn, 'root', '');
if ( isset($_POST['upload']) )
{
$file = addslashes(file_get_contents($_FILES['image']['tmp_name']));
if ( !empty($file) )
{
$sql = " INSERT INTO images(name) VALUES (:name) ";
$pdo->prepare($sql)->execute(array('name' => $file));
}
}
?>
This I use to display images on my images div tag:
<div class="images" id="Images">
<?php
$sql = " SELECT * FROM images ";
$result = $pdo->query($sql);
if ( $result->rowCount() > 0 )
{
while ( $row = $result->fetch() )
{
echo '<img src="data:image/jpeg;charset=utf-8;base64,' .base64_encode($row['name']). '" alt="Binary Image"/>';
}
}
?>
</div>
I would store the image directly encoded in base64 an also its extension for proper display.
IMPORTANT
The content field has to be TEXT type in your database, otherwise you won't store the data properly and you won't be able to get it as you should
<?php
$dsn = 'mysql:host=localhost;dbname=website;charset=utf8mb4';
$pdo = new PDO($dsn, 'root', '');
if (isset($_POST['upload'])) {
// Get the image and convert into string
$img = file_get_contents($_FILES['image']['tmp_name']);
// Encode the image string data into base64
$content = base64_encode($img);
// Get the extension
$extension = strtolower(end(explode('.', $_FILES['image']['name'])));
if (!empty($content)) {
$sql = " INSERT INTO images(content, extension) VALUES (:content, :extension) ";
$pdo->prepare($sql)->execute(array('content' => $content, 'extension' => $extension));
}
}
// Later in your code
?>
<div class="images" id="Images"></div>
<?php
$sql = " SELECT * FROM images ";
$result = $pdo->query($sql);
if ($result->rowCount() > 0) {
while ($row = $result->fetch()) {
echo "<img src='data:image/{$row['extension']};charset=utf-8;base64,{$row['content']}' alt='Binary Image'/>";
}
}
?>
</div>
I am going out of my mind as it is. I am trying to pass a variable from a page that shows all albums thumbnail image and name to a page that will display all the pictures in that gallery using that passed variable, but the variable is empty in the url on the target page. I have seen similar cases on the web and on this site and I've applied the suggestions but it's still the same. Here is the code that lists the thumbnail and passes the variable(id).
<?php
include ("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
$albums = mysqli_query($conn,"SELECT * FROM albums");
if (mysqli_num_rows($albums) == 0) {
echo "You have no album to display. Please upload an album using the form above to get started. ";
}
else{
echo "Albums created so far:<br><br>";
echo "<table rows = '4'><tr>";
while ($thumb = mysqli_fetch_array($albums)) {
echo '<td><a href ="view.php?id="'.$thumb['id'].'"/><img src = "'.$thumb['thumbnail'].'"/><br>'.$thumb['album_name'].'<br>'.$thumb['id'].'</a></td>';
}
echo "</tr></table>";
}
?>
The code for getting the passed variable is as follows:
<?php
include("config.php");
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
$db = mysqli_select_db($conn,dbname);
if (isset($_GET['id'])) {
$album_id = $_GET['id'];
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn,$pic);
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
}
else{
echo "Pictures in the gallery:<br><br>";
while ($result = mysqli_fetch_assoc($picQuery)) {
echo "<img src='".$result['photo_path']."'/>";
}
}
}
?>
Please help as i have spent the last two days trying to get it right.
First, your's code is weak against sql injections:
$album_id = $_GET['id']; // here
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
Use either $album_id = intval($_GET['id']) or prepared statements functionality.
Second, add debug lines to your code, like:
<?php
include("config.php");
if (isset($_GET['id'])) {
$album_id = intval($_GET['id']);
var_dump($album_id); // should print actual passed id
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD);
var_dump($conn _id); // should print conn resource value
$db = mysqli_select_db($conn, dbname);
var_dump($db); // should print 'true' if db select is ok
$pic = "SELECT * FROM photos WHERE album_id ='$album_id'";
$picQuery = mysqli_query($conn, $pic);
var_dump($picQuery); // should print query resource value
if (!$picQuery) {
exit();
}
if (mysqli_num_rows($picQuery) == 0) {
echo "Sorry, no Pictures to display for this album";
} else {
echo "Pictures in the gallery:<br><br>";
while (($result = mysqli_fetch_assoc($picQuery)) !== false) {
var_dump($result ); // should print fetched assoc array
echo "<img src='".$result['photo_path']."'/>";
}
}
}
Notice $album_id = intval($_GET['id']) and while (($result = mysqli_fetch_assoc($picQuery)) !== false) parts
Then follow link view.php?id=<existing-album-id> and observe debug result. On which step debug output differs from expected - there problem is.
I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);
I have the TPLancer component for Joomla installed on my site and I am trying to add some more information to the profile page of both the Freelancer and the Buyer. I am no genius with PHP or mySQL but can kind of bluff my way thru usually.
The information currently displayed on the profile pages is just data pulled from the database. I have added a new ‘website’ row in the database and have entered some data into the database but I can’t seem to get it to display. I thought it would just be something like echo $row->website; because echo $row->categories; works and so does echo $row->company; and they are all in the same table.
There is something happening that is obviously way above my head. Below I have pasted a section of the code from the tplancer.php file which contains the function for what I am trying to target.
Below that is some code from the tplancer.html.php file which displays the actual HTML on the page.
I hope someone can help and I hope I don’t sound too dumb! Cheers
function showLancerInfo($option)
{
global $mainframe;
$user =& JFactory::getUser();
$db =& JFactory::getDBO();
$lancer_id = JRequest::getVar('id', 0, 'get', 'int');
$is_lancer = isLancer($user->id);
$is_buyer = isBuyer($user->id);
$query = "select id FROM #__glance_lancer where userid =".$lancer_id;
$db->setQuery( $query );
$id = $db->loadResult();
if(!$id)
{
echo "Freelancer not found!";
return;
}
$query = "select username FROM #__users where id =".$lancer_id;
$db->setQuery( $query );
$username = $db->loadResult();
$row =& JTable::getInstance('lancer','Table');
$row->load($id);
$query = "select * FROM #__glance_projects where chosen =".$lancer_id." ORDER BY id desc LIMIT 10";
$db->setQuery( $query );
$projects = $db->loadObjectList();
$query = "select * FROM #__glance_bids where userid=".$lancer_id." order by id desc LIMIT 10 ";
$db->setQuery( $query );
$bids = $db->loadObjectList();
HTML_front_glance::showLancerInfo($option,$row,$projects,$bids,$username);
}
function showLancerInfo($option,$row,$projects,$bids,$username)
{
global $mainframe, $option;
$user =& JFactory::getUser();
$lancer_info = getUserInfo($row->userid);
?>
<!-- /////////////////////// FREELANCER PROFILE PAGE /////////////////////// -->
<?php
$img = JPATH_SITE.DS.'images'.DS.'glance'.DS.$row->userid.'.jpg';
if(file_exists($img)) {
$img = JURI::base().'images/glance/'.$row->userid.'.jpg';
echo '<img class="profile_logo" src="'.$img.'" alt="Logo" />';
}
else
{
$img = JURI::base().'components/com_glance/images/noimage.jpg';
echo '<img class="profile_logo" src="'.$img.'" alt="Logo"/>';
}
?>
<div class="profile_info">
<h1><?php echo $lancer_info['username'] ?><?php if($row->special=='y') {?>
<img src="components/com_glance/images/featured.png" alt="Featured" class="feat_lancer" />
<?php } ?></h1>
<h3><?php echo $row->company ;?></h3>
<p><?php echo $row->categories ; ?></p>
<p>Website: <?php echo $row->website; ?></p>
<p>Hourly Rate US $<?php echo $row->rate; ?></p></code>
Trying look for a folder in the component called "tables". Find the correct file, it should be called "lancer", in there that defines the table variables for the table you want and add the new variables you wish to display - e.g.
...
var $website = null;
...
Then you will be able to use, as you said, $row->website.
The clue you are looking for in the model function is this line:
$row =& JTable::getInstance('lancer','Table');
I hope that solves your problem! Good luck!