Using same php files with include erease the main page - php

everyone. The deal is I'm trying to do an overflow-x=scroll show for products in a company and show productos there using a database with php. Everything was fine, I pack the code of it in an eternal php file and try to use it twice with include. The main idea is to only chance the sql of the second include and respective querySelect file to avoid writing the code twice. The PROBLEM is that when I include the 2 files the first one content doesnt show neither the second one and everything that's after it. The code is something like:
<div>Div with some content<div>
<?php require ("productos.php"); ?>
<div>Div with some content<div>
<?php require ("productos1.php"); ?>/*This file will be the same as the other but with different sql*/
<div>Guest what? More divs<div>
What does the php file has? Well it's:
<?php
require "querySelect.php";
$productos = new columnas();
$array_productos = $productos->get_items();
foreach ($array_productos as $value) {
echo
'<div class="card">
<img data-toggle="modal" data-target="#exampleModal" data-nombre="' . $value["NOMBRE"] . '" data-imagen="' . $value["IMAGEN"] . '" data-color="' . $value["COLOR"] . '" data-peso="' . $value["PESO"] . '" data-tiempo="' . $value["TIEMPO"] . '" data-observaciones="' . $value["OBSERVACIONES"] . '" class="card-img-top" src="' . $value["IMAGEN"] . '" alt="Card image cap">
<div class="card-block p-3">
<h4 class="card-title">' . $value["NOMBRE"] . '</h4>
<p class="card-text">' . $value["DESCRIPCION"] . '</p>
<!-- Go somewhere -->
</div>
</div>';
}
?>
The querySelect.php is:
<?php
require "conexion.php";
class columnas extends conexion {
public function columnas() {
parent::__construct();
}
public function get_items() {
$sql = "SELECT * FROM primaproductos";
$sentencia = $this->conexion_db->prepare($sql);
$sentencia->execute(array());
$resultados = $sentencia->fetchAll(PDO::FETCH_ASSOC);
$sentencia->closeCursor();
return $resultados;
$this->conexion_db = null;
/*$resultados = $this->conexion_db->query('SELECT * FROM post');
$productos = $resultados->fetch_all(MYSQLI_ASSOC);
return $resultados;*/
}
}
?>
Last file:
<?php
require "config.php";
class conexion {
protected $conexion_db;
public function conexion() {
//--------------PDO-------------------------------------------------------------------
try {
$this->conexion_db = new PDO('mysql:host=###; dbname=###', '###', '###');
$this->conexion_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conexion_db->exec("SET CHARACTER SET utf8");
return $this->conexion_db;
} catch (Exception $e) {
echo "La linea de error es: " . $e->getLine();
}
}
?>

Files : [ Conexion.php , ( querySelect.php check the return statement.. ) ] i suppose are okay.
I think you're using bootstrap 4, so you should have a good structure before, i mean..
<div class="container-fluid">
<div class="row no-gutters">
<!-- HERE THE CARD ELEMENT, so
http://php.net/manual/en/function.require-once.php
-->
<?php require_once('productos.php'); ?>
<!-- And div with class col-12 or whatever you want per item -->
</div>
</div>
Productos.php
I think your mistake gonna be here too i mean..
Check elements before..
if ( !empty($array_productos) ) {
//The foreach
foreach ($array_productos as $value) {
echo '<div class="col-12">'.$value["nombre"].PHP_EOL.'</div>';
}
};
I hope this help to you =)

Related

Other way of displaying image, when only having the link from php

