While-loop inside else-statement not printing all answers - php

I got this code, which is linked to a search field on my index page:
<?php
ini_set('display_errors', 2);
$search = $_GET ['q'];
$conn = mysqli_connect("localhost", "root", "","release");
$query = mysqli_query($conn,"SELECT * FROM game WHERE game_name LIKE '%". $search ."%'");
$foundnum = mysqli_fetch_assoc($query);
$count = count($foundnum['game_name']);
if ($foundnum == 0) {
echo "No results found. Either this game doesn't exist, or we have yet to add it. Please contact us!";
}
else {
while($foundnum= mysqli_fetch_assoc($query))
{
echo "$count result(s) found!<p>";
echo"<pre/>";print_r($foundnum['game_name']);
echo"<pre/>";print_r($foundnum['game_release']);
}
}
?>
Everything's working fine without the while-loop, but because some search terms ('car' for example), should print both Project CARS and Rise of Incarnates, I need a while-loop.
I tried putting the while-loop before the if-statement as well, but that doesnt work either. What am I doing wrong?

I have made some correction in your code.. please re-veirfy using below code
I have tried the code using my db tables and it is showing correct values...
<?php
ini_set('display_errors', 1);
$search = $_GET['q'];
$conn = mysqli_connect("localhost", "root", "", "release");
$query = mysqli_query($conn, "SELECT * FROM game WHERE game_name LIKE '%" . $search . "%'");
$count = mysqli_num_rows($query); // right way to find row count
if ($count == 0)
{
echo "No results found. Either this game doesn't exist, or we have yet to add it. Please contact us!";
}
else
{
while ($foundnum = mysqli_fetch_assoc($query))
{
echo "$count result(s) found!<p>";
echo"<pre>";
print_r($foundnum['game_name']);
echo"</pre><pre>";
print_r($foundnum['game_code']);
echo"</pre>";
}
}
?>
if you want to search insensitively (i.e ignoring capital and small letters) than do let me know.. I will update the code

Related

Select data from MySQL DB based on the URL example (www.example.co.uk/essex.php)

I am very new to php and I am looking to create dynamic pages.
Basically If a person lands on www.example.co.uk/essex.php I would like to be able to add something like <h1>Company In <?php echo $row['County']; ?> so that it would show
Company In Essex when Live and save time if I need to duplicate the page for another county or town.
So far I have setup a database in phpmyadmin
Picture of Table
My code so far to grab the table is;
$dbconnect = mysqli_connect("HOST", "USER", "PASSWORD", "DB");
if(mysqli_connect_errno()) {
echo "Connection Failed:".mysqli_connect_error();
exit;
}
$count_sql="SELECT * FROM areas";
$count_query=mysqli_query($dbconnect, $count_sql);
$count_rs=mysqli_fetch_assoc($count_query);
and then on www.example.co.uk/essex.php
<?php
do {
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))
?>
But where I have gone wrong is it pulls all the data from the table for County where I only wish it to pull the county of Essex.
Please forgive me for explaining this badly.
UPDATE -
$row = url2content();
extract($row);
function url2content($url = NULL){
if(is_null($url)){
if(isset($_SERVER["REQUEST_URI"]) && $_SERVER["REQUEST_URI"]){
$url = $_SERVER["REQUEST_URI"];
}elseif(isset($_SERVER["PATH_INFO"]) && $_SERVER["PATH_INFO"]){
$url = $_SERVER["PATH_INFO"];
}
if (substr($url,0,1) == '/'){
$url = substr($url,1);
}
}
if (DEBUG_MODE){
echo ('URL requested: "'.$url.'"<br>');
}
function get_towns($county){
$query = sprintf("select townName from " . AREAS_TABLE . " where countyName = '%s' order by rand() LIMIT 0,24" ,mysql_real_escape_string($county));
$res = mysql_query($query);
if(!$res){
printf("Unable to query ".AREAS_TABLE." table: %s \n", mysql_error());
}
$html="";
while($row = mysql_fetch_assoc($res)){
$html.="<li>".stripslashes($row["townName"])."</li>\n";
}
return $html;
}}
You have to use WHERE clause in your query in order to select a specific country from your db
SELECT * from table WHERE felid_country=$count_rs['County'];
You can use strpos() to match the County (eg.essex) with url $_SERVER['REQUEST_URI'] (eg.www.example.co.uk/essex.php) in your case.
Just like this
<?php
do {
if(strpos($_SERVER['REQUEST_URI'],$count_rs['County'])!=false)
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))

