I am creating an SIC code lookup and I am having a weird issue with my query. I have 6 table names, description, description-2, description-3. and two-digit-sic, four-digit-sic, and six-digit-sic and I am getting unexpected results.
If I search for an item in any of the description tables (example: agriculture) it will return the correct queries. and it will display as it should. As well as if I only search for a two-digit-sic. (example: 01)
However if I try and search via six-digit-sic or four-digit-sic It will not display the records.
A weird thing is when I search for the correct six-digit-sic it will say it found records but just not display them. if you put in an incorrect sic code it will just say no records found. example of working six-digit-sic (011198) non-working SIC (112112)
I am truly at a loss as to why this is happening.
this is live here: http://mainstaycomputing.com/client/prospects/list-brokers-resources/sic-code-search/
<?php
get_header();
?>
<div id="main-content" style = 'position: relative'>
<div class = 'wrapper'>
<h1 class="entry-title main_title"><?php the_title(); ?></h1>
<div class = 'sic-text'>
<p> SIC codes are assigned by the Government and are standard at the 4 digit level.
The 8 digit codes may be customized by each individual list owner. Because we represent all list
sources, there may be variance in what the 8 digit codes represent. For greatest accuracy,
when speaking with one of our List Brokers please supply the sic code # along with a description so
we can provide as exact a match as possible.To use this search, simply type the Industry you’re
looking for into the Search By Keyword field. For instance, entering “Dentists” will cause all
businesses related to dentists listed. <! — If you know the SIC code and want to know the industry
name, enter the 8 digit code into the Search By Code field. –> </p>
</div>
<form action="" method="GET" class = 'sic-search'>
<input class = 'sic-search-text' type="text" name="search" placeholder="Search for an industry, eg 'Agriculture'"/>
<input type="submit" value="Search" class = 'sic-search-button'/>
</form>
<?php
$search = $_POST['search'];
$host = "****";
$user = "****";
$password = "****";
$database_name = "****";
$min_length = 2;
// you can set minimum length of the sic if you want
if(strlen($search) >= $min_length && $search != ''){ // if sic length is more or equal minimum length then
echo "<p id='rowCount'> </p>";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from siccodes where description LIKE ? OR description-2 LIKE ?");
$query->bindValue(2, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table class='sic-code-table'";
echo "<tr><th>description</th><th>two-digit-sic</th><th>description</th><th>four-digit-sic</th><th>description</th><th>six-digit-sic</th></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['description'];
echo "</td><td>";
echo $results['two-digit-sic'];
echo "</td><td>";
echo $results['description-2'];
echo "</td><td>";
echo $results['four-digit-sic'];
echo "</td><td>";
echo $results['description-3'];
echo "</td><td>";
echo $results['six-digit-sic'];
echo "</tr>";
}
echo "</table>";
} else {
echo "<p style = 'text-align:center; margin-bottom:30px; color: red;'>No results match" . " '" . $search . "' " . "Please try another search term.</p>";
}
} else {
if (!empty($_POST['search'])) {
echo "<p style = 'text-align:center; margin-bottom:30px; color: red;'> Please search again, '$search' is to short.</p>";
}
}
$host = "****";
$user = "***";
$password = "***!";
$database_name = "*****";
mysql_connect("****", "****", "****") or die("Error connecting to database: ".mysql_error());
/*
localhost - it's location of the mysql server, usually localhost
root - your username
third is your password
if connection fails it will stop loading the page and display an error
*/
mysql_select_db("****") or die(mysql_error());
/* tutorial_search is the name of database we've created */
?>
<?php
$query = $_GET['search'];
// gets value sent over search form
// if the query is null which it would be when they first enter the page then show all results
if(empty($_GET['search'])) {
// $query = '01';
$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 siccodes ") 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 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
echo "<table class='sic-code-table'";
echo "<tr><th>description</th><th>two-digit-sic</th><th>description</th><th>four-digit-sic</th><th>description</th><th>six-digit-sic</th></tr>";
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 "<tr><td>";
echo $results['description'];
echo "</td><td>";
echo $results['two-digit-sic'];
echo "</td><td>";
echo $results['description-2'];
echo "</td><td>";
echo $results['four-digit-sic'];
echo "</td><td>";
echo $results['description-3'];
echo "</td><td>";
echo $results['six-digit-sic'];
echo "</tr>";
// posts results gotten from database(title and text) you can also show id ($results['description'])
}
echo "</table>";
}
} // end of displaying all results
/* this is the actual search */
$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 siccodes
WHERE (`description` LIKE '%".$query."%') OR (`description-2` LIKE '%".$query."%') OR (`description-3` LIKE '%".$query."%') OR (`two-digit-sic` = '$query') OR (`four-digit-sic` = '$query') OR (`six-digit-sic` = '$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 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
$raw_num_rows = mysql_num_rows($raw_results);
$num_rows = $raw_num_rows - 1;
echo "<p id='rowCount'> We have retrieved " . " " . $num_rows . " " . " records related to the keyword '$query'</p>";
echo "<table class='sic-code-table'";
echo "<tr><th>description</th><th>two-digit-sic</th><th>description</th><th>four-digit-sic</th><th>description</th><th>six-digit-sic</th></tr>";
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 "<tr><td>";
echo $results['description'];
echo "</td><td>";
echo $results['two-digit-sic'];
echo "</td><td>";
echo $results['description-2'];
echo "</td><td>";
echo $results['four-digit-sic'];
echo "</td><td>";
echo $results['description-3'];
echo "</td><td>";
echo $results['six-digit-sic'];
echo "</tr>";
// posts results gotten from database(title and text) you can also show id ($results['description'])
}
echo "</table>";
}
else{ // if there is no matching rows do following
echo "<p style='text-align:center;color:red;'>No results for '$query' | Please try again";
}
}
else{ // if query length is less than minimum
echo "<p style='color:orange; text-align:center; '>Minimum length is ".$min_length."</p>";
}
?>
<!-- creates a form at the bottom of the list if there are more than 100 records -->
<?php if(mysql_num_rows($raw_results) > 100) : ?>
<form action="" method="GET" class = 'sic-search'>
<input class = 'sic-search-text' type="text" name="sic" placeholder="Search for an industry, eg 'Agriculture'"/>
<input type="submit" value="Search" class = 'sic-search-button'/>
</form>
<?php endif; ?>
</div> <!-- end of wrapper -->
</script>
</div> <!-- #main-content -->
<?php get_footer(); ?>
Related
I can't style an echo in PHP with css. No matter what I do, it doesn't work.
The php function is a search bar that will echo results from a mysql database.
Here's the CSS:
.php {
font-family: montserrat, sans-serif;
font-style: normal;
font-weight: 200;
text-align: justify;
color: rgba(200,200,200,1.00);
}
PHP:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<form method="GET" action="index.php" id="searchform">
<input type="text" name="query" placeholder="Enter keyword...">
<input style="width:30%;height:24px;" type="submit" name="submit" value="Search">
</form>
<?php
$hostname = "localhost";
$username = "user123";
$password = "pass123";
mysql_connect($hostname, $username, $password);
mysql_select_db("tehdatabase") or die(mysql_error());
$query = $_GET['query'];
// 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 env
WHERE (`id` LIKE '%".$query."%') OR (`name` LIKE '%".$query."%') OR (`short` LIKE '%".$query."%') OR (`short_withtag` 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 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><h3>".$results['id']."</h3>".$results['name'].$results['short'].$results['short_withtag']."</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 "No results";
}
}
else{ // if query length is less than minimum
echo "Please enter at least one character";
}
?>
<div class="php">
<?php
echo("$output");
?>
</div>
</body>
</html>
I found this on the internet, and it works perfectly, except for one thing.
The div class php that is supposed to style the output is not working. the echo is black, times new roman text. How do I get around this?
You're not echoing anything in the div.php block. $output is never defined in your code. You echo plenty of times before the div.php block.
It seems to me you want to define, or append, $output instead of echo in the various sections like:
echo "No results";
Or just put the <div class="php"> before the PHP block so the echoes will be inside of it.
I have a problem, small to others, but huge to me. I have been working on a project since March 15 of this year. I am not a web designer but this is just a hobby of mine.
My problems are:
When I call this program for data, I receive records but it only works if I search for the full postcode
(EX 1: n = no results EX 2: nn12ab = 5 results displayed )
I have to arrange the results in some order
(my results = abcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ab,
the way I am trying to get them its
first name / last name / email / postcode.
I had checked in w3schools and all other mode but still I am asking this. :(
I am fully aware its no hack protected , I just want to make it work.
any idea where I need to place whatever works ?
TXT IN ADVANCE!
HTML search
<form method="post" action="search.php">
<center>
<h1>My Search Engine</h1>
<input type="text" value="Search..." name="query" />
<input type="submit" value="Find" name="list" />
</center>
</form>
PHP SEARCH and display CODE
<?php
$servername = "localhost";
$username = "abcd";
$password = "******";
$dbname = "abcd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM wfuk";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><td><tr><th>ID</th></td></tr>
<th>Name</th></td></tr>
<th>postcode</th</td>></tr>
<th>trade</th></td></tr>
<th>telephone</th></td></tr>
<th>comments</th></td></tr></table>
";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table><tr><td>"
.$row["id"].
"</td><td>"
.$row["first_name"]
.$row["last_name"].
"</td></tr>".
"<tr><td>"
.$row["post_code"].
"</td></tr>".
"<tr><td>"
.$row["trade"].
"</td></tr>".
"<tr><td>"
.$row["telephone"].
"</td></tr>".
"<tr><td>"
.$row["comments"].
"</td></tr></table>"
;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Substitute this line:
$sql = "SELECT * FROM wfuk";
by
$sql = "SELECT * FROM wfuk where name like " . $_POST["query"] . " order by first_name, last_name, email, postcode";
I'm assuming that the columns in table wfuk have the names you said. If not, change them by the column names.
This is not the best way to do a search, because it open the possibility for SQL-injection attacks. But at your current level of knowledge you probably aren't ready for other solution.
Later please educate yourself on better prattices on this kind of operation.
Nothing to worry about, just basic confusions .
Answer of first question:
Dont use = sign in query like this :
Select * from table where postcode='.$variable.'
Use like clause this :
Select * from table where postcode like '%.$variable.%'
Answer for Second question:
Place border for your table :
<table border="1">
a few things here
Use some good tutorials, don't trust on w3school (some people call
it w3fool)
Never User Select * from table, rather specify column names
something like Select firstname, lastname from table
if you want search based on integer, user = sign e.g where rollunme=134
if you want to search some text/ character field , use LIKE operator
eg firstname LIKE %zaffar%
these are basic tips which should help you...
PS
question edited, but these tips should still apply as they are very generic in nature and should help you
yes it work unfortunately not whit this code, but from hear i lear the pice that i was missing THX ALL .
CODE I HAVE USE
<?php
//load database connection
$host = "localhost";
$user = "change my";
$password = "change my";
$database_name = "chage my database name";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from change_table_name where change_title LIKE '%$search%' OR change_author LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Title_Books</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Author</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">change_Price</td></tr>";
while ($results = $query->fetch()) {
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Chage_title'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Change_author'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
// if not needit delete "$". from bellow
echo "$".$results['change_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
<html>
<head>
<title> How To Create A Database Search With MySQL & PHP Script | Tutorial.World.Edu </title>
</head>
<body>
<form action="search-database.php" method="post">
Search: <input type="text" name="search" placeholder=" Search here ... "/>
<input type="submit" value="Submit" />
</form>
<p>PHP MySQL Database Search by Tutorial.World.Edu</p>
</body>
</html>
i found a different code i will post it for future references but you guys let me understand the thinks i could not understand
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));
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
Hello i am trying to make a trade script were users can trade each others monsters.
So i have a script were it shows there monsters and the users monsters that they type in so if the user types in nick it will shows the pokemon nick monsters and the user who typed it in monster.
All of whic works fine it displays what i want.
Now i want to store the monsters they want and are offering in the db. And that is were we come to the problem. For some resosn its storing the username and the username of the trader ok but not the monsters. Its storing
{"pokemon":[""]}
For the trade_pokeid and the trade_mypokeid
Here is how i display there monsters and the users monsters which works fine
Trade with </h4>
<?php
$username_trade = $_POST['username_trade'];
$_SESSION['username_trade'] = $username_trade ;
echo "You put in id ". $username_trade . ".<br />";
?>
</p>
<p> </p>
<p><span class="mid_box">
<?php
// get and display userbox
$q = "SELECT id,pokemon,exp,level FROM user_pokemon WHERE belongsto='". $_SESSION['username_trade']."'";
$r = mysql_query($q);
if (mysql_num_rows($r) <= 0) {
echo "You have no current pokemon stored";
}
?>
</span></p>
<p> </p>
<p>
<?php
echo "<form action='test_process.php' method='POST'>";
while ( $v = mysql_fetch_object( $r ) )
{
echo "<label><input type='checkbox' name='pokemon[]' value='$v->dbid'/> They have a $v->pokemon </label><br/>";
echo "<label> Level $v->level </label><br/>";
}
echo "<input type='hidden' name='user' value='$username_trade'/>";
echo "<input type='submit' value='Check!!'/>";
?>
</p>
<p><strong>Pick what you want two offer for the pokemon </strong></p>
<p>
<?php
// get and display userbox
$q = "SELECT id,pokemon,exp,level FROM user_pokemon WHERE belongsto='". $_SESSION['username']."'";
$t = mysql_query($q);
if (mysql_num_rows($t) <= 0) {
echo "You have no current pokemon stored";
}
?>
</p>
<p>
<?php
echo "<form action='test_process.php' method='POST'>";
while ( $v = mysql_fetch_object( $t ) )
{
echo "<label><input type='checkbox' name='pokemonin[]' value='$v->dbid'/> I have a $v->pokemon</label><br/>";
echo "<label> Level $v->level </label><br/>";
}
echo "<input type='hidden' name='userin' value='$username'/>";
echo "</form>";
?>
<p align="center">
Now here is how i try and store them.
<?php
include 'config.php';
$pokemon = $_POST['pokemon'];
$pokemonin = $_POST['pokemonin'];
$meid = $_SESSION['username'];
$toid = $_POST['user'];
$dbid = array();
$dbid2 = array();
foreach ( $pokemon as $poke )
{ $dbid['pokemon'][] = $poke;
}
foreach ( $pokemonin as $poke2 )
{ $dbid2['pokemonin'][] = $poke2;
}
srand ((double) microtime( )*1000000);
$random_number = rand( );
echo "$random_number";
mysql_query("INSERT INTO trade (trade_id, trade_to, trade_from, trade_pokeid, trade_mypokeid)
VALUES ('$random_number','$toid', '$meid', '"$dbid."', '".$dbid2."');") or die("Error: ". mysql_error());
?>
What am i doing wrong ? why are the results not being stored ? or carried over the db connect and session start are in the config.php page
In your last MySQL query, you're trying to insert a PHP array as a string into a query, that won't work. If I'm guessing correctly, you'll want to use something like implode(",",$dbid['pokemon']) instead of $dbid.
Also, it's definitely a good idea to run mysql_real_escape_string on anything that comes from the user and/or the URL before you put it in a query!
Your code is open for sql injection !
You shuld aviod passing parameters (without escaping) to sql query => for start check:
http://php.net/manual/en/function.mysql-real-escape-string.php
You have an error (not enough - or too many dots) in your MYSQL statement...
VALUES ('$random_number','$toid', '$meid', '"$dbid."', '".$dbid2."')
Should read
VALUES ('$random_number','$toid', '$meid', '$dbid', '$dbid2')