I am making a tool to convert steam profile urls to the different steam ids, whatever.
I have the different functions, triggered when submitting the URL of the profile with a form.
One of the function are, that it gets the avatar of the regarding steam profile.
Actually it gets the link of the image. What I can do is, echo an img element with the link, this wont give me any flexibility since I wont be really able to style etc that afterwards.
Now, the function of getting the avatar, is in the function of the submit form.
I tried just inserting the image URL into an img element.
<img src"<?php echo $avatar ?>">
Well, then I get a error message, saying "$avatar" is undefined, even though I defined it in my main php tags. I think that is due to the fact that it is done inside the form function, could be wrong though.
My main question now is, what could be a different approach to this? I need that in the form function because it should only be called then.
Maybe I just have to use the inconvenient way of echoing an img element every time.
Here is the actual code.
<form method="post">
<input type="text" name="profile_url">
<input type="submit" value="click" name="submit">
</form>
<div id="avatar-div" style="height:100px; width:100px;">
<img src="<?php echo $avatar; ?>">
</div>
the main php part
if(isset($_POST['submit']))
{
display();
}
function display() {
require_once 'steamid.class.php';
$input = $_POST["profile_url"];
$api_key = "xxxxxxxxxxxxxxx";
$id = new SteamID($input,$api_key);
if(substr_count($input, ' ') === strlen($input)) {
echo "Enter URL";
} else {
if ($id->resolveVanity()) {
$avatar = $id->toAvatar();
$communityid = $id->toCommunityID();
echo $communityid . ", " . " ";
$steamid = $id->toSteamID();
echo $steamid . ", " . " ";
$userid = '[U:1:'.$id->toUserID().']';
echo $userid . ", " . " ";
} else {
echo "Profile wasnt found!";
}
}
}
I'm refactoring my answer based on the conversation we had. Here is the recommended PHP code.
function urlCheck() {
$input = $_POST["profile_url"];
if(empty($input)) {
echo "Enter URL";
return false;
} else {
return true;
}
}
function display() {
require_once 'steamid.class.php';
$api_key = "xxxxxxxxxxxxxxx";
$id = new SteamID($input,$api_key);
if (urlCheck()) {
if ($id->resolveVanity()) {
$communityid = $id->toCommunityID();
echo $communityid . ", " . " ";
$steamid = $id->toSteamID();
echo $steamid . ", " . " ";
$userid = '[U:1:'.$id->toUserID().']';
echo $userid . ", " . " ";
return $id->toAvatar();
} else {
echo "Profile wasn't found!";
}
}
}
You haven't mentioned where you're running display(), or where you're expecting the output (echo) to display. I can only assume you want it at the top of the page. Let me explain how to use this.
<head>
$avatar = display();
</head>
<body>
<div id="avatar-div" style="height:100px; width:100px;">
<img src="<?= $avatar ?>">
</div>
</body>
Basically the way this works, is that wherever you run display(), is where the echoes will output (in this case, before the body). Wherever you echo $avatar is where the id will be displayed. I hope this works for you.
Take a look at PHP's Variable Scope
Any variable used inside a function is by default limited to the local function scope.
To fix this problem, use the global keyword. This way you will explicitly set $avatar; as a global variable so it can be used outside of your display() function.
Here is how it would work for your example:
function display() {
global $avatar;
// Rest of your display() function
// Set $avatar somewhere in here
}
display(); // Actually call display so $avatar is set
<div id="avatar-div" style="height:100px; width:100px;">
<img src="<?=$avatar;?>">
</div>

Implementing flash messages in Yii framework

