Display an image from the databse to results page - php

Is it possible for a user to input let's say 'Red Car' and it will find the image in the database and in php/html and in the search results it will show the image?
My code for "Search"
<?php
$query = $_GET['query'];
$min_length = 3;
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM articles
WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `title`, `text`
// articles is the name of our table
// '%$query%' is what I'm looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<div class='successmate'><h2></h2></a>
</div><br><br><br>";
echo "<div class='search69'><a href='../pages/{$results['page_name']}'><h2>{$results['title']}</h2></a><p>{$results['text']}</‌​p>";
}
}
else{ // if there is no matching rows do following
echo ("<br><br><div class='search1'><h2>No results</h2></br></br>");
}
}
else{ // if query length is less than minimum
echo ("<br><br><div class='search1'><h2>Minnimum Length Is</h2><h2>".$min_length);
}
?>
The images that I want to be found for keywords:
http://puu.sh/cCHv1/9f58d770f3.jpg
These are the names of the images in the DB:
http://puu.sh/cCHwa/a82d2cc7fe.png
Thanks!

Without testing I'd say you have your search function down, to display the results would be a simple matter simply put the below code where you would want to display the image results (This will only be for displaying the images, but to get it to work with other results is a simple rework)
<?php
while($data = $result->fetch_assoc()){
echo '<img src="'.$data['image_path'].'" alt="" title="" />';
}
?>
And then you can simply wrap the images in what ever container if you wish so, another way to do it could be to store the results into an' array and display it with a foreach loop
<?php
while($data = $result->fetch_assoc()){
$imageArray[] = $data['image_path'];
}
/*Code below you can place where ever you want, no need to place it directly after the
above query execute*/
foreach($imageArray as $imgPATH){
echo '<img src="'.$imgPATH.'" alt="" title="" />';
}
?>

The way i understand the problem, i would do it like this
Edit your database table so you also got "image_name", after image where you contain "ser_pic1.jpg"
SELECT * FROM {your_database} WHERE image_name = "Red car"
And post it like
link here

Related

PHP output as link from database

I have the following code that works by outputting as a link ( the link comes from a field in my database) I wish to do the same for the code below, however i cannot get it work, here is the example of what I have that works, and the code that i wish to make output as a link:
Working Code what I want it to look like
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM adrenaline WHERE title LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br> '. $row['title'] .'';
}
}
?>
And the code that i have at the moment, it works by be manually typing in the hyper link, however I wish to make it take the link from the database like the example above
//query the database
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
//ferch the results / convert results into an array
WHILE($rows = mysql_fetch_array($query)):
$title = $rows['title'];
echo "<a href='shard.php'>$title</a>";
endwhile;
?>
Many thanks!
I am not 100% certain if this is what you meant to ask... let me know in comments:
<?PHP
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
if(mysql_num_rows($query) >= 1) {
while($rows = mysql_fetch_array($query)) {
echo sprintf("%s", $rows["description"], $rows["title"]);
}
} else { echo "No hobbies found."; }
?>
I believe you might have faced some syntax issues while dealing with quotes parsing a variable in <a html tag. Consider using sprintf something like in my example.
I have also added a mysql_num_rows() just in case and you can see its a good fail-safe method incase there are no rews found on any select query.
IMPORTANT: STOP using mysql_ functions because its deprecated from new PHP versions. Use PDO or mysqli instead.

Retrieve data from a dynamically created html table

