I need some help with some PHP and MySQL code. At the moment I have a php file which displays the contents of a table in my database. I would like it to omit results that match "Not Booked". So the file only shows me slots which are booked. Here is my code:
<link href="../css/pagestyle.css" rel="stylesheet" type="text/css" />
<?php
include("../config.php");
include("functions.php");
if($logged["level"] == "HDJ" OR $logged["level"] == "SA") {
echo "<div class=\"head\">View Booked Slots</div>
<img src=\"../images/spacer.png\" width=\"5\" height=\"5\">
<div class=\"board\">Here you can view booked slots.</div>
<img src=\"../images/spacer.png\" width=\"5\" height=\"5\">
<table width=\"580px\" class=\"board\" border=\>";
$order = "SELECT * FROM timetable";
$result = mysql_query($order);
while ($row=mysql_fetch_array($result)){
echo ("<tr><td>$row[username]</td>");
</tr>");
}
echo "
</table>
";
} else {
echo ("<div class=\"caution\">Access is denied.</div>");
}
?>
Modify the query not to pull them in the first place.
$order = "SELECT * FROM timetable WHERE <the column> <> 'Not Booked';
Replace <the column> with the correct column name in your table where Not Booked appears.
It is often not advisable to intermix database logic and display logic as you have done here. Instead, you ought to do the query before outputting your table, and store its results in an array. Then loop over the array to display your table.
$order = "SELECT * FROM timetable WHERE somecolumn <> 'Not Booked'";
$result = mysql_query($order);
// Error checking
if (!$result) {
// output error, take other action
}
else {
while ($row=mysql_fetch_array($result)){
// Append all results onto an array
$rowset[] = $row;
}
}
Later, loop over the array to output your values. Dont' forget to escape it for HTML output with htmlspecialchars().
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td></tr>";
}
In your mySQL code:
SELECT * FROM timetable WHERE myvariable <> 'Not Booked'
Michael's answer will only pull out results that MATCH 'Not Booked' rather than omit them. Tweak the code to:
$order = "SELECT * FROM timetable WHERE <the column> <> 'Not Booked';
And you'll get all the booked ones (assuming there are only two states)
Related
The php-code below finds and displays an external url as a link from a database. Sometimes there is a phonenumber instead of an url in that row. How can I manage to echo out the phonenumber without making it to a link. I guess it will work with if and else but I'm not finding out how to display it the right way. My code below:
<?php
$ticketurl = $row ['show_external_url'];
$query = mysqli_query( $connection,"SELECT *, DATE_FORMAT(`show_date`, '%W (%d/%m/%y)') as dateFormatted
FROM nhto_gigpress_shows
WHERE `show_date` >= CURDATE()
AND WEEKDAY(nhto_gigpress_shows.show_date) >= 5
ORDER By show_date" );
$row = mysqli_fetch_array( $query ); {
echo "<a href='".$ticketurl."'>BOOK</a>";
}
?>
Try to check whether the column has any data or not and use condition
inside the while loop:
if(empty($row['url'])){
echo $row['phone'];
}
else{
echo 'BOOK';
}
I am trying to combine two things which are already know how to do, but can't figure out how to combine them. Here is what I want to achieve:
I have a database with locations and events. There are several events in each location. I will be using PHP to query the database and output the code needed to display search results. I want something similar to the below:
<div id="location">
<p>Location1</p>
<div id="event">Event1</div>
<div id="event">Event2</div>
<div id="event">Event3</div>
</div>
<div id="location">
<p>Location2</p>
<div id="event">Event4</div>
<div id="event">Event5</div>
<div id="event">Event6</div>
</div>
I know that I can use select distinct to get the unique value of each location, and know that I can use a normal select statement to get all the events, however how do add all the events inside the location div?
My current PHP looks like this:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)){
$location = $row['location'];
$event = $row['event'];
echo "<div id="location">
<p>$location</p>
<div id="event">$event</div>
</div>";
}
My current code adds duplicates of the same location with 1 unique event in each. Even if I use select distinct I get the same results. How do I group the events have have the same location?
I think you should write something like:
$sql ="SELECT location, event from events";
$res = mysql_query($sql) or die(mysql_error());
$prevlocation = "";
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
if ( $prevlocation != "" ) // Close previous div if needed
{
echo "</div>";
}
if ( $location != $prevlocation )
{
echo "<div id='location'><p>$location</p>";
$prevlocation = $location;
}
else
{
echo "<div id='event'>$event</div>";
}
}
echo "</div>"; // Close last div
If you have join of two tables, let's assume that your query looks like this:
$sql ="SELECT * FROM events
JOIN locations ON
locations.id=events.loc_id";
And then, within one loop, get events and location arrays:
$res = mysql_query($sql) or die(mysql_error());
$locations = array();
$events= array();
while($row = mysql_fetch_assoc($res))
{
$location = $row['location'];
$event = $row['event'];
$loc_id=$row['loc_id'];
$id=$row['id'];
$events[]=$loc_id.'%'.$event;
if(!in_array($id.'%'.$location,$locations)) { // avoid duplicate entries
$locations[]=$id.'%'.$location;
}
}
And, another loop (+loop inside loop):
for($i=0;$i<count($locations);$i++) {
$location=explode('%',$locations[$i]);
echo "<div class='location'>\n
<p>$location[1]</p>\n";
for($j=0;$j<count($events);$j++) {
$event=explode('%',$events[$j]);
if($event[0]==$locations[$i][0]) {
echo "<div class='event'>".$event[1]."</div>";
}
}
echo "</div>";
}
Not so elegant, but it is working, and produces valid HTML. :)
First, i wanted to make two associative arrays, and to compare keys, but i couldn't, because i couldn't convert ID keys to strings, so i made it with explode (% is separator between key and value).
I'm trying to echo out multiple rows from a sql database, but I get the error Warning. Illegal string offset 'Date' In....
$channel_check = mysql_query("SELECT content, Date FROM wgo WHERE Posted_By='$user' ORDER by `id` DESC;");
$numrows_cc = mysql_num_rows($channel_check);
if ($numrows_cc == 0) {
echo '';
// They don't have any channels so they need to create one?><h4>                                                                                                             You haven't posted anything yet. You can post what's going on in your life, how you're feeling, or anything else that matters to you.</h4>
<?php
}
else
{
?>
<div id="recentc">
</div>
<?php
echo"<h2 id='lp'> Latest Posts</h2>";
while($row = mysql_fetch_array($channel_check)) {
$channel_name = $row['content']['Date'];
?>
<div style="margin-top:60px;">
<hr style="margin-right:340px;width:600px; opacity:0;">
<?php echo "<div id='rpc'><h6> $channel_name</h6></div>";?>
</div>
<?php
}
}
?>
DATE is a datatype in SQL, you need to escape it with back ticks
SELECT content, `Date` FROM wgo WHERE Posted_By='$user' ORDER by `id` DESC
Also, you're accessing your row incorrectly. Rows are typically represented by a uni-dimensional array, so $row['content'] and $row['Date']
$row is 1-dimensional array with 2 fields: content and Date.
Try,
while ($row = mysql_fetch_array($channel_check)) {
print_r($row);
//$channel_name = $row['content']['Date'];
ok i got this page working well but what would do i have to do to display data from a certain letter?
here is the code i got at present
<html>
<head>
<title>MySQLi Read Records</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = "select * from contacts";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results > 0){ //it means there's already a database record
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th>Username</th>";
echo "<th>Action</th>";
echo "</tr>";
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$name}</td>";
echo "<td>{$surname}</td>";
echo "<td>{$mobile}</td>";
echo "<td>";
//just preparing the edit link to edit the record
echo "<a href='edit.php?id={$id}'>Edit</a>";
echo " / ";
//just preparing the delete link to delete the record
echo "<a href='#' onclick='delete_user( {$id} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
</body>
</html>
i am wanting to place multiple entries like the following to dislay under the right letter
<h1>A</h1>
echo "<td>{$name}</td>";
echo "<td>{$surname}</td>";
echo "<td>{$mobile}</td>";
<h1>b</h1>
echo "<td>{$name}</td>";
echo "<td>{$surname}</td>";
echo "<td>{$mobile}</td>";
ECT ECT
what i am trying to acchieve is to dispaly all the surnames that begin with a then b
i have found this bit of code on this page http://www.sitepoint.com/forums/showthread.php?303895-Display-Data-Beginning-with-a-Particular-Letter
but how would i make this work for me?
i am novice (extremly) so any help be fantastic i tried to read tutorials i find it better with hands on :)
Updated ***************************
this is working great but now it only lists one line this is my code
<html>
<head>
<title>MySQLi Read Records</title>
</head>
<body>
<?php
//include database connection
include 'db_connect.php';
//query all records from the database
$query = " SELECT name,
surname,
mobile,
UPPER (LEFT(surname, 1)) AS letter
FROM contacts
ORDER BY surname";
//execute the query
$result = $mysqli->query( $query );
//get number of rows returned
$num_results = $result->num_rows;
//this will link us to our add.php to create new record
echo "<div><a href='add.php'>Create New Record</a></div>";
if( $num_results > 0){ //it means there's already a database record
echo "<table border='1'>";//start table
//creating our table heading
//loop to show each records
while( $row = $result->fetch_assoc() ){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<h1>', $row['letter'], '</h1>';
$lastLetter = $row['letter'];
echo "{$surname}";
}
}
}else{
//if database table is empty
echo "No records found.";
}
//disconnect from database
$result->free();
$mysqli->close();
?>
</body>
</html>
Since you are learning, I will give you the idea of how you can archive what you want and the functions you can use.
As you have mentioned you want all records displayed on the same page with their own alphabet letter as the header.
There is a few ways of doing what you want, the most common is to return the data ORDERed BY the field you want on the order you want, in this case ASC.
This will list all your records in alphabetical order.
From there you can use the function LEFT to extract the first letter as another field.
Now here is where you will use some PHP, from the above you already have your records ordered and the first letter for each record.
You can use something like this inside your while:
if (!isset($lastLetter) || $lastLetter != $row['letter'])
{
echo '<h1>', $row['letter'], '</h1>';
$lastLetter = $row['letter'];
}
Basically the above will check if $lastLetter has been set/defined which is not for the first record so it will enter the if, print your first header and set $lastLetter to the first letter.
After the first record it will be matching the $lastLetter against the $row['letter'] and once they are not equal, it prints the header again and update the $lastLetter with $row['letter'] which is the current letter.
Your MySQL query would look like this:
SELECT *,
LEFT(firstname, 1) AS letter
FROM contacts
ORDER BY firstname
However it is always better to define all fields you need instead of catching all the fields in case you have more fields on the table in question:
SELECT firstname,
surname,
mobile,
LEFT(firstname, 1) AS letter
FROM contacts
ORDER BY firstname
NOTE in case your names are not normalize you can use the UPPER function to make the letter uppercase like this:
SELECT firstname,
surname,
mobile,
UPPER(LEFT(firstname, 1)) AS letter
FROM contacts
ORDER BY firstname
See more about the UPPER function here
I suggest you do the following steps.
Update your mysql query statement
$query = "select * from contacts order by name_field";
Name_field or whatever is the column name so that you get the result set sorted in dictionary order.
Keep $previous to keep track of what letter you added last time.
Use this function (refer startsWith() and endsWith() functions in PHP) at each row to find whether the name value starts with a different letter from $previous. If there is a change then update $previous and include "" tags with the letter as you desire.
function startsWith($haystack, $needle)
{
return $needle === "" || strpos($haystack, $needle) === 0;
}
First of all you should change your SQL query to:
SELECT * FROM contacts ORDER BY name ASC
this will sort all of the contacts from A to Z. Now, to able to determine an initial alphabet of a contact name use substr function...
$initial_letter = strtoupper(substr($name, 0, 1));
I have a page displaying random bible quotes from which you can also search. The quotes on this page are displayed in dynamic link format, e.g. bible-query.php?id=200
On the search results page, I have put a link each at the bottom and top of the page to help the users get back to the random display page. These links are dynamic links. The only problem is, I can only get the top link to display the dynamic link, the bottom one just loads a page with no quotes.
What I want is to have the bottom and top 'Back' links display the same dynamic link location.
Here is the code I have for the search results:
<html>
<font face="arial">
<title>BQuotes: Random Bible Verses</title>
<?php
// db requirements
$db_host="localhost";
$db_username="username";
$db_password="password";
$db_name="name";
$db_tb_name="table";
$db_tb_atr_name="line";
$db_tb_atr_name2="book";
$db_tb_atr_name3="cap";
$db_tb_atr_name4="verse";
//do search task
mysql_connect("$db_host","$db_username","$db_password");
mysql_select_db("$db_name");
$query=mysql_real_escape_string($_GET['query']);
$query_for_result=mysql_query("SELECT * FROM $db_tb_name WHERE
$db_tb_atr_name like '%".$query."%' OR $db_tb_atr_name2 like '%".$query."%'
OR $db_tb_atr_name3 like '%".$query."%' OR $db_tb_atr_name4 like '%".$query."%'");
echo "Search Results<ol>";
// new bible query section begins
define ('HOSTNAME', 'localhost');
define ('USERNAME', 'username');
define ('PASSWORD', 'password');
define ('DATABASE_NAME', 'name');
$db = mysql_connect(HOSTNAME, USERNAME, PASSWORD) or die ('I cannot connect to
MySQL.');
mysql_select_db(DATABASE_NAME);
$query = "SELECT id,book,cap,verse,line FROM table ORDER BY RAND() LIMIT 1 ";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "<center><a href='bible-query.php?id=$row[id]'>Back</a></center> ";
}
//mysql_free_result($result);
//mysql_close();
//bible query new section ends
while($data_fetch=mysql_fetch_array($query_for_result))
{
echo "<li>";
echo substr($data_fetch[$db_tb_atr_name2], 0,160)," ";
echo substr($data_fetch[$db_tb_atr_name3], 0,160)," ";
echo substr($data_fetch[$db_tb_atr_name4], 0,160)," ";
echo substr($data_fetch[$db_tb_atr_name], 0,160);
echo "</li><hr/>";
}
echo "<center><a href='bible-query.php?id=$row[id]'>Back</a></center> ";
echo "</ol>";
//mysql_close();
?>
</font>
</html>
Please help!
Your while loop is fetching the row using mysql_fetch_array. On the first time it runs it retrieves a result and so the value of $row is set to an array and the conditional is "true" so the bit in the while loop runs. However, on the second run-through there is no second row and so $row is set to false and the while loop doesn't run. This means that after the while loop $row is an empty variable. When it gets to the second calling of that array it is empty. By removing the while loop the $row variable is only fetched once and the first row is returned. This is all you need.
Just change this bit:
while ($row = mysql_fetch_array($result)) {
echo "<center><a href='bible-query.php?id=$row[id]'>Back</a></center> ";
}
to:
$row = mysql_fetch_array($result);
echo "<center><a href='bible-query.php?id=$row[id]'>Back</a></center>";
and both parts should work.
Change your code to this. No need for a while loop since you are limiting 1 row in your query. Also I changed the php mysql function that you should use.
$query = "SELECT id,book,cap,verse,line FROM table ORDER BY RAND() LIMIT 1 ";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
echo "<center><a href='bible-query.php?id=$row[id]'>Back</a></center> ";
Noticed I used mysql_fetch_assoc