This is my function from my controller :
public function actionUser(){
Yii::app()->user->setFlash('success', "Data1 saved!");
....
}
In the view If I write this :
<?php echo Yii::app()->user->getFlash('success'); ?>
it works, BUT I want to appear somewhere above the content and then automatically fade out after a few second. I tried this from here
<?php
Yii::app()->clientScript->registerScript(
'myHideEffect',
'$(".info").animate({opacity: 1.0}, 3000).fadeOut("slow");',
CClientScript::POS_READY
);
?>
But i don't understand who is myHideEffect and the class .info ? Can someone give me an example ? or a link to a demo?
thanks .
Below there are two implementation for the flash message, We can show messages using toastr notification or the normal bootstrap flash messages implementation.
If you want display messages as toastr notification have this line of code your controller action.
YII::app()->user->setFlash('toastr.error', 'An Error occured when saving');
If you want to use the normal bootstrap flash message use instead.
YII::app()->user->setFlash('alert alert-danger', 'An Error occured.');
For this to work you have to handle the flash messages on your main view layout as below. Most likely just before <?php echo $content; ?>
/** Takes care of the flashmessages **/
$flashMessages = Yii::app()->user->getFlashes();
if ($flashMessages) {
foreach ($flashMessages as $key => $message) {
$pattern = '/\s/';
$match = preg_match($pattern, $key);/* This checks the type of error message to use if the error $key is just one word then use toastr notification */
if ($match == 0) {
Yii::app()->clientScript->registerScript(
'myNotifyEffect', $key . '("' . $message . '");', CClientScript::POS_READY
);
} elseif ($match > 0) {
if ($key != 'alert alert') {
Yii::app()->clientScript->registerScript(
'myHideEffect', '$(".' . $key . '").animate({opacity: 1.0}, 5000).fadeOut("slow");', CClientScript::POS_READY
);
echo '<div class= "' . $key . ' alert-bold-border square fade in alert-dismissable">' . '<button class="close" data-dismiss="alert" type="button">×</button>' . $message . "</div>\n";
} else {
echo '<div class="' . $key . ' alert-bold-border square fade in alert-dismissable">' . '<button class="close" data-dismiss="alert" type="button">×</button>' . $message . "</div>\n";
}
}
}
}
This is a jquery based question, not yii based. However try this:
<?php if(Yii::app()->user->hasFlash("success")): ?>
<div id="message">
<?php echo Yii::app()->user->getFlash('success'); ?>
</div>
<?php endif; ?>
...
<script>
$(document).ready(function() {
setTimeout(function() {
$('#message').fadeOut('slow');
}, 3000);
});
</script>

PHP MySQL Database Images Toggler