Here is my problem:
I have a dynamically created html table that I got with mysql_fetch_array
I would actually like to retrieve the first cell of a line when the user clicks on the last cell of this very same line (circle_plus_grey.png in the code).
If possible I would like to retrieve the first cell content (song_name) by using PHP, my final goal being to send an email including with the content of the first cell.
Thank you so much for your help, here is my code :
<?php
$query = $_GET['mood'];
// gets value sent over search form
$min_length = 1;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM song_main
WHERE (`song_name` LIKE '%".$query."%') OR (`song_artist` LIKE '%".$query."%') OR (`song_album` LIKE '%".$query."%')" ) or die(mysql_error());
$num = mysql_num_rows($raw_results);
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
echo '<table id="hor-minimalist-a" summary="songs table">
<thead>
<tr>
</tr>
</thead>
<tbody>';
echo'<td width="270px">'. ucfirst($results['song_name']).'</td>';
echo'<td width="200px">'. ucfirst($results['song_artist']).'</td>';
echo'<td width="270px">'. ucfirst($results['song_album']).'</td>';
echo '<td>';
echo '<a href="linkto.php"/><img src="images/circle_plus_grey.png">';
echo '<a href="#"/><img src="images/play_overlay.png">';
echo '</td>';
}
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
else{ // if there is no matching rows do following
echo "No results";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
echo'</tr>
</tbody>
</table>';
?>
You can send the first column content as a GET parameter to the other script.
echo '<a href="linkto.php?data='.ucfirst($results['song_name']).'"><img src="images/circle_plus_grey.png">';

Apply CSS Styling to PHP output

The following displays HTML results from the database field "Never". I am trying to apply CSS styling to the output.
Here's what I have...
echo "<p><strong>Never:</strong> ".$results['Never']."".$results['text']."</p><br />";
Here's what I've tried...
echo "<p><strong>Never:</strong> ".$results['<div id="nevermsg">'Never'</div>]."".$results['text']."</p><br />";
Here's my CSS...
#nevermsg { color: red; }
...but it's not applying properly. I am receiving a syntax error and a headache. Am I putting this in the wrong spot?
The $results variable is not being filled.
Edit: Code Added
Here's my connection...
<?php
mysql_connect("localhost", "jpcso_compliance", "abc*123") or die("Error connecting to database: ".mysql_error());
/*
localhost - it's location of the mysql server
root - username
third is your password
if connection fails it will stop loading the page and display an error
*/
mysql_select_db("jpcsolut_compliance") or die(mysql_error());
/* jpcsolut_webfro_HS is the name of database we've created */
?>
There is no other HTML formatting for the output, other than what is right here...
<div id="title">
<p><h1>Database Search Results</h1></p></div>
<br />
<div id="main_inner">
<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 2;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length){ // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM Compliance
WHERE (`Question` LIKE '%".$query."%') OR (`Sample Response / Must` LIKE '%".$query."%') OR (`Must` LIKE '%".$query."%') OR (`Can` LIKE '%".$query."%') OR (`Never` LIKE '%".$query."%') OR (`Tags` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields, you can also write: `id`, `title`, `text`
// IllegitimateHighSchools is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
// it will match "hello", "Hello man", "gogohello", if you want exact match use `title`='$query'
// or if you want to match just full word so "gogohello" is out use '% $query %' ...OR ... '$query %' ... OR ... '% $query'
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><strong><u><h2>Question:</u> ".$results['Question']."".$results['text']."</h2></u></strong></p><br />";
echo "<p><strong>Sample Response / Must:</strong> ".$results['Sample Response / Must']."".$results['text']."</p><br />";
//echo "<p><strong>Location:</strong> <a href='".$results['Location']."' target='_blank'>".$results['SchoolLocation']."</a>".$results['text']."</p><br />";
echo "<p><strong>Must:</strong> ".$results['Must']."".$results['text']."</p><br />";
echo "<p><strong>Can:</strong> ".$results['Can']."".$results['text']."</p><br />";
//echo "<p><strong>Never:</strong> ".$results['Never']."".$results['text']."</p><br />";
echo "<span id=\"nevermsg\"><p><strong>Never:</strong> ".$results['Never']."".$results['text']."</p></span><br />";
echo "<p><strong>_____________________________________________</strong> "."</p><br />";
echo "<p><strong>Tags:</strong> ".$results['Tags']."".$results['text']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
}
else{ // if there is no matching rows do following
echo "<br /><br /><br /><strong><h2>"."You have searched a term that is not in the database. Please contact ".htmlentities('email#domain.com') . ", if you think this term should be added."."</h2></strong>";
}
}
else{ // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
<br />
<br />
<br />
<br />
<br />
<br />
</div>
<!--End of Inner Main-->
Additionally, here is a link to the site, where I've included a query in the URL here.
Lastly, I call the stylesheet 'global.css', which is where the style lives.
#nevermsg { color: red; }
You need to change the array type in your while loop. mysql_fetch_array will return a standard array accessed like $array[0] not $array['my_key'] so use mysql_fetch_assoc.
So instead of this:
while ($results = mysql_fetch_array($raw_results)) {
echo "<p><strong>Never:</strong> <span id=\"nevermsg\">".$results['Never']."</span></p>"; //Doesn't
}
Do this:
while ($results = mysql_fetch_assoc($raw_results)) {
echo "<p><strong>Never:</strong> <span id=\"nevermsg\">".$results['Never']."</span></p>"; //Works
}
UPDATE:
Another option if you don't know the key is loop through the $results array itself like so with a foreach:
while ($results = mysql_fetch_assoc($raw_results)) {
foreach ($results as $key => $value) {
echo "<span id=\"nevermsg\"><p><strong>$key:</strong> ".$value."</p></span><br/>";
}
}
See the PHP fiddle example of the loop and <span> in action here. For obvious reasons the SQL could not be duplicated in the fiddle.
Why don't you use direct output of HTML?
// some preceding PHP code
?>
<p>
<strong>Never:</strong> <span id="nevermsg"><?=$results['Never'].$results['text'] ?></span>
</p>
It will be more readable and there will be no mess of HTML and PHP quotes, and no need to escape them...
Try this:
<?php
echo "<p><strong>Never:</strong> " . $results['<div id=\"nevermsg\">\'Never\'</div>'] . $results['text'] . "</p><br />";
?>
Your query is fine, it's your HTML which is quite messy. Try replacing this:
echo "<p><strong>Never:</strong> ".$results['Never']."".$results['text']."</p><br />";
With:
?>
<strong>Never:</strong>
<div id="nevermsg"><?= $results['Never']; ?></div>
<br>
<?php

Duplicate dynamic Link

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

Selecting one value from an array called by a query in PHP

Basically I have a query called using PHP:
<?php $result = mssql_query("SELECT * FROM Colours WHERE Type = 'type1' ");
while ($row = mssql_fetch_array($result)) {
if ($row['ColourID'] == "1") {
$sayclass1="imgactive";
}else{
$sayclass1="imginactive"; }
?>
As you can see once I execute the query I then loop it, the problem is that it returns an array, now in some instances I need to use the full array, but I would like to be able to select one entry from it for if statements and such. For example:
<img id="h" src="<?php echo $row['thumbimg']; ?>
now thumbimg is a column in my DB, and it just holds a url. However due to the fact its an array the picture doesn't display because its echoing all the values, so instead of images/image1.png for example it is echoing images/image1.png images/image2.png images/image3.png etc etc...
I hope that makes sense, and can anyone tell me how to manipulate the query/code slight to still return all the entries but to select certain values from the arrays please?
You need to use the img tag with in for each if you want to show all the images
foreach($row[thumbimg] as $img):
<img id="h" src="<?php echo $img; ?>
end foreach;
<?php $result = mssql_query("SELECT * FROM Colours WHERE Type = 'type1' ");
while ($row = mssql_fetch_array($result)) {
if ($row['ColourID'] == "1") {
$sayclass1="imgactive";
}else{
$sayclass1="imginactive";
}
echo '<img id="h" src="'.$row['thumbimg'].'">';
}
?>
Using this above code, you will get one image per line from the database. The part of code you have copy-pasted is not enough to determine where your mistake is and why $row['thumbimg'] contains a concatenated value of the result.

Categories