Duplicate dynamic Link - php

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

Related

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

How to populate multiple items on a different page using a search bar?

Hi I was wondering if anyone could help. I have just developed a search bar for my site which will be on every page loaded using an include function so they will all be the same. The code can read my database perfectly but I am at a lose on how to send more than one result to another page in the format that I need. The problem is that I post 2 to 3 variables to the next page in the url for each link of this sort and if the search bar returns more than 1 result then each result will need 2 to 3 variables to populate the next page.
Link example
Movies Home
Here is the search bar code.
<?php
if(isset($_POST['search_term'])){
$search_term = $_POST['search_term'];
if (!empty($search_term)) {
$query = "SELECT title FROM database WHERE title LIKE '%".mysql_real_escape_string($search_term)."%'";
$query_run = mysql_query($query);
$query_num_rows = mysql_num_rows($query_run);
$result = mysql_query($query_num_rows);
if ($query_num_rows >= 1) {
echo $query_num_rows.' results found:<br>';
while ($query_row = mysql_fetch_assoc($query_run)){
echo $query_row ['title']. '<br>';
}
}
else{
echo 'No results found.';
}
}
}
?>
This code currently echos on the current page. I am hopeing to pass it to a results page and populate multiple items depending on how many results were found in the search bar. Here is an example of the code that I would be hopeing to populate from the search bar on the target page.
<?php
if (isset($var1)){
$subject_set = mysql_query("Select * FROM database WHERE genre like '%".$info."%' and media = '".$med."' ORDER BY ".$sort." ", $connection);}
else{
$subject_set = mysql_query("Select * FROM media", $connection);
}
if (!$subject_set){
die("Database connection failed: " . mysql_error());
}
htlm code</div>
<?php } ?>
I was thinking that if I was even able to pass the results id's using an array and then retrieve the corrosponding results from the database on the target page.
Sorry I am still quite a novice at this type of coding and I hope I did not confuse anyone with what I am trying to say. Thank you for your time and hopefully I can get this problem sorted. Thanks again.
If you want to display the results on other pages, consider putting them in SESSION variables.
<?php
session_start ( ); // at top of page
...
$theIndex=0;
while ($query_row = mysql_fetch_assoc($query_run)){
echo $query_row ['title']. '<br>';
$_SESSION['searchResult'][$theIndex] =$query_row ['title'];
$theIndex++;
}
Then on your the page where you want to display the results, loop through the SESSION['searchResult'] and echo it out...
<?php
session_start ( ); // at top of page
$theResults = $_SESSION['searchResult'];
foreach ($theResults as $key=>$value){
echo htmlentities($value) . "<br>";
}

PHP MySQL omit result if contains phrase

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)

How to select certain fields from table in mySQL using PHP

I'm trying out my hand at php at the moment - I'm very new to it!
I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.
For example:
I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.
I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant
echo $row['name']." ";
echo $row['DOB']." "; etc etc
next to where it should go?
I have got php to include data into an array (I think?!)
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['DOB']." ";
echo $row['Fruit']." ";
}
?>
Just place this (or whatever your trying to display):
echo $row['name']." ";
Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.
<h1>This is a the name <?php echo $row['name']." ";?></h1>
If you want to access your data later outside the while-loop, you have to store it elsewhere.
You could for example create a class + array and store the data in there.
class User {
public $name, $DOB, $Fruit;
}
$users = new array();
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user = new User;
$user->name = $row["name"];
$user->DOB = $row["DOB"];
$user->Fruit = $row["Fruit"];
$users[$row["name"]] = $user;
}
Now you can access the user-data this way:
$users["USERNAME"]->name
$users["USERNAME"]->DOB
$users["USERNAME"]->Fruit

Can these database calls be optimized?

I'm working on a project to further learn php and how it can be used to interface with a mysql database. The project is a forum, with the page in question displaying all the topics in a category. I'd like to know if I am handling my calls efficiently, and if not, how can I structure my queries so they are more efficient? I know its a small point with a website that isn't used outside of testing, but I'd like to get a handle on this early.
<?php
$cid = $_GET['cid'];
$tid = $_GET['tid'];
// starting breadcrumb stuff
$catname = mysql_query("SELECT cat_name FROM categories WHERE id = '".$cid."'");
$rcatname = mysql_fetch_array( $catname );
$topicname = mysql_query("SELECT topic_title FROM topics WHERE id = '".$tid."'");
$rtopicname = mysql_fetch_array( $topicname );
echo "<p style='padding-left:15px;'><a href='/'> Home </a> » <a href='index.php'> Categories </a> » <a href='categories.php?cid=".$cid."'> ".$rcatname['cat_name']."</a> » <a href='#'> ".$rtopicname['topic_title']. "</a></p>";
//end breadcrumb
$sql = "SELECT * FROM topics WHERE cat_id='".$cid."' AND id='".$tid."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) == 1) {
echo "<input type='submit' value='Reply' onClick=\"window.location = 'reply.php?cid=".$cid."&tid=".$tid."'\" />";
echo "<table>";
if ($_SESSION['user_id']) { echo "<thead><tr><th>Author</th><th>Topic » ".$rtopicname['topic_title']."</th></thead><hr />";
} else {
echo "<tr><td colspan='2'><p>Please log in to add your reply.</p><hr /></td></tr>";
}
echo "<tbody>";
while ($row = mysql_fetch_assoc($res)) {
$sql2 = "SELECT * FROM posts WHERE cat_id='".$cid."' AND topic_id='".$tid."'";
$res2 = mysql_query($sql2) or die(mysql_error());
while ($row2 = mysql_fetch_assoc($res2)) {
echo "<tr><td width='200' valign='top'>by ".$row2['post_creator']." <hr /> Posted on:<br />".$row2['post_date']."<hr /></td><td valign='top'>".$row2['post_content']."</td></tr>";
}
$old_views = $row['topic_views'];
$new_views = $old_views + 1;
$sql3 = "UPDATE topics SET topic_views='".$new_views."' WHERE cat_id='".$cid."' AND id='".$tid."' LIMIT 1";
$res3 = mysql_query($sql3) or die(mysql_error());
echo "</tbody></table>";
}
} else {
echo "<p>This topic does not exist.</p>";
}
?>
Thanks guys!
Looks like a classic (n+1) query mistake that could die a latent death. You get a key using one round trip, then you loop over the results to get n values based on it. If the first result set is large you'll have a lot of network round trips.
You could bring it all back in one go with a JOIN and save yourself a lot of network latency.
The statements themselves are fairly simple so there's not much you can do to optimize them further that I know of. However, if you create some business objects and cache the data into them on a single call and then access data from the business objects then it could be faster.
In other words, 1 SQL call for 1,000 rows is going to be much faster than 1,000 calls for a single row.
Here are some of extra things I would do when I write a code like above:
Never use * in SELECT statement when you know the columns you are going to use.
Always use or die(mysql_error()) when executing the query.
Unset the result sets once the result sets has served its purpose.
Use mysql_real_escape_string() to escape the injections when using some substitutions in your queries.

Categories