How can I SELECT field FROM table WHERE id=variable?

I have a variable of the logged in user ($steamid) that I need to use to select and echo specific fields from the database. I am using the following code, but it is working incorrectly. All database info is correct, the tables, columns, and variables are not misspelled. Not sure what I'm doing wrong.
<?php
$con=mysqli_connect("private","private","private","private");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `bananas` FROM `es_player` WHERE `steamid` = '$steamID'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("bananas: %n",$fieldinfo->bananas);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
No errors are shown, it simply returns "bananas:" with nothing after it. I feel like I didn't to it correctly, does anyone know what I might've done wrong? Here is a screenshot of my database table so you know what it looks like http://puu.sh/gCY3d/983b738458.png.
Try this:
$query = Mysqli_Query($con, "SELECT * FROM `es_player` WHERE `steamid`='$steamID'") or die(mysql_error());
if( ! mysqli_num_rows($query) )
{
echo 'No results found.';
}
else
{
$bananas_array = mysqli_fetch_assoc($query);
$bananas = $bananas_array['bananas'];
echo 'Number of bananas: '. $bananas;
}
If this doesn't work, there is a problem with STEAM_ID format. You could try triming the IDs to be JUST a number, and add the STEAM_x:x: to it later.

sql search using like not working

i have an search box on website but whenever we search, it doesn't give any output.
I want to search for page title from database. But don't know what is wrong.
<div id="siteSearch">
<h3>Site Search</h3>
<?php
if (isset($_POST['search'])) {
$search = $_POST['search'];
$query = "SELECT * FROM pages WHERE ptitle LIKE '%$search%'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if ($count > 0) {
while ($fetch = mysql_fetch_array($result)) {
echo $fetch['ptitle'];
}
}
} else {
echo "No result found!";
}
?>
</div>
You are using the semicolon after the while loop:
while($fetch = mysql_fetch_array($result));
Please remove the semicolon in this line.
You have a misplaced closing bracket. The one above else should be 5 lines below. As it currently stands, the else clause relates to if (isset($_POST['search'])).

Why isn't this query returning an object?

