MYSQL formulating a search query - php

I'm having slight difficulties (syntax presumably) formulating a query for a search I'm writing in php.
So far I have this:
$query = ("SELECT * FROM $table WHERE $field LIKE "$trimmed);
trimmed is defined as
$trimmed = trim($var);
What I'm trying to accomplish is, use that query to search for a certain row in my mysql database. I've confirmed that it does indeed connect to the dbase and it does grab data from the table. I'm 99% new to php and mysql, I've just started working on this. Any help would be greatly appreciated.
EDIT: Oh I use the query here:
$result = mysql_query($query); I'm sure the issue isn't here, but in $query

Change
$query = ("SELECT * FROM $table WHERE $field LIKE "$trimmed);
to
$query = "SELECT * FROM $table WHERE $field LIKE '$trimmed'";
It's always a good idea to escape any special characters, such as backslash, in the input. With mysql, you can use mysql_escape_string:
$trimmed = mysql_escape_string($trimmed);
$query = "SELECT * FROM $table WHERE $field LIKE '$trimmed'";
Equivalent commands exist in mysqli, PDO, and all PHP frameworks.

Check out the PHP manul, example:
$query= mysql_query("SELECT data FROM mydb;");
$myarray= array();
while ($row= mysql_fetch_array($query)) {
$myarray[] = $row['data'];
}
EDIT
This is your code? if so, you have a syntax error:
$query = ("SELECT * FROM $table WHERE $field LIKE "$trimmed);
should be:
$query = ("SELECT * FROM $table WHERE $field LIKE '$trimmed'");

Related

Laravel raw expression is not working when including wildcard parameter

Given the following code:
$sql = "SELECT * FROM items WHERE name LIKE '%?%'";
$key = 'orange';
$result = \DB::select(\DB::raw($sql), [$key]);
the result is always no records!
while by changing LIKE to =, it works fine:
$sql = "SELECT * FROM items WHERE name = ?";
I don't know why this is happening but I have to use RAW in this script. Can anybody figure out where is the problem?
You're failing to understand how bindings work... binding not only handles quotes and other special characters within the value, but also handles the quoting
$sql = "SELECT * FROM items WHERE name LIKE ?";
$key = '%orange%';
$result = \DB::select(\DB::raw($sql), [$key]);
and note the % around the $key value before you bind it

Search multiple User-inputted Text fields in database

Here's The code we have tried so far.
What actually we have to do is user will input data in his selected textboxes. we want php query to combine the search result and provide output.
$query=array();
$query[] = empty($_POST['keyword_s_dec']) ? : 'cand_desc='.$_POST['keyword_s_dec'];
$query[] = empty($_POST['keyword_s_location']) ? : 'cand_location='.$_POST['keyword_s_location'];
$results = implode('AND', $query);
$sql = "SELECT * FROM candidate where '".$results."'";
$result = mysql_query($sql) or die(mysql_error());
Where keyword_s_dec & keyword_s_location are our texfield ID;
cand_desc & cand_location are database columns.
Also we are trying for SQL Injection how can we achieve this?
I did some adjustments to your code:
$query = array();
if (!empty($_POST['keyword_s_dec'])) $query[] = "cand_desc = '".$_POST['keyword_s_dec']."'";
if (!empty($_POST['keyword_s_location'])) $query[] = "cand_location = '".$_POST['keyword_s_location']."'";
$condition = implode(' AND ', $query);
$sql = "SELECT * FROM candidate WHERE $condition";
$result = mysql_query($sql) or die(mysql_error());
This builds a valid query:
SELECT * FROM candidate WHERE cand_desc = 'test1' AND cand_location = 'test2'
Your main issue was that you weren't inserting spaces around the AND string and single quotes for the values in the WHERE clause, but I also removed the conditional ?: operator since it made the code less readable.
Note that I only fixed the code that you wrote. It won't work if none of the POST variables are set (since then the SQL string will have a WHERE clause without any content) and you should definitely use mysql_real_escape_string() when reading the POST variables to prevent SQL injection.

Selecting row where field = value error

Can you explain me why my code isnt working? Ive been thinking about it for a while and I cant find it. obviously I want to print some columns from rows where column F1 is equal to user's username.
$db = JFactory::getDBO();
$user = JFactory::getUser();
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$user->username;
$db->setQuery($query);
$result = $db->query();
while($row = mysqli_fetch_object($result))
{
print $row->F1;
}
It works when I remove condition from select command and I cant figure out how to make it work with it
$query = "SELECT * FROM qwozh_visforms_1";
Now Im getting this error:
UNKNOWN COLUMN 'ADMIN' IN 'WHERE CLAUSE' SQL=SELECT * FROM
QWOZH_VISFORMS_1 WHERE F1 = ADMIN RETURN TO PREVIOUS PAGE
Thanks
All it takes if a quick read of the Joomla documentation. The following is the same as your query but making full use of Joomla's up to date database class:
$db = JFactory::getDbo();
$user = JFactory::getUser();
$query = $db->getQuery(true);
$query->select(array('*'))
->from($db->quoteName('#__visforms_1'))
->where($db->quoteName('F1') . ' = '. $db->quote($user->username));
$db->setQuery($query);
$results = $db->loadObjectList();
// Display the results
foreach($results as $result){
// echo what you want here
}
Note, I've used the prefix #__ rather than manually defining qwozh, assuming your table belong to a Joomla extension.
I know PHP and MySQL, but not Joomla. But the problem is that your username needs to be quoted because it is probably a string.
Try this:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '{$user->username}'";
or
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = ".$db->quote($user->username);
You need to wrap the name in quotes:
$query = "SELECT * FROM qwozh_visforms_1 WHERE F1 = '".$user->username . "'";
As pointed out in the comments my answer has a pretty bad quality, you may want to look at prepared statements, expecially using bindParam, which takes care of quotes for you and protects you agains SQL injection attacks.
Unfortunately I cannot suggest you Joomla based approach since I never used it, somebody else can suggest you a more appropriate solution.

