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'.
Related
I am trying to learn php together with MYSQL. I have built the database on on the from end I have written the code below to bring in the website title from the database which works. However, I have two questions.
How would I get the result to display in <h1> tags?
Is this the cleanest way of pulling this value through?
Any help or advise greatly appreciated
<?php
include 'connection.php';
$sql = "SELECT VariableValue FROM VariableValues WHERE VariableID = '1'";
$result = $conn->query($sql);
while($header = $result->fetch_assoc()) {
echo $header["VariableValue"]. "<br>";
}
?>
To get a single row from db, you could use this:
$header_title = implode(mysqli_fetch_assoc(mysqli_query($conn, "SELECT VariableValue FROM VariableValues WHERE id = 1 LIMIT 1")));
Put a php variable between a html tag :
<tag><?php echo $var; ?></tag>
Eg :
<title><?php echo $header_title; ?></title>
You can echo all types of tags in PHP echo
for example:
echo '<div class="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div id="success_alert" align="center" class="alert alert-success">
<strong>Log in to download this chapter.</strong>
</div>
</div>';
I have echoed different types of bootstrap tags in echo. Similarly you can also echo all types of tags you want.
To displays it in tags, use <h1><?php echo $var; ?></h1> for example.
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 an issue with bootstrap and creating a 4 column responsive grid from a mysql response.
The problem is that if the second mysql query has a variable number of results, it brakes the grid.
Here is my code (where the first query has 9 results and the second query has a variable number of results):
<?php
$a = "SELECT * FROM $table_users ORDER BY username";
$result = mysql_query($a);
?>
<div class="container">
<div class="row">
<?php while ($row = mysql_fetch_array($result)) {?>
<div class="col-xs-3" style="background-color:aqua;">
<?php echo $row['username'];
$b = "SELECT * FROM $table_presents WHERE bought_for='$row[username]' OR bought_for='' ORDER BY id";
$result_presents = mysql_query($b) or die(mysql_error());
while ($row_presents = mysql_fetch_array($result_presents)) {
?>
<div style="background-color:red;">
Hello world!
</div>
<?php }?>
</div>
<?php }?>
</div>
</div>
which gives me this:
enter image description here
instead of this (obviously with many 'Hello world'):
enter image description here
Any help greatly appreciated!
Bootstrap doesn't claim to do any kind of elegant bin-packing on panels with different sizes. You could do some programming or css work to make all your panels the same size.
If that doesn't work for your application, you're going to need a layout library that does bin-packing so these panels of different sizes align properly.
There are a few such libraries available as jQuery plugins.
In this, $row[username] is wrong as it should be $row['username'].
$b = "SELECT * FROM $table_presents WHERE bought_for='$row[username]' OR bought_for='' ORDER BY id";
BTW, I changed your code bit. Please Try this.
<?php
$a = "SELECT * FROM $table_users ORDER BY username";
$result = mysql_query($a);
?>
<div class="container">
<div class="row">
<?php while ($row = mysql_fetch_array($result))
{
$username=$row['username'];
?>
<div class="col-xs-3" style="background-color:aqua;">
<?php echo $username;
$b = "SELECT * FROM $table_presents WHERE bought_for='$username' OR bought_for='' ORDER BY id";
$result_presents = mysql_query($b) or die(mysql_error());
while ($row_presents = mysql_fetch_array($result_presents)) {
?>
<div style="background-color:red;">
Hello world!
</div>
<?php }?>
</div>
<?php }?>
</div>
</div>
[NOTE: Users can inject your SQL commands. Use prepared statements and parameterized queries. For more info, click Prevent SQL Injections
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.
I have a list of names in a database that i want to display one by one
(also for bonus points, another column in the database is a Boolean value for if a task is completed or not. if this is true i want the css content box background to be green instead of red.)
so how can i select a name from row one, put it to a PHP variable, then select the value from the "Name" column in row 2 and put that to another PHP variable or the next item in the array?
thanks for any help!
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="mngPWinCSS.css"/>
</head>
<body>
<?php
$dsn ='mysql:host=****.******.com;dbname=o****_**n';
$username='********';
$password ='******';
mysql_connect('localhost',$username,$password);
$query=mysql_query("SELECT Name FROM CLOAS_Team LIMIT 0,1");
$bob="dkajfk";
$url=$_SERVER['REQUEST_URI'];
header("Refresh: 60; URL=$url");
$com[1]="i";
$com[2]="i";
$com[3]="i";
$com[4]="i";
$com[5]="i";
$com[6]="i";
$name=mysql_fetch_array($query);
?>
<div id="content">
<img src="logjpg.JPG" alt="Smiley face" height="50" width="200">
<h3>CLOAS Tracker</h3>
</div>
<div id="Content">
<?php
?>
<div id="complete">
<h3names>
<?php
echo $name['Name'];
?>
</h3names>
</div>
<div id="incomplete">
<h3names>Name2</h3names>
</div>
</div>
</body>
</html>
First you need to change your SELECT query to select all of the rows that you wish to display, perhaps by taking off the LIMIT clause. Something like this;
$result=mysql_query("SELECT Name FROM CLOAS_Team");
(This will get you all of the names in your table.)
Next, you need to loop through the results you got from this query, like so;
$names = array();
while($row = mysql_fetch_assoc($result))
{
$names[] = $row['Name'];
}
This will put them into the array $names for you, which you can then work with. Instead of putting them into the array, you might want to output them immediately, perhaps like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div>
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>
However, you have many more errors in your code. Such as;
You can't just invent html elements called <h3names>
I doubt that you want to set the id attribute to 'incomplete'. An id should be unique, I expect you should be putting this in as a class (class = "incomplete")
I don't think your line header("Refresh: 60; URL=$url"); will do anything as your headers have already been sent to the page. If you want this line to work, it needs to be right at the top, BEFORE any output has been sent to the browser.
And for the bonus point, include the 'Completed' field in your query (if that is what it is called) and use this to add a style to each <div> element that you display in your loop. So your query might become;
$result=mysql_query("SELECT Name, Completed FROM CLOAS_Team");
And your loop would now be like this;
while($row = mysql_fetch_assoc($result))
{ ?>
<div style = "background-color:<?php echo $row['Completed'] == true ? 'green' : ' red'; ?>">
<h3>
<?php
echo $row['Name'];
?>
</h3>
</div>
<?php } ?>