I have recently started using PHP to implement a basic ranking system. Here is my code:
review.php
<?php
require 'connect.inc.php';
mysql_select_db("conference");
$query = mysql_query("SELECT * FROM event");
$event = [];
while($row = mysql_fetch_array($query)){
$event [] = $row;
}
?>
<?php foreach($event as $events): ?>
<div class="event">
<h3><?php echo $events['eventName'];?><h3>
<div class="event-rating"> Rating: x/5</div>
</div>
<?php endforeach;?>
event.php
<?php
require 'connect.inc.php';
$event= null;
if(isset($_GET['eventID'])){
$id=(int)$_GET['eventID'];
$event = mysql_query("SELECT * FROM event WHERE eventID = {$id}")->fetch_object();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<?php if($event):?>
<div class="event">
This is Event "<?php echo $event['eventName'];?>"
<div class="event-rating"> Rating: x/5</div>
<div class="event-rate"> Rating: x/5</div> Rate this Event:
<?php foreach(range(1,5)as $rating):?>
<?php echo $rating; ?>
<?php endforeach ?>
</div>
<?php endif;?>
</body>
</html>
The problem I have is that nothing is outputting onto the webpage, whereas it should display a rating page from 1 to 5. I believe the problem lies within the ->fetch_object(); line because this had been causing me problems before so I used alternatives such as mysql_fetch_array.
I also tried starting again using PDO and mysqli connections but still not having any luck.
If anyone could provide any advice it would be greatly appreciated.
Also, if anyone can explain ->fetch_object(); that would be very useful as there isn't much explanation online.
OK, this one is going to be a tricky one to explain, since it appears as though you don't have a basic understanding of how PHP's mysql_* functions work.
In PHP, the -> operator is used to access properties and functions of an Object type. mysql_query() returns a Resource Identifier, which cannot be used as an object within PHP. Instead, you need to use the procedural mysql_fetch_object( $result ); function. However, later in your code, you try to use the returned object as an array, for example:
This is Event "<?php echo $event['eventName'];?>"
The next issue you face is that the mysql_* family of functions is now deprecated, and will soon be disappearing from new versions of PHP. As a result, you're much better off going with one of the newer libraries, such as PDO.
Your code can be rewritten in PDO, and I've taken the time to do that for you:
<?php
$db = new PDO('mysql:dbname=conference;host=127.0.0.1', 'username', 'password');
$result = $db->query( 'SELECT * FROM event' );
while( $event = $result->fetchObject() ):
?>
<div class="event">
<h3><?php echo $event->eventName ?><h3>
<div class="event-rating"> Rating: x/5</div>
</div>
<?php endwhile ?>
Similarly, inside of event.php, you should be using Prepared Statements to prevent SQL injection attacks on your site. For example:
<?php
$db = new PDO('mysql:dbname=conference;host=127.0.0.1', 'username', 'password');
if( isset($_REQUESR['eventID']) )
{
$sql = $db->prepare( 'SELECT * FROM event WHERE eventID = :eid' );
$sql->execute( array(':eid' => $_REQUEST['eventID']) );
$event = $sql->fetchObject();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<?php if($event):?>
<div class="event">
This is Event "<?php echo $event->eventName ?>"
<div class="event-rating"> Rating: x/5</div>
<div class="event-rate"> Rating: x/5</div> Rate this Event:
<?php foreach(range(1,5)as $rating):?>
<?php echo $rating; ?>
<?php endforeach ?>
</div>
<?php endif;?>
</body>
</html>
Hopefully the above friendly advice will help you with your learning and development with PHP.
Related
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 } ?>
I have this function that gets a table from another site by finding each row of that table and, providing that row isn't a duplicate, echos it to my site. I want to add my own row to the bottom though so I thought it would be as simple as just echoing
<tr><td>TEXT</td></tr>
as you can see below. But when I load the page, this row isn't added. Anyone know what the cause may be?
Here is the website if that helps.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key=>$element) {
if(!in_array($element, $rows)){
$rows[$key]=$element;
echo $rows[$key-1];
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
Main problem was in key offset, when you work with arrays it's better to use keys in this case. So in order to that I've changed the in_array to array_key_exists, because we want to check if key exists, but if you want to work with element you have to know its key.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key => $element) {
if(!array_key_exists($key, $rows)){
$rows[$key] = $element;
/* Echo only when it exists */
if(array_key_exists($key-1, $rows)){
echo $rows[$key-1];
}
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
?>
<?php
include "getData.php";
include "simple_html_dom.php";
?>
<!DOCTYPE HTML>
<html>
<head>
<title>KSA Flight Tracker</title>
<link rel="stylesheet" type="text/css" href="KSAStyle.css"/>
</head>
<body>
<div id="page">
<div id="leftPanel">
<p id="missionsHeader">Active Missions</p>
<?php getList(); ?>
</div>
<div id="mainPanel">
<p id="infoHeader">
<?php getTitle(); ?>
</p>
<div id="info">
<center>
<?php
getInfo();
getImage();
getMap();
getStats();
?>
</center>
</div>
</div>
</div>
</body>
</html>
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;
can someone please help me i am having problems creating my forum.
At the moment users can create posts, the post title is listed down the page and then the user is suppose to be able to click the title link and be taken to read_post.php and then this should take the user to another page where the post content can be viewed, i am trying to do this by echoing the forum post id but it doesnt seem to want to work, instead i get this error:
Database query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
can someonee please show me where im going wrong.
here is my sql function:
function read_forum() {
global $connection;
global $forum_id;
$query = "SELECT *
FROM ptb_forum, ptb_profiles
WHERE ptb_forum.id = $forum_id ";
$forum_set = mysql_query($query, $connection);
confirm_query($forum_set);
return $forum_set;
}
here is the link code that takes the user to read_post.php which suppose to echo the forum id and display the content for each individual post.
<?
$forum_set = get_forum();
while ($forum = mysql_fetch_array($forum_set)) {
?>
<div class="forumcase" id="forumcase">
<div class="pend-forum-content">
<?php echo "<strong>{$forum['title']}</strong> - Posted by {$user['first_name']}"; ?>
</div>
here's my code for read_post.php:
<?php
$page_title = "Read Post";
include('includes/header.php');
include ('includes/mod_login/login_form2.php'); ?>
<?php
confirm_logged_in();
if (isset ($_GET['frm'])) {
$forum_id = $_GET['frm'];
}
?>
<?php include('includes/copyrightbar.php'); ?>
<div class="modtitle">
<div class="modtitle-text">Messages Between <?php echo "{$forum['display_name']}"; ?> & You</div>
</div>
<div class="modcontent57">
<br /><br /><br/><br/>
<div class="forum">
<div class="forum-pic"><?php echo "<img src=\"data/photos/{$_SESSION['user_id']}/_default.jpg\" width=\"100\" height=\"100\" border=\"0\" align=\"right\" class=\"img-with-border-forum\" />";?>
</div>
<div class="message-links">
<strong><< Back to Forum
</div>
<br /><br /><br/><br/>
<?php
$datesent1 = $inbox['date_sent']; ?>
<?php
$forum_set = read_forum();
while ($forum = mysql_fetch_array($forum_set)) {
$prof_photo = "data/photos/{$message['user_id']}/_default.jpg";
$result = mysql_query("UPDATE ptb_forum SET ptb_forum.read_forum='1' WHERE ptb_forum.id='$forum_id'")
or die(mysql_error());
?>
<div class="message-date">
<?php echo "".date('D M jS, Y - g:ia', strtotime($message['date_sent'])).""; ?></div>
<div class="img-with-border-msg-read"><?php echo "<img width=\"60px\" height=\"60px\" src=\"{$prof_photo}\"><br />"; ?></div>
<div class="conversation-text">
<?php echo "<i>Conversations between you and </i>{$forum['display_name']}.<br /> "; ?></div>
<div class="message-content">
<?php echo "<strong>Message Subject: </strong><i>{$forum['subject']}</i>"; ?>
<br/>
<br/>
<br/>
<br/>
<?php echo "<strong>Message:<br/></strong></br ><i>{$forum['content']}</i>"; ?>
</div>
<div class="reply-box">
<? include ('message_reply.php'); ?>
</div>
<?php
}
?>
<br/>
<br/>
<br/>
</div>
</div>
<?php include('includes/footer.php'); ?>
</div>
You have an error in your query... Your parameter is not quoted...
$query = "SELECT *
FROM ptb_forum, ptb_profiles
WHERE ptb_forum.id = '$forum_id'";
However... I suggest that you refrain from using the mysql_ family of functions. They are deprecated and due to be removed from PHP in a future release. You should be using parameterized queries using MySQLi or PDO.
Also, global is evil. I've never had a need to use it in 10 years of PHP programming. Neither should you.