I have built a little uploader that works fine, uploading the images file path to my DB, and storing the image in a folder.
Now I also have made a call that will call only images with the same ID as the Property ID it has assigned.
Where I have trouble is the Image display, I am looking for a simple way to toggle between the images in the database, but even before that, I need to know why the Database call only displays one of the images stored in the DB.
Here is my code so far :
PHP
if ($id) {
$query = "SELECT houses.*, gallery_photos.* " .
"FROM houses LEFT JOIN gallery_photos " .
"ON $id = gallery_photos.photo_category";
$result = mysql_query($query) or die(mysql_error());
}
// Print out the contents of each row into a table
while ($row = mysql_fetch_array($result)) {
$images_dir = "houses";
$photo_caption = $row['photo_caption'];
$photo_filename = $row['photo_filename'];
$photo_id = $row['photo_id'];
}
and the display happens withing a larger ECHO command, I will add a little of it so you get the idea :
Within the ECHO
echo "
<li>
<div id='imagizer'> <img src='" . $images_dir . "/" . $photo_filename ."?id=" . $photo_id . " ' title='$photo_caption'/></div>
</li>
There are many more elements within the li element that work fine, like Title, Price, Summary, etc etc.... But I can simply not accomplish 3 thing here :
Getting all the images to display (I only get one, which would be fine if the toggler worked).
Making a toggler to display the next image that has the same category_id.
Optional (An image slider)
UPDATE
This is kind of working, but I get various duplicate entries! It seems that for every picture I get 1 entry on the list. So if 4 pics, 4 entries, if 2, only 2 entries.
function showShort() {
$houses = #mysql_query('SELECT houses.*, gallery_photos.*
FROM houses LEFT JOIN gallery_photos
ON houses.id = gallery_photos.photo_category');
if (!$houses) {
die('<p> Error retrieving Propertys from database!<br />' . 'Error: ' . mysql_error() . '</p>');
}
while ($house = mysql_fetch_array($houses)) {
$id = $house['id'];
$title = htmlspecialchars($house['title']);
$ref = $house['ref'];
$summary = htmlspecialchars($house['summary']);
// $content = $house['content'];
$price = $house['price'];
$houseorder = $house['houseorder'];
$pool = $house['pool'];
$bedrooms = $house['bedrooms'];
$bathrooms = $house['bathrooms'];
$aircon = $house['aircon'];
$basement = $house['basement'];
$location = $house['location'];
$floorm = $house['floorm'];
$aream = $house['aream'];
$garage = $house['garage'];
$furbished = $house['furbished'];
$images_dir = "houses";
$photo_caption = $house['photo_caption'];
$photo_filename = $house['photo_filename'];
$photo_category = $house['photo_category'];
$photo_id = $house['photo_id'];
if ($garage == 'Yes') {
($garage = "Garage : Yes<br>");
} elseif ($garage == 'No') {
($garage = "");
}
if ($pool == 'Yes') {
($pool = "Swimming Pool : Yes<br>");
} elseif ($pool == 'No') {
($pool = "");
}
if ($aircon == 'Yes') {
($aircon = "Air Condition : Yes<br>");
} elseif ($aircon == 'No') {
($aircon = "");
}
if ($basement == 'Yes') {
($basement = "Basement : Yes<br>");
} elseif ($basement == 'No') {
($basement = "");
}
if ($furbished == 'Yes') {
($furbished = "Furbished : Yes<br>");
} elseif ($furbished == 'No') {
($furbished = "");
}
echo "
<li>
<div id='summarybox'>
<div id='titlestyle'> $title </div><br>
<div id='imagebox'> </div>
<div id='refstyle'> Ref. $ref </div>
<div id='details1'>
Bedrooms : $bedrooms <br>
Bathrooms: $bathrooms <br>
Living Area : $floorm m² <br>
Plot Area : $aream m² <br>
Location : $location <br>
</div>
<div id='details2'>
$pool
$aircon
$basement
$furbished
$garage </div>
<section class='ac-container'>
<div>
<input id='$id' name='accordion-1' type='checkbox' />
<label for='$id' >Read More</label>
<article class='ac-small'>
<div id='summarystyle'> $summary </div>
<div id='price'>Price : $price </div><br>
<div id='imagizer' align='center'>
<ul id='$id'>
<li><a href='" . $images_dir . "/" . $photo_filename . "' rel='lightbox[$photo_category]' title='$photo_caption'><img src='" . $images_dir . "/" . $photo_filename . "' height='50%' with='50%'/></a></li>
</ul>
</article>
</div>
</selection>
<br>
<div id='admbuttons'><a href='editProperty.php?id=$id' ><button>Edit</button></a>
<a href='deleteProperty.php?id=$id' onclick='return confirm()'> <button>Delete</button></a></div>
</div>
</li>";
}
}
This is the live example where i have used this idea just open the below link and click on the thumb image and then slide inside the lightbox.
Inspect the image with firebug and see the anchor tags below the image you will get the logic what i am trying to say and then you can manage it into your code
http://dev.tasolglobal.com/osclass/
your echo statement should be like in for loop
while ($row = mysql_fetch_array($result)) {
$images_dir = "houses";
$photo_caption = $row['photo_caption'];
$photo_filename = $row['photo_filename'];
$photo_id = $row['photo_id'];
echo "
<li>
<div id='imagizer'> <img src='" . $images_dir . "/" . $photo_filename ."' id=" . $photo_id . " title='$photo_caption'/></div>
</li>
}
id and src should have some space to print in echo.
please add above code in you for loop sure it will work for you.
The main thumb single image
<a href="url of the first image" rel="lightbox['unique name for a particular bunch of image']><img src="url of the first image" /></a>
Just fire a query and get all the image url only for the particular category and run a loop for the urls to create anchor tags with rel
for($b=1;$b<$thumb_url;$b++)
{
echo = '';
}
These image url are in the href so will not load on page load and when the lightbox will be triggered on the click of the first image it will load all the images with a particular unique string in the rel="lightbox[]" and will show next and previous link to show images like slider
You can use "cat_" then the unique id of a particular category to make unique the rel of those particular images.
I have tried it and it works
UPDATE
What you need to do is do not loop the li but just place the first image in the li inside the img tag and the unique rel and then after the li you have to run the loop for the rest of the category images and create anchor tag with image url in the href and rel similar to the first image
Do not forget to include the js and css for the light box
<div id='imagizer' align='center'>
<ul id='$id'>
<li><a href='" . $images_dir . "/" . $photo_filename . "' rel='lightbox[$photo_category]' title='$photo_caption'><img src='" . $images_dir . "/" . $photo_filename . "' height='50%' with='50%'/></a></li>
</ul>
//Put your loop here to make the anchor tags and keep the url in the href only with the rel corresponding to the first image so they will be treated as a bunch by lightbox
Create a common select function and try query with it and then use for loop on the result associative array it will be less confusion and neat code
Execute Select Query
function select ($sql="", $fetch = "mysql_fetch_assoc")
{
global $conn;
$results = #mysql_query($sql,$conn);
if(!$results) {
echo mysql_errno()." : ". mysql_error();
}
$data = array();
while ($row = $fetch($results))
{
$data[] = $row;
}
mysql_free_result($results);
return $data;
}