How WHERE clause works when inserting php variables

I am having problems trying to get these queries with a WHERE clause to work. I have two tables which look like this :
What I am trying to do is return the genre that each film has. At the moment no data is returning at all from what I can see. Here are the two queries:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
$row_get_genre = mysql_fetch_assoc($get_genre);
$totalRows_get_genre = mysql_num_rows($get_genre);
$genre_id = $row_get_genre['id_genre'];
mysql_select_db($database_fot , $fot);
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
$totalRows_genre = mysql_num_rows($genre);
PHP with content area. I fairly new to PHP so any help would be appreciated.
<?php do { echo $genre['genre']; } while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Update: I am now able to get first genre but not second it just echos the first one twice and I have tried but still no luck:
do {do { echo $row_genre['genre']; } while($row_genre = mysql_fetch_assoc($genre));} while($row_get_genre = mysql_fetch_assoc($get_genre)); ?>
Avoiding the fact that you're using a deprecated way to establish connection and interact with MySQL, what you're doing is getting a single relation genre-film and then getting the row of the genre that matches. You should surround part of your code with a while that executes while it's still genres of the film with id. Something like:
$film_id = $row_movie_list['film_id'];
mysql_select_db($database_fot , $fot);
$query_get_genre = "SELECT * FROM film_genre WHERE `id_film` ='". $film_id. "'";
$get_genre = mysql_query($query_get_genre, $fot) or die(mysql_error());
while($row_get_genre = mysql_fetch_assoc($get_genre)){
$genre_id = $row_get_genre['id_genre'];
$query_genre = "SELECT * FROM genre WHERE `id_genre` ='". $genre_id. "'";
$genre= mysql_query($query_genre, $fot) or die(mysql_error());
$row__genre = mysql_fetch_assoc($genre);
// You should do whatever you want to do with $row__genre here. Otherwise it will be cleared.
}
I must insist this is a deprecated and insecure way of communication with a MySQL Database. I recommend you read about MySQLi or PDO extensions.
MySQLi: http://www.php.net/manual/en/book.mysqli.php
PDO: http://www.php.net/manual/en/book.pdo.php

mysql query fails if name has more then 1 words

I began to create a website for my small real estate business.
I played a bit with functions http://www.php.net mysql and I managed to make a page accessed via AJAX and returning html content for the search engine.
I have a database already populated with apartments and houses
The problem is that if the apartment name is "apartment" I return html content if "apartment with 3 rooms" it no longer write anything.
I do not understand where I was wrong:
<?php
$search = $_GET['selected'];
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('houses', $link);
function searchHouse($search, $link){
$query = "select * from houses where name=$search limit 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query2 = "select * from houses_info where house_id=$row[id]";
$result2 = mysql_query($query2);
$row = mysql_fetch_assoc($result2);
return $row;
}
$result = searchHouse($search, $link);
echo $result['house_sq'];
echo "<br>";
echo $result['house_rooms'];
echo "<br>";
echo $result['house_bathrooms'];
echo "<br>";
echo $result['house_address'];
?>
you should know if you "played" with php.net that mysql_* functions are deprecated and are no longer maintained. It's a red box on top of the page informing you that.
you have a big MySQL injection hole there, you are not escaping $string at all
your problem is that you are not adding quotes to $string like: '$string'
you should stat using PDO to get rid of the bad code and SQL Injections holes.
you can wrap those 2 selects into a single select:
<?php
function searchHouse($search, $link){
$search = mysql_real_escape_string($search);
$query = "select * from houses_info where house_id IN (select * from houses where name='".$search."' limit 1)";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
return $row;
}
?>
since you are already building that website you can start moving to PDO, read this tutorial, your code will be more like this:
<?php
$db = new PDO('mysql:host=localhost;dbname=houses;charset=UTF-8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$search = $_GET['selected'];
function searchHouse($search){
global $db;
$query = $db->prepare("select * from houses_info where house_id IN (select * from houses where name=:search limit 1)");
$query->execute(array(':search' => $search));
$row = $query->fetch(PDO::FETCH_ASSOC);
return $row;
}
$result = searchHouse($search);
?>
try:
$query = "select * from houses where name='".mysql_real_escape_string($search)."' limit 1";
and remember to always sanitize user input before passing it to sql to avoid sql injections.
Your first query should be:
$query = "select * from houses where name like $search% limit 1";
Strings need to be quoted in queries. Also, this is vulnerable to MySQL injection, make sure to escape $search with mysql_real_escape_string. Or even better yet use MySQLi or PDO instead of the old mysql_ functions.
$query = "select * from houses where name=$search limit 1";
Should be:
$query = "select * from houses where name='$search' limit 1";
Although you REALLY need to escape $search because it came from a user, even if they aren't malicious, any search queries with a single quote in it will break;
$search = $_GET['selected'];
Should be:
$search = mysql_real_escape_string($_GET['selected']);
(Anybody have the copy paste handy with the links to tutorials for MySQLi/PDO and such?)

Categories