I am learning PHP and MySQL from 'PHP and MySQL web dev'. Currently I am finding difficulties in displaying results from database. Here is the code:
<body>
<?php
$searchtype = $_POST['searchtype'];
$seachterm = trim($_POST['searchterm']);
if(!$searchtype || !$seachterm){
echo "You did not enter all the details. Bye";
exit;
}
if(!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$seachterm = addslashes($seachterm);
}
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
if(mysqli_connect_errno()){
echo "Sorry Could not connect to db";
exit;
}
$query = "select * from books where".$searchtype."like '%".$seachterm."%'";
$result = $db -> query($query);
$num_of_results = $result->num_rows; // Line 47
echo "Num of books found is ".$num_of_results." ";
for($i = 0; $i < $num_of_results; $i++){
$row = $result -> fetch_assoc();
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
$result->free();
$db -> close();
?>
</body>
When I run the above code, this is the error i get.
Notice: Trying to get property of non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 47
Num of books found is
Fatal error: Call to a member function free() on a non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 64
What am I doing wrong?
There's probably an error in your SQL query and $result is false instead of the result object.
I think it's probably because you're missing some spaces in the query. This line:
$query = "select * from books where".$searchtype."like '%".$seachterm."%'";
should be something like:
$query = "SELECT * FROM books WHERE '" .$searchtype. "' LIKE '%".$seachterm."%'";
It would help if we knew the values of:
$_POST['searchtype'];
$_POST['searchterm'];
You're not checking to make sure that $result is what you think it is. It's very likely that something went wrong with your query, and the return value of $db->query() is false. It's a good idea to check for that to make sure your query actually worked.
Try using this code:
$result = $db->query($query);
if ($result === false) {
// Query failed - we can't continue
die('My query failed, I want to be a teapot instead.');
}
// Now it's safe to operate on $result, deal with a successful query, but no results
if ($result->num_rows == 0) {
echo 'no results found.';
// display any other output, search again?
exit;
}
// At this point you have results to display
Now, as to why your query is failing, take a look at this part closely:
"select * from books where".$searchtype."like '%"
You need some spaces. If $searchtype was 'foo', your query would actually expand to:
select * from books wherefoolike
Try instead:
"select * from books where ".$searchtype." like '%"
Notice the space after 'where' and before 'like'? That should probably fix it.
I'm not going to harp too much about making sure your query is properly prepared for safety, your book should go into that - but do keep it in mind.

Searching MySQL with PHP

I am doing a project where I want a person to enter the name of any artist/band into a text box where it will seach my mysql database for the event information and display the results/content on another page. The code below is within my index.php where it should get the information from search.php (below also). I've looked all over and I'm not sure why it's not working and I can't figure out what to do. Help would be great! (I really need to pass this class!) :)
(index.php)
<form name="search" action="search.php" method="get">
<div align="center"><input type="text" name="q" />
<p><input type="submit" name="Submit" value="Search" /></p>
</form>
(search.php)
<?php
//Get the search variable from URL
$var=#&_GET['q'];
$trimmed=trim($var); //trim whitespace from the stored variable
//rows to return
$limit=10;
//check for an empty string and display a message.
if($trimmed=="")
{
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var))
{
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "select * from events where artist_name like \"%trimmed%\" order by date";
$numresults=mysql_query($query);
$numrows=mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0)
{
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank\" title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row=mysql_fetch_array($result)) {
$title = $row["artist_name"];
echo"$count.) $title";
$count++;
}
$currPage = (($s/$limit) + 1;
echo"<br />";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
print" <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a> ";
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news = $s+$limit;
echo " Next 10 >>";
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
Your where clause is goofy...try changing it to:
WHERE artist_name like '%$trimmed%'
just putting trimmed will be interpreted literally as the string "trimmed". However, using the variable $trimmed in your double-quoted string will give the actual variable's value.
$query = "select * from events where artist_name like '%$trimmed%' order by date";
In order to use the variable $trimmed in a query, escape it first. Otherwise, your script will be vulnerable to SQL injection attacks, and attackers will be able to run almost any query against your database. This problem is exacerbated by the fact that you are connecting to MySQL as root. Never ever do this in a production environment.
Also, to expand a variable in a string, you should include the $ character before the variable name.
$trimmed = trim($var);
$escaped = mysql_real_escape_string($trimmed);
$query = "select * from events where artist_name like \"%$escaped%\" order by date";
Your code still looks all over the place. I think the main reason it wasn't working was the mixing of " and '. You need to escape variables before you use them in your queue. mysql_real_escape_string is the lowest form of escaping you should be using. I'd recommend you have a look at PDO though.
<?php
//Get the search variable from URL
$var = $_GET['q'];
$trimmed = mysql_real_escape_string(trim($var)); //trim whitespace and escape the stored variable
//rows to return
$limit = 10;
//check for an empty string and display a message.
if($trimmed == "") {
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var)){
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "SELECT * FROM events WHERE artist_name LIKE %$trimmed% ORDER BY DATE";
$numresults = mysql_query($query);
$numrows = mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0){
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank"\ title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row = mysql_fetch_array($result)) {
$title = $row['artist_name'];
echo $count.' '.$title;
$count++;
}
$currPage = (($s/$limit) + 1;
echo "<br>";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
echo ' <a href="'.$PHP_SELF.'?s='.$prevs.'&q='.$var.'"><&lt';
echo 'Prev 10</a> ';
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news=$s+$limit;
echo ' Next 10 >>';
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo '<p>Showing results '.$b.' to '.$a.' of '.$numrows.'</p>';
?>
You are missing a $ symbol. I think
$var=#&_GET['q'];
should probably be
$var=#$_GET['q'];
unless you really want a reference, in which case it should be this: (the error suppression is not needed at this point if you want a reference, but you should check $var is set before trying to access it)
$var=& $_GET['q'];
I would be tempted to write it a bit more like this.
if (!isset($_GET['q'])) {
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
$trimmed = trim($_GET['q']);
if($trimmed=="") {
echo"<p>Please enter a name.</p>";
exit;
}
Also as Chad mentioned, an sql injection would be simple since you arent cleaning input before performing DB actions with it.
try adding
foreach($_REQUEST as $param => $value)
{
$_REQUEST[$param]=mysql_real_escape_string($value);
}
This way you escape all the user input so the user cant tamper with the db. Read more about this method and sql injection in the docs here:
http://us2.php.net/mysql_real_escape_string

Categories