on click change questions displayed

I have a page that has a list of items. On the bottom of the page is a "view more" button. When someone clicks this button, the page needs to add more items. The var is $displayedquestions, and the page is coded right now to refresh when the "view more" button is clicked, but we'd like to have it do it live. How can this be done?
Here is code:
<?php
include "db_connect.php";
db_connect();
function tags($tags)
{
$tagarray=explode(",",$tags);
$i=0;
$finished='false';
while($finished=='false') {
if (empty($tagarray[$i])=='true') {
$finished='true';
} else {
$taglist = $taglist . '<a class="commonTagNames" href="">' . $tagarray[$i] . '</a> ';
$i++;
}
}
return $taglist;
}
function formattime($timesince)
{
$strsince=number_format($timesince,0,'','');
$nodecimals=intval($strsince);
if ($nodecimals<1){
return "Less than a minute ago";
} elseif ($nodecimals>=1&&$nodecimals<60) {
return $nodecimals . " min ago";
} elseif ($nodecimals>60&&$nodecimals<1440){
$hourssince=$nodecimals/60;
$hoursnodecimals=number_format($hourssince,0);
return $hoursnodecimals . " hours ago";
} elseif ($nodecimals>1440){
$dayssince=$nodecimals/1440;
$daysnodecimals=number_format($dayssince,0);
return $daysnodecimals . " days ago";
}
}
$submitbutton=$_REQUEST['viewmore'];
$numquestions=intval($_REQUEST['questions']);
if($numquestions!=0) {
$displayedquestions=$numquestions;
} else {
$displayedquestions=10;
}
$sql="SELECT * FROM `Questions` ORDER BY `Questions`.`ID` DESC LIMIT 0, " . $displayedquestions;
$questions=mysql_query($sql);
while($row = mysql_fetch_array($questions))
{
$id = $row['ID'];
$user = $row['userAsking'];
$question = $row['question'];
$tags = $row['tags'];
$timestamp = $row['timestamp'];
$time=strtotime($timestamp);
$secondssince=(date(U)-$time)/60;
$timesince=formattime($secondssince);
$responses=mysql_query("SELECT * FROM `answersToQuestions` WHERE `idOfQuestion`= '$id'");
$comments=mysql_num_rows($responses);
$likes=mysql_query("SELECT * FROM `likesOfQuestions` WHERE `idOfQuestion`= '$id'");
$numlikes=mysql_num_rows($likes);
$userprofileq = mysql_query("SELECT `ID`,`avatar` FROM `Users` WHERE `username` = '$user'");
$userprofileresult = mysql_fetch_row($userprofileq);
$linktoprofile = $userprofileresult[0];
$avatar = $userprofileresult[1];
$taglist=tags($tags);
echo "</li>";
echo '<li class="questionsList" onclick="showUser(' . $id . ')">
<div id="questionPadding">
<img class="askerImage" width=50 height=50 src="../Images/userimages/' . $avatar . '.png"/>
<div class="questionFirstRow"><h1 class="questionTitle">' . $question . '</h1></div>
<span class="midRow">
<span class="askerSpan"><a class="askerName" href="">'. $user .'</a></span>
</span>
<span class="bottomRow">
<img src="../Images/comment.png"/>
<span class="comments">' . $comments . '</span>
<img src="../Images/likes.png"/>
<span class="likes">' . $numlikes . '</span>
' . $timesince . '
</span>
</div>
</li>';
}
?>
<center><img class="moreQuestions" src="../Images/viewMoreBar.png" alt="More" /></center>
Without doing a lot of work you can add ajax to this. Use this function:
First, (I am assuming you are including the code above into another file) create a container around it. Ex:
<div id='container'>...</div>
Second, add this javascript to the page that includes the code you have above:
<script type="text/javascript">
$(function(){
$("#container img.moreQuestions").parent().live('click', (function (e) {
e.preventDefault();
$("#container").load($(this).attr("href"));
});
});
});
</script>
This will load into #container the script you already have without refreshing the rest of the page.
Note the selector for the More link (slash button) in my example is $("#container img.moreQuestions").parent() because you don't have a class or id on it. You should give a class or id to the More link and use that for the selector.
like #diEcho mentioned, jQuery would be a great help: You could easily refresh your list of items by ajax (retrieving the complete list from a php file for example) as well as update your DOM elements with newly added values. Give it a try.
In addition you should think about getting you initial items by ajax as well. Data logic /display /UI functionality were seperated cleanly this way.

