I'm fairly new to PHP and I've been trying to construct some code to print basic HTML, however the code causes an error 500 whenever used. I am guessing it is a syntax error since I've tried the code in a couple of forms and nothing seems to work (including removing the database lookup and just trying to compare to set values to each other). The script needs to get a variable from the db, compare it to a set value and print the HTML if true, here is the code I am trying:
<?php
$db = &JFactory::getDBO();
$id = JRequest::getString('id');
$db->setQuery('SELECT #__categories.title FROM #__content, #__categories WHERE #__content.catid = #__categories.id AND #__content.id = '.$id);
$category = $db->loadResult(); ?>
<?php if strcmp($category,"Blog")==0 : ?>
<div style="display: -webkit-inline-box" class="sharelogos">
<img src="/images/sharing-icons/facebook.png" width="30px" alt="Facebook" />
</div>
<?php endif; ?>
Any help will be appreciated, thanks!
You if is incorrect, try like this
<?php if (strcmp($category,"Blog")==0) { ?>
<div style="display: -webkit-inline-box" class="sharelogos">
<img src="/images/sharing-icons/facebook.png" width="30px" alt="Facebook" />
</div>
<?php } ?>
Related
I have created a homepage editor tool in a script I purchased. The function of this homepage editor is to allow me to create different sections and display them one on top of the other in the order they are created. Which in hopes will give me an effect of several blocks that stretch width of the screen.
All seems to work well except one piece. I input my html and php code into the field in the admin panel and it saves to the db as I wrote it. However, when I go to echo each section back to the homepage it just displays my php code as plain text and doesn't interpret it as php and do its function.
Here is code from the homepage.php that prints the results.
<?php
session_start();
require_once("inc/config.inc.php");
if (isset($_GET['ref']) && is_numeric($_GET['ref']))
{
$ref_id = (int)$_GET['ref'];
setReferal($ref_id);
header("Location: index.php");
exit();
}
/////////////// Page config ///////////////
function get_all_section($section_id='')
{
$sql="SELECT * FROM `cashbackengine_homepage` WHERE 1";
if($section_id!="")
{
$sql.=" AND section_id='".$section_id."'";
}
$sql.=" AND section_status=1";
$sql.=" ORDER BY section_order ASC";
//echo $sql;
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$section_array[]=array(
'section_id' =>$row['section_id'],
'section_name' =>$row['section_name'],
'section_desc' =>$row['section_desc'],
'section_order' =>$row['section_order'],
'section_status' =>$row['section_status'],
'last_updated' =>$row['last_updated'],
);
}
return $section_array;
}
$get_all_section=get_all_section('');
/*$get_all_section2=get_all_section('2');
$get_all_section3=get_all_section('3');
$get_all_section4=get_all_section('4');
$get_all_section5=get_all_section('5');*/
for($i=0; $i<count($get_all_section);$i++)
{
//echo htmlspecialchars_decode($get_all_section[$i]['section_desc']);
//echo htmlspecialchars_decode(stripslashes(str_replace(" ","",(str_replace("<br />","\n",$get_all_section[$i]['section_desc'])))));
echo $get_all_section[$i]['section_desc'];
}
?>
I am certain the problem has to do with the echo at the end. But I am unsure how to use htmlspecialchars to make it work with php if it even will. Or if I have to put something weird in my saved section.
Here is one of my sections. Any help is greatly appreciated. Thank you.
<div style="height:260px; width:100%; background-color:#000; margin:0px; color:white;">
<div id="header">
<div id="logo"><img src="<?php echo SITE_URL; ?>images/logo.png" alt="<?php echo SITE_TITLE; ?>" title="<?php echo SITE_TITLE; ?>" border="0" /></div>
<div class="start_saving">
<div id="links">
<?php if (MULTILINGUAL == 1 && count($languages) > 0) { ?>
<div id="languages">
<?php foreach ($languages AS $language_code => $language) { ?>
<img src="<?php echo SITE_URL; ?>images/flags/<?php echo $language_code; ?>.png" alt="<?php echo $language; ?>" border="0" />
<?php } ?>
</div>
<?php } ?>
<div id="welcome">
<?php if (isLoggedIn()) { ?>
<?php echo CBE_WELCOME; ?>, <span class="member"><?php echo $_SESSION['FirstName']; ?></span><!-- | <?php echo CBE_ACCOUNT ?>--> | <?php echo CBE_BALANCE; ?>: <span class="mbalance"><?php echo GetUserBalance($_SESSION['userid']); ?></span> | <?php echo CBE_REFERRALS; ?>: <span class="referrals"><?php echo GetReferralsTotal($_SESSION['userid']); ?></span>
<?php }else{ ?>
<a class="signup" href="<?php echo SITE_URL; ?>signup.php"><?php echo CBE_SIGNUP; ?></a> <a class="login" href="<?php echo SITE_URL; ?>login.php"><?php echo CBE_LOGIN; ?></a>
<?php } ?>
</div>
</div></div>
</div>
It looks like you're getting these section contents pieces out of your database, and not from a file stored on your web server. Is that correct?
Assuming that's true, then my next question would be, who populates this data? Is this taken in any way from user input? The reason why I ask is because of my next suggestion, which may or may not be received well.
The reason why your PHP code isn't executing, is because it's being retrieved from the database and output as a string, not as code. So how do you execute code that's stored in a string, you ask? Well, the answer to that question is to use eval() on the string. But this is where you have to be really careful!!!!!!! If any part of that string could have possibly come from an untrusted source, then malicious PHP code could be executed, which could potentially give evildoers a way into your server, where they can find all the information in your database, server, etc. Make sure you know where your code is coming from before executing it!
You make a good point that it's HTML mixed with PHP. So I see two possible solutions...
This post suggests that you could do eval(' ?>'. $section .' <?php'); This makes sense, you're breaking out of PHP before you eval your string, and so requiring the included string to open its own PHP tags to write PHP code.
Another way I can think of would be to throw the contents into a temporary file, and then include() that file:
// get contents, store in $contents
$filename = tempnam(sys_get_temp_dir(), 'section');
file_put_contents($filename, $section);
include($filename);
unlink($filename);
I'm new to PHP and MySQL so i'm not quite sure what i am doing wrong here. I am using the jQuery plugin quicksand to create a filterable portfolio. The plugin uses custom data attribute data-tag inside the li item to populate the filter nav.
What I am trying to do is use a foreach loop to populate the contents of the ul. The problem is that the filter nav won't auto populate when I use php to get the value of the data attribute from the gallery_tag column in my mySQL table.
<?php
$pagetitle = "Red Penguin - Our Work";
$navcurrent = "work";
$headTitle = "RECENT WORK";
$headsubTitle = "SOME OF OUR RECENT WORK";
include_once('includes/headersub.php');
include_once('includes/connection.php');
include_once('includes/project.php');
$project = new Project;
$projects = $project->fetch_all();
?>
<div class="row">
<nav id="filter"></nav>
<section id="container">
<ul id="stage" class="three-up">
<?php foreach($projects as $project) { ?>
<li class="gallerylist" data-tag="<?php echo $project['gallery_tag']; ?>">
<a href="project.php?id=<?php echo $project['gallery_id']; ?>">
<img src="<?php echo $project['gallery_thumb']; ?> " alt="<?php echo $project['gallery_proj']; ?>" />
<?php echo $project['gallery_title']; ?>
</a>
</li>
<?php } ?>
</ul>
</section>
The error that comes up in the log is in the jquery line:
tags = elem.data('tags').split(',');
The log comes back with this error: "Uncaught TypeError: Cannot call method 'split' of undefined" for the above line.
I'm not quite sure why this is a conflict that causes the jquery to be unable to read the value of the data-attribute as taken from the gallery_tag column of my table. Any help would be appreciated.
I guess there is a spelling mistake in your html you have data-tag and you are trying to get the elem.data('tags') it should be elem.data('tag')
your elem.data('tags') returns undefined. So split() would not work on it.
Maybe I'm wrong, but I think you need: tags = elem.data('tags').split(' ');
I hope the title I used here was understandable...
I have a database with two columns: ward_id and ward_name.
I wish to create dynamic pages for each ward and have the ward_name show in the page title. I have created a header.php file which I am including.
I am passing the id through the URL using ....?wid={$row['ward_id']} which is working fine when I create other queries that use that id to get data from the database.
However the problem I am having is that the page refuses to display the ward_name as the page title. I expected something like this to work:
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$pagetitle = "$row['ward_name']";
}
But it doesn't, I have tried so many variations on the above I can't possibly remember them all now so I really hope someone can help me... Here is the code as it currently stands:
Header Page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title><?php echo $pagetitle; ?></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wholepage">
<div class="headlinewrapper">
<div class="headline">
<h1></h1>
<h2></h2>
</div>
</div>
<div class="headlinesidewrapper">
<div class="headlineside">
<p>shv jsfj sjnsf jnsf nsnf nj njsfn
njfjn sfns njf njnsf njs dgbjn dn jnd njjn dd d d nj njd njnd njd nn djndj njd</p>
</div>
</div>
<div class="topnavigation">
<ul>
<li>Home</li>
<li>Boroughs</li>
<li>Wards</li>
</ul>
</div>
<div class="sidebar">
</div>
<div class="mainpagewrapper">
Dynamic page:
<?php
$pagetitle = "Hello";
include ('header.php');
?>
<div class="mainpage">
<div class="infobox">
</div>
<?php
require('mysqli_connect.php');
mysql_select_db('onetwom2_london');
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
echo "<div class=\"boroughlist\"><p>{$row['ward_name']}</p></div>" ;
}
$pagetitle = $result;
?>
<div class="clear">
</div>
</div>
</div>
</div>
</body>
</html>
So I just want to know how/if it is possible to match the id passed through the URL to the ward_id stored on the database and then have the page title display the ward_name linked to that id. I apologise if this is a really easy question, I have spent hours trying to work this out and I am completely stumped! (the code I posted above is just the end result of 5 hours of frustration so please appreciate I have tried hard before asking you for help :) )
You should step through the problem to see where it goes awry, var-dump $pagetitle in the while loop. See what is being stored if it comes out as NULL you are not retrieving anything from the DB and there is an issue with either Query. if it has the correct variable the problem is with your PHP. Var_dump $pagetitle in your header.php file to be sure it is getting the correct variable.
Let me know the outcome and I can help you from there
<?php
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$pagetitle = "$row['ward_name']";
//Step Through The Problem
var_dump($pagetitle);
}
include ('header.php');
?>
<div class="mainpage">
<div class="infobox">
</div>
<?php
require('mysqli_connect.php');
mysql_select_db('onetwom2_london');
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
echo "<div class=\"boroughlist\"><p>{$row['ward_name']}</p></div>" ;
}
$pagetitle = $result;
?>
<div class="clear">
</div>
</div>
UPDATED - Try This
<?php
require('mysqli_connect.php');
mysql_select_db('onetwom2_london');
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$pagetitle = $row['ward_name'];
//Step Through The Problem
var_dump($pagetitle);
}
include ('header.php');
?>
<div class="mainpage">
<div class="infobox">
</div>
<?php
$result2 = mysql_query($query);
while ($row2=mysql_fetch_array($result2))
{
echo "<div class=\"boroughlist\"><p>{$row2['ward_name']}</p></div>" ;
}
?>
<div class="clear">
</div>
</div>
Do yourself a favor and use some ORM or library that gives you parameterized queries.
This code opens you right up for SQL-injection attacks:
$wardid = $_GET['wid'];
$query = "SELECT ward_name, ward_id FROM wards WHERE ward_id=$wardid";
First of all, avoid using double quotes as much as possible. Use single ' quotes instead. Double quotes makes php look for variables in the string which will be parsed. Using single quotes, any variables in the string will be echo'd as plain text, increasing overall performance.
So,
instead of
$pagetitle = "$row['ward_name']";
you want to use
$pagetitle = $row['ward_name'];
The same here:
echo "<div class=\"boroughlist\"><p>{$row['ward_name']}</p></div>";
should be changed into:
echo '<div class="boroughlist"><p>'.$row['ward_name'].'</p></div>';
Using single quotes makes \" also obsolete, making the code more readable and it'll be easier to write.
For working with databases in PHP I recommend you to work with a MySQLi Class. Have a look at https://github.com/ajillion/PHP-MySQLi-Database-Class . It's easy to implement and the learning curve is low.
MySQLi is the successor of MySQL (which is deprecated by now). With MySQLi prepared statements got introduced which make your queries containing (user) input save against SQL Injection. PDO would be even better, but it's harder to use.
Regarding $wardid = $_GET['wid'];: Make sure the value is being interpreted as integer. So try this:
$wardid = (int) $_GET['wid']; // type cast to integer aka Type Juggling
$query = 'SELECT ward_name, ward_id FROM wards WHERE ward_id=`'.$wardid.'` LIMIT 1';
Notice the LIMIT 1. This limits the query to one result, making it perform better as it stops right after it has found a result.
Good luck on your way learning more about SQL and PHP :-)
Edit:
According to a comment from the questioner, I want to add a rewritten example of the code given in the question:
<?php
// I'll demonstrate how to use the MySQLi Class
require_once('mysqlidb.php');
// Connect to the database
$db = new Mysqlidb('host', 'username', 'password', 'databaseName');
// Get the wid from the uri
$wardid = $_GET['wid'];
// Fetch the page title from the db
$result = $db->where('ward_id', $wardid)->get('wards', 1);
$pagetitle = $result['ward_name'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo $pageTitle; ?></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- A templating engine like smarty would make things easier -->
<section class="whole-page">
<div class="headline-wrapper">
<div class="headline">
<h1></h1>
<h2></h2>
</div>
</div>
</section>
<div class="headline-sidewrapper">
<div class="headline-side">
<p>Lorem ipsum...</p>
</div>
</div>
<nav class="top-navigation">
<ul>
<li>Home</li>
<li>Boroughs</li>
<li>Wards</li>
</ul>
</nav>
<aside class="sidebar"></aside>
<section class="mainpage-wrapper">
<!-- Dynamic page part - I recommend using a separate template that will be included here -->
</section>
</body>
</html>
This is a basic example using the MySQLi Database Class. I recommend you to use a template engine like smarty to make jobs like this easier. Also consider reading 'Separation of concerns'.
I am currently creating a CMS.
Currently I have.
* Saved my images in mysql as app_image
* Saved the images as a URL to where the images are located
But creating MY INDEX PAGE only displays my link as a broken URL.
my code for this page:
<?php
include_once('include/connection.php');
include_once('include/article.php');
$article = new article;
$articles = $article->fetch_all();
?>
<html>
<head>
<title>testing</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
CMS
<ol>
<?php foreach ($articles as $article) { ?>
<li>
<a href="article.php?id=<?php echo $article['app_id']; ?>">
<img src="<?php echo $article['app_image']; ?>" height"100" width"100">
<?php echo $article['app_title']; ?>
</a> -
<small>
Posted: <?php echo date('l jS', $article['article_timestamp'] ); ?>
</small></li>
<?php } ?>
</ol>
<br><small>admin</small>
</div>
</body>
</html>
Can anyone see how I have gone wrong?
Thanks.
OK, I have done simalar thing and it is working just fine.
The code looks similar, and looks fine by me, now, maybe the link indeed is broken (maybe you didn't input the right upload link in DB)
I would go step by step and check that link (check if it is the right link). (with /path/name.ext)
If it is some help here is my case:
I put in DB post_id,post_title,post_contents, post_link
than i get that info with:
$query = $db->prepare ("SELECT bla bla FROM bla bla ORDER BY id DESC")
$query->execute();
$query->bind_result(everything that is selected seperated with ",");
(including $link)
<?php
while($query->fetch()):
?>
<a href="single-post.html" title="">
<img src="../images/<?php echo $link; ?>">
</a>
<?php
}
?>
NOW, the trick I did (to avoid problem is that i put inside DB only the name of file, the upload path is stored directly in HTML ("../images/")
Your code looks similar, and I think it should work, I think the problem is with link.
Var dump can come to the rescue here. Try this to see what the array key values should be set to for each of the elements in $article.
<?php foreach ($articles as $article) { ?>
echo '<pre>'; //just makes it a bit easier to read
var_dump($article); exit;
Hi am trying to go through a list of xml results and I am taking the id from these results and performing a query in my database to get more information. I have placed this into a foreach loop and then I have my while loop getting the mysql results. Everything works until I do the while loop. My page goes blank and I get no errors.. ANY help would be so appreciated!
Here is my code:
foreach($data->HotelList->HotelSummary as $info):
$hotelId = $info->hotelId;
$title=$info->name;
?>
<!---------------------------------------------------------------------->
<!-----------------Listed hotel results div----------------------------->
<!---------------------------------------------------------------------->
<div class="listResults">
<div class="hotelListing">
<div class="hotelThumb">
<?php
//----------Getting thumb url from database by HotelId-------
$getImages = mysql_query("SELECT Caption FROM HotelImages WHERE ID = '4110'") or die(mysql_error());
while($r=$mysql_fetch_array($getImages)):
$img = $r['Caption'];
?>
<img src="" width="200" height="180" alt="test image" class="thumb" />
<?php endwhile; ?></div>
<?php endforeach; ?>
Just as a note, I have tried to get num_rows and I do get the correct result. SO the query is executing, but something is happening in the while loop.
Your while loop is bad. Take out the $ in front of the function.
while($r=mysql_fetch_array($getImages)):
Your main problem is that you put a $ in front of a method call ($mysql_fetch_array()). It should just be mysql_fetch_array().
An important issue that you shouldn't overlook is that you have a static query being called within a loop. Perform the query outside of your loop, since the results will never change. You can then store the results in an array and iterate through the array within your loop. This will significantly improve your code's performance.
<?php
//----------Getting thumb url from database by HotelId-------
$getImages = mysql_query("SELECT Caption FROM HotelImages WHERE ID = '4110'") or die(mysql_error());
$images = array();
while($img = mysql_fetch_array($getImages)) {
$images[] = $img['Caption'];
}
foreach($data->HotelList->HotelSummary as $info):
$hotelId = $info->hotelId;
$title=$info->name;
?>
<!---------------------------------------------------------------------->
<!-----------------Listed hotel results div----------------------------->
<!---------------------------------------------------------------------->
<div class="listResults">
<div class="hotelListing">
<div class="hotelThumb">
<?php
foreach($images as $img) :
?>
<img src="" width="200" height="180" alt="test image" class="thumb" />
<?php endforeach; ?></div>
<?php endforeach; ?>
while($r=$mysql_fetch_array($getImages)):
$img = $r['Caption'];
?>
You have a $ before the mysql_fetch_array(), removing that should fixed your problem.