I am adding an ancillary page to my wordpress site ( without the site's styling, menu, etc ) using the following template and it is not returning any results from the database. I've read countless web pages and a couple of WP books and I am at a lost. I can see the four records in the database but the page shows none. Here's my template:
<?php
/*
Template Name: Media Player Page
*/ ?><!DOCTYPE html> >
<head>
<meta charset="<?php bloginfo('charset'); ?>" />
<title>Online Media Player</title>
<?php wp_head(); ?>
<link rel="stylesheet" href="/assets/css/music-player.css" type="text/css" media="screen" charset="utf-8">
<script src="/assets/js/jquery-1.8.3.js"></script>
</head>
<body>
<div class="main-center">
<h1>Please select your choice of music</h1>
<?php
global $wpdb;
$rows = $wpdb->get_results("select * from ppm_playlists");
foreach($rows as $row) :
?>
<a class="openplayer" data-genre="<?php echo $row['id']; ?>" href="#"><?php echo $row['playlist']; ?></a>
<?php endforeach; ?>
</div> <!-- /.main-center -->
<script type="text/javascript">
(function($) {
$('.main-center').on('click', '.openplayer', function(e){
var genre = $(this).data('genre');
e.preventDefault();
alert(genre);
});
})(jQuery);
</script>
</body> </html>
$wpdb->get_results will return an array of objects, not an array of arrays, unless you pass it a second parameter instructing otherwise. If you had debugging enabled, you would see Fatal Error: Cannot use object of type stdClass as array....
You want to be using object syntax:
foreach($rows as $row) : ?>
<a class="openplayer" data-genre="<?php echo $row->id; ?>" href="#"><?php echo $row->playlist; ?></a>
<?php endforeach; ?>
Or pass a second parameter to get_results
$rows = $wpdb->get_results("select * from ppm_playlists", ARRAY_A);
Related
I am working on building a site, but right now it has several images that I don't have actual images for yet. As this site has thousands of images or places where images should be, I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?
Update: Since I am still a bit confused as to where to even place this function, I am going to add the code for one of the pages that I need this for then maybe someone can help me figure out how to place it.
Here is the code for one of the pages:
<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>
<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>
<body>
<div class="wrapper">
<a id="top"></a>
<?php require_once('header.php'); ?>
<?php require_once('nav.php'); ?>
<div class="category"><h2>Flower Trees</h2></div>
<div class="display">
<?php do { ?>
<ul>
<li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>
<br />
<span class="name"><?php echo $row_master['name']; ?></span></a></li>
</ul>
<?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
<!-- end .display --></div>
<?php
mysqli_free_result($master);
?>
<?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
Since this is as simple as a foreach loop, and not tons of images scattered across your webpage, you can use something like:
$image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';
Full code:
<?php
require_once('dbconnection.php');
mysqli_select_db($conn, $dbname);
$query_master = "SELECT DISTINCT * FROM `master_list` INNER JOIN types_join ON master_list.join_id=types_join.join_id WHERE `type_id` = 171 ORDER BY `item_id`";
$master = mysqli_query($conn, $query_master) or die(mysqli_error());
$row_master = mysqli_fetch_assoc($master);
$totalrows_master = mysqli_num_rows($master);
?>
<!doctype html>
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flower Trees</title>
<link href="/css/styles.css" rel="stylesheet" type="text/css">
<link rel="shortcut icon" type="image/png" href="img/favicon.png">
</head>
<body>
<div class="wrapper">
<a id="top"></a>
<?php require_once('header.php'); ?>
<?php require_once('nav.php'); ?>
<div class="category"><h2>Flower Trees</h2></div>
<div class="display">
<?php do {
$image = file_exists('img/' . $row_master['img']) ? 'img/' . $row_master['img'] : 'placeholder.png';
?>
<ul>
<li><a href="details.php?recordID=<?php echo $row_master['master_id']; ?>"><img class="thumb" src="<?php echo $image; ?>"/>
<br />
<span class="name"><?php echo $row_master['name']; ?></span></a></li>
</ul>
<?php } while ($row_master = mysqli_fetch_assoc($master)); ?>
<!-- end .display --></div>
<?php
mysqli_free_result($master);
?>
<?php require_once('footer.php'); ?>
<!-- end .wrapper --></div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
I don't want to have to manually change each of them and then change them again when I find the correct image. Is there a way to create a function that will look for the missing images and replace them with a specified image until the correct image is found?
Such a function might be written as:
function im($imgName) {
$pathToImgs = "images/";
if (file_exists( $pathToImgs . $imgName )) {
echo $pathToImgs . $imgName;
}
else {
echo $pathToImgs . "placeholder.jpg";
}
}
Then in your html:
<img src="<?php im("product1.jpg"); ?>">
<img src="<?php im("product2.jpg"); ?>">
<img src="<?php im("product3.jpg"); ?>">
As a start.
***Edit 1:
Given your code where it says:
<img class="thumb" src="img/<?php echo $row_master['img']; ?>"/>
You might modify it with a conditional that inserts the placeholder image in the event that the target image simply doesn't exist, yet.
<img class="thumb" src="<?php
if (file_exists("img/" . $row_master['img'])) {
echo "img/" . $row_master['img'];
}
else {
echo 'img/placeholder.jpg';
}
?>">
You could reuse this functionality by turning the conditional into a php function, so described as a starter above.
Using jQuery, you can accomplish something easy enough using a global $('img') handler when errors occur. Simply swap them out with your placeholder image afterwards.
$('img').on('error', function() {
const oldSrc = encodeURIComponent($(this).attr('src'));
$(this).attr('src', `https://via.placeholder.com/300/000000/FFFFFF/?text=${oldSrc}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="imagethatdoesntexist.jpg"><br />
<img src="anotherimage.jpg">
Here I use placeholder.com (A convenient site for placeholder images such as this), and inject the old image source into the query string, which the site will render in the image itself.
I'm getting weird results when trying to kind of make a "templating engine". Basically, I want to be able to use PHP variables that contain data from an SQL database.
What happens is that everything works properly with the PHP side, what does not is the page that needs to display this information (index.php).
I'm working on a way to get the website's name from the sql database, so I have something like that on my index:
<?php
include ('php/data/sitename.php');
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $sitename; ?> - Home</title>
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="container">
<!-- HEADER: Navbar -->
<?php $navbar; ?>
<!-- MAIN: Index Page contents -->
<?php $page_index ?>
<!-- FOOTER: Footer -->
<?php $footer; ?>
<?php $sitename; ?>
</div>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
</body>
</html>
This variable comes from a file (that has been included) called sitename.php, with the following code:
<?php
include ('../db.php');
$sql = "SELECT id, sitename FROM GeneralData";
$getname = mysqli_query($conn, $sql);
if ($getname->num_rows > 0) {
while($row = $getname->fetch_assoc()) {
$sitename = $row['sitename'];
echo $sitename;
}
}
?>
Yes, I used echo $sitename;, I know it wont echo the actual data, but I did it to test some things, and here are the results:
Including the file sitename.php to index.php will do nothing, it would be like if it did not exist. However, if I write "echo "123";" on it, it will echo 123 on index. What does not work is what I need.
If I go to sitename.php directly, it will simply output the correct SQL value I requested because I told it to echo (as I stated before). But, it wont work in index, it will simply not work.
Also, I'll leave my project structure here. It might help.
What can I do?
Thanks in advance!
try set GLOBAL for sitename
GLOBAL $sitename;
or
GLOBALS['sitename'];
$sitename = ...
EDIT
try use
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/yourpath/yourfile.php";
include_once($path);
I have my footer.php with admin button in it and when i include it at the end of my page the button doesn't appear.. But if i put it before this code:
<?php if ($row["rights"]=="2"):?>
<div id='cssmenu-admin'>
<ul>
<li name='admin' class='active'><a href='administration.php'><span>Admin</span></a></li>
</ul>
</div>
<?php endif; ?>
from footer.php before while cycle it works like it should.
This my footer.php file:
<div id="footer">
<hr>Copyrighted (C) 2014 by djdanas#gmail.com<br>
<?php if ($row["rights"]=="2"):?>
<div id='cssmenu-admin'>
<ul>
<li name='admin' class='active'><a href='administration.php'><span>Admin</span></a></li>
</ul>
</div>
<?php endif; ?>
</div>
<br><hr>
And this is my page file:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Pagrindinis</title>
<link href="CSS/stilius.css" rel="stylesheet" type="text/css"/>
<link href="CSS/menu.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php require("includes/validate.php");?>
<?php require("includes/stilius.php");?>
<?php
require("includes/connection_to_db.php");
$sql = "SELECT prekės.* , CONCAT(vartotojai.name) as v_name
FROM prekės
LEFT JOIN vartotojai
ON vartotojai.V_ID=prekės.V_ID
ORDER BY prekės.date
DESC LIMIT 8";
$result = mysql_query("$sql");
?>
<?php mysql_close(); ?>
<?php while ($row = mysql_fetch_assoc($result)) : ?>
<?php $image = '<td><img src="data:image/jpeg;base64,'.base64_encode($row['image']).'" name="pix" width="270" height="200"/></td>' ?>
<table class="two">
<th><?php echo $row['name'] ?></th>
<th>Prekės savininkas: <?php echo $row['v_name']?></th>
<th><input type="button" value="Mainyti"></th>
<tr>
<?php echo $image?>
<td><textarea disabled style="resize:none; background-color:white" name="about" rows="12" cols="65"><?php echo $row['specs']?></textarea><td>
</table>
<?php endwhile; ?>
<?php require("includes/footer.php");?>
</body>
</html>
EDIT:
Ok, i solved my problem by adding new variable
$rights = $row['rights'];
right after
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Pagrindinis</title>
<link href="CSS/stilius.css" rel="stylesheet" type="text/css"/>
<link href="CSS/menu.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php require("includes/validate.php");?>
<?php require("includes/stilius.php");?>
in my page file and changed 1 line in my footer.php file from
<?php if ($row['rights']=="2"):?>
to
<?php if ($rights="2"):?>
now it's working like a charm :)
I'll take a stab in the dark here and say that your test
if ($row["rights"]=="2")
means you are checking to see if the user logged in has the "rights" of 2?
Then when you loop through your query...
while ($row = mysql_fetch_assoc($result))
You are overwriting your $row variable. So whatever you thought was in there to begin with, isn't anymore. You should use a different variable for either your user or looping through the query.
EDIT:
It's also possible that the variable isn't in scope once you get to where you are testing it. You could try using a print_r($row) in footer.php to see what is currently inside of $row -- that should help.
I have a blog and I would like the tag in the head section of the HTML document to change dynamically using PHP. Here is my PHP code:
<?php
session_start();
if(isset($_SESSION['admin']) and !empty($_SESSION['admin'])){
echo 'Logout';
}
require('mysql2.php');
//Displaying the information from the DB to the user
//with pagination, i.e different pages
function post(){
$sp_query = mysql_query("SELECT COUNT(id) FROM posts");
$pages = ceil(mysql_result($sp_query, 0) / 1);
$page = (isset ($_GET['page'])) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * 1;
$query = mysql_query("SELECT id,title, article, datetime
FROM posts ORDER BY id DESC LIMIT $start, 1 ");
//Check if there are any rows in the DB
if(mysql_num_rows($query)){
while($result = mysql_fetch_assoc($query)){
//displaying the results
echo '<article class="blog-post">
<div class="blog-info">
'.stripslashes($result['title']).' ';
echo
stripslashes($result['datetime']).'<div>';
echo
nl2br(stripslashes($result['article'])).'</article>';
$title[] = $result['title'];
$id =
mysql_real_escape_string((int)$result['id']);
echo '<input type="hidden"
value="'.$result['id'].'" />';
$_SESSION['post_id'] = $id;
//If the admin is logged in, session variables
//for editing and deleting a post must be set
//and the conforming links should be displayed
if(isset($_SESSION['admin']) and
!empty($_SESSION['admin'])){
//$_SESSION['post_id'] = $id;
$_SESSION['edit_post'] = $id;
echo '<article class="blog-post">';
echo '<a href="delete.php"
id="delete" onclick="return del();">Delete this post</a>';
echo '<br />Edit this post';
echo '</article>';
}
}
}
//The drop down menu
function options(){
$new_query = mysql_query("SELECT title FROM posts
ORDER BY id DESC");
$num = 1;
while($array = mysql_fetch_assoc($new_query)){
echo '<option
value="blog.php?page='.$num++.'">'.$array['title'].'</a></option>';
}
}
?>
And here is the HTML:
<?php require('mysql2.php');
require('blog_process.php');
?>
<!DOCTYPE html>
<html>
<head>
<!--Meta Data-->
<meta charset="utf-8">
<meta name="description" content="About Chris Shilts">
<meta name="author" content="Chris Shilts">
<meta name="keywords" content="chris, shilts">
<meta name="viewport" content="width=device-width, initial-scale=1,
maximum-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<!--css-->
<link rel="stylesheet" href="reset.css">
<link rel="stylesheet" href="style.css">
<!-- Javascript -->
<script type="text/javascript" src="delete.js"></script>
<!-- Favicons-->
<link rel="shortcut icon" href="favicon.ico">
<!--Title-->
<title id="title"><?php //php code should go here?></title>
</head>
<body>
<!--Contains all content-->
<div id="container">
<!--Content at start of page, generally the same-->
<header>
<div id="logo">
Hello There!
</div>
<!--Primary Navigation-->
<nav>
Link
Link
Link
</nav>
</header>
<!--Blog Posts-->
<?php post();?>
<!-- The navigation bar for the blog posts -->
<select onclick="navigation();" id="select">
<option value="" selected="selected"></option>
<?php options(); ?>
</select>
<!--First Footer-->
<footer id="footer-one">
Site Design By Chris Shilts | Programming by
Stefany Dyulgerova
</footer>
<!--Second Footer-->
<footer id="footer-two">
<a href="http://www.w3.org/html/logo/">
<img id="html5" src="http://www.w3.org/html/logo/badge
with CSS3 / Styling">
</a>
</footer>
<!--/container-->
</div>
</body>
</html>
I have also have a mysql database and here are the fields there:
id title article dateime
Please help me!
I tried to put the $result['title'] into a an array like this
$title[] = $result['title'];
And then to loop it through in the element based on the based on the id in the $_SESSION['post_id'] but the problem is that I have to reload the page twice in order the title to take effect.
Trying to save the blog title in an array isnt't work for you because the $title variable is only accessible within the post function.
You could have post return the $title array...
//initialize the array at the beginning of the post function like so
$title = array();
//return the array at the end of the function like so
return $title;
Then in the page, you'd replace
<?php post();?>
With
<?php $title = post();?>
However, You need $title BEFORE you the call to post. So that won't really help you.
I would suggest...
1) Create a Class Object with a global title variable. Have an initialize function to handle the database call. Then make post a function on the class that prints out the page HTML.
2) Create a title function that returns the correct page title and call it like so..
<title id="title"><?php get_page_title(); ?></title>
Update:
In your php file add the following function after the options function:
public function get_page_title() {
//add code to get the page title
// not sure what title you want since you are showing multiple posts on one page
}
Here is the code snippit that needs to be fixed : <title id="title"><?php echo $result['title']; ?></title>
This will work if there is one title, otherwise take the first : <title id="title"><?php echo $result['title'][0]; ?></title>
Having a strange zend framework issue. Although it's most likely something simple, I've been unable to resolve it so far. I have scraped the bottom of stackOverflow and several other community sites, as well as the zend documentation.
Any ajaxLink that I include in my layout refuses to function. They are classed properly, with hash placeholder in href attribute, but the javascript to activate the link is not being included in the page .
echo $this->jQuery; statement in layout is also failing. Might be the cause of ajaxLink failure. I have verified that I am properly adding the jQuery view helper in my bootstrap. Have tried using both ZendX_JQuery::enableView($view); and $view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper"); methods.
Thanks in advance
Excerpts from the relevant files follow:
bootstrap.php:
protected function _initViewHelpers()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$view->doctype('HTML4_STRICT');
$view->headMeta()->appendHttpEquiv('Content-type', 'text/html;charset=utf-8')
->appendName('description', 'Business Club');
$view->headTitle()->setSeparator(' - ');
$view->headTitle('SOU Business Club');
$view->setHelperPath(APPLICATION_PATH.'/views/helpers', '');
ZendX_JQuery::enableView($view);
}
dashboardLayout.phtml:
<?php echo $this->doctype();?>
<html>
<head>
<?php echo $this->headTitle();?>
<?php echo $this->headMeta();?>
<?php
echo $this->headLink()->prependStylesheet($this->baseUrl().'/css/dashboardStyle.css');
echo $this->headLink()->prependStylesheet($this->baseUrl().'/js/jquery/css/smoothness/jquery-ui-1.8.11.custom.css');
?>
<?php
echo $this->headScript()->appendFile($this->baseUrl().'/js/paginator.js');
echo $this->jQuery();
?>
</head>
<body id="body">
<div id="wrapper">
<div><?php include "dashboardHeader.phtml"; ?></div>
<div id="bar">
Dashboard Home|
<?php
echo $this->ajaxLink('Club Roster | ',
'user/index',
array('update' => '#content',
'method' => 'post'),
array('format' => 'html')
);
?>
Google Docs|
Book Sale Management|
</div>
<div id="content" align="center">
<?php
echo $this->layout()->content;
?>
</div>
<div id="statusBar">
<?php
$userData = Zend_Registry::get('userData');
$name = $userData->name;
$role = $userData->role;
$status = 'Logged in as: '.' Name: '.$name.' Role: '.$role;
echo $status;
?>
<br />
Logout
</div>
<div><?php include "dashboardFooter.phtml"; ?></div>
</div>
</body>
</html>
HTML <head> output:
<head>
<title>SOU Business Club - Member Dashboard</title>
<meta http-equiv="Content-type" content="text/html;charset=utf-8" >
<meta name="description" content="Business Club" >
<link href="/css/dashboardStyle.css" media="screen" rel="stylesheet" type="text/css" >
<link href="/js/jquery/css/smoothness/jquery-ui-1.8.11.custom.css" media="screen" rel="stylesheet" type="text/css" >
<link href="/css/dashboardStyle.css" media="screen" rel="stylesheet" type="text/css" >
<script type="text/javascript" src="/js/paginator.js"></script>
</head>
In your bootstrap you need to specify where jQuery is, either on your local machine or a CDN. Locally you use:
$view->jQuery()->setLocalPath(PATH);
Or you could use a CDN such as Google's: http://code.google.com/apis/libraries/devguide.html#jquery