PHP - Show results, conditional based on link

Looking for some help with the code below. I think there may be an issue with the way I've organized the php call and function calls. I'm a beginner and am trying to allow users to display results from different tables, depending on what link they click.
I get this error:
Parse error: syntax error, unexpected '{' in /home/content/c/e/l/celebrything/html/wp-content/themes/celebrything/sidebar.php on line 16
Any help in correcting the issue here would be amazing. Here's the code:
<div id="sidebar">
<div class="post">
<h2>
<font color="#333333">Most Popular Celebrities</font><br>
<font color="#333333">in last 24 hours</font>
<br>
<br>
Today
Week
Month
<?php
if (!in_array($table, array('today', 'week', 'month')) {
return false;
}
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_' . $table);
foreach($result as $row) {
echo '<a href="http://www.celebrything.com/?s=' .
urlencode($row->name) . '&search=Search">' . $row->name .
'</a> - ' . $row->count . ' Posts<br/>';
}
}
?>
showTable($_GET['table']);
</h2>
</div>
</div>
<div class="clear"></div>
UPDATED CODE----------------
<div id="sidebar">
<div class="post">
<h2>
<font color="#333333">Most Popular Celebrities</font><br>
<font color="#333333">in last 24 hours</font>
<br>
<br>
Today
Week
Month
<?php
if (!in_array($table, array('today', 'week', 'month'))) {
return false;
}
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_' . $table);
foreach($result as $row) {
echo '<a href="http://www.celebrything.com/?s=' .
urlencode($row->name) . '&search=Search">' . $row->name .
'</a> - ' . $row->count . ' Posts<br/>';
}
if (!empty($_GET['table'])) {
showTable($_GET['table']);
} else { showTable('today'); }
?>
</h2>
</div>
</div>
<div class="clear"></div>
1. Missing a ) on the first if block
if (!in_array($table, array('today', 'week', 'month'))) {
return false;
}
2. There is an extra } right before the closing ?>
}
}
?>
3. You need to put the showTable function before the closing ?> like:
showTable($_GET['table']);
?>
In Summary:
Get a code editor that supports syntax highlighting. You will love it.
Looks to me like you're referencing a function -- showTable() -- but you haven't set up your logic inside function (unless you're leaving something out of the code sample). Should be:
<?
//----------------------
//Create the showTable() function, which won't do anything until it's called. It can
//reside anywhere on the page, really. It's here just because this is where I put it.
function showTable($table) {
if (!in_array($table, array('today', 'week', 'month'))) {
return false;
}
global $wpdb;
$result = $wpdb->get_results('SELECT name, count FROM wp_celebcount_' . $table);
foreach($result as $row) {
echo(''.$row->name.' - '.$row->count.' Posts<br/>');
}
}
//----------------------
//Here is where you actually call the function, to display some stuff on the page
if (!empty($_GET['table'])) {
showTable($_GET['table']);
} else {
showTable('today');
}
?>
The code above assumes that you're using proper/working functions built into Wordpress (I don't know Wordpress very well). But the syntax above should clear up any function syntax related issues, which I think is your main issue.

Categories