I'm making a search site where the user can either search by Business Name or the table rows cat1, cat2,cat3. The "cat" rows are in the same table as the business name. I have it set up so I return business info if I search for the correct business. But I need to have it show businesses that have the category name you searched for.
**Basically what I'm asking is for a get search (php) to either search for the name of businesses or one of three categories.
Any Help, would be greatly appreciated... Here is my code In case you need it(Though I think this should be a pretty easy task, maybe not though, I'm a PHP Beginner)
include('config.php');
$var = $_REQUEST['search'];
$trimmed = trim($var);
$search = ucfirst($var);
$result = mysql_query("SELECT * FROM gj WHERE name like '%$search%' ORDER by name") or trigger_error(mysql_error());
$num_rows = mysql_num_rows($result);
And then I am using a while loop to get all the code from it.
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$name=$row['name'];
$phone=$row['phone'];
$website=$row['website'];
$city=$row['city'];
$address=$row['address1'];
$zipcode=$row['zipcode'];
$addressmap = preg_replace('/\s/', '+',$address);
$citymap = preg_replace('/\s/', '+',$city);
echo"
include('config.php');
$searchfields = array('name', 'cat1', 'cat2', 'cat3', )
$cleandata = mysql_real_escape_string(trim(strtolower($_REQUEST['search'])));
$where = array();
foreach($searchfields as $field) {
$where[] = 'lcase('.$field.') like \'%.$cleandata.%\'';
}
$result = mysql_query('SELECT * FROM gj WHERE '.implode(' OR ', $where).' ORDER by name') or trigger_error(mysql_error());
$num_rows = mysql_num_rows($result);
I've added a variable cleandata which contains the cleaned request data (to prevent SQL injection).
I've created a variable searchfields which can be easily expanded to search on more fields.
To search on more fields simply expand the array data:
$searchfields = array('name', 'cat1', 'cat2', 'cat3', 'cat4', )
EDIT
Added case insensitive
EDIT Added PDO
Note that since I have written this answer the community has begun the deprecation process of the ancient mysql_*. See the red box? Instead you should learn about prepared statements and use either PDO or MySQLi. If you can't decide, this article will help to choose. If you care to learn, here is a good PDO tutorial.
A rewrite of the above answer using PDO would look like something like the following:
$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$searchfields = array('name', 'cat1', 'cat2', 'cat3', )
$where = array();
foreach($searchfields as $field) {
$where[] = 'lcase(' . $field . ') LIKE :keyword';
}
$stmt = $dbConnection->prepare('SELECT * FROM gj WHERE ' . implode(' OR ', $where) . ORDER BY name);
$stmt->execute(array(
':keyword' => '%' . trim(strtolower($_REQUEST['search'])) . '%',
));
Lets say, you want to search for bussines name 'Jake' and category 'php'.
URL for your request will be like this...
http://yourdomain.com/search.php?name=Jake&category=php
You need to have some column, thats is unique identifier of table row. In this example I use 'id' column. Edit it to your needs. Now lets set up your query...
$query = "SELECT * FROM `gj`
WHERE name LIKE '%{$_GET['name']}%'
AND `gj.id` IN (
SELECT id FROM test
WHERE
cat1 LIKE '%{$_GET['category']}%' OR
cat2 LIKE '%{$_GET['category']}%' OR
cat3 LIKE '%{$_GET['category']}%'
)";
// or edit this cat1 LIKE '%{$_GET['category']}%'
// to cat1 = '{$_GET['category']}'
// if you want to compare exact values
With this query you retrieve data from DB
$result = mysql_query($query) or trigger_error(mysql_error());
Now do whatever you want with retrieved data.
Let me know the result ;-)
Related
Noobie here, apologies if the question is silly.....
I have an array of 8 images used in a session. These images are fetched randomly from the directory using the following code.
gameply.php:
<?php
session_start();
$dire="Annotated Dataset/images/";
$images = glob($dire. '*.{jpg,jpeg}', GLOB_BRACE);
shuffle($images);
$images=array_slice($images,0,8);
$_SESSION['images']=$images;
?>
I have the names of all the images from the directory stored in the database table "images". Now i want to display these 8 images from the session as a Gallery with help of mysql, by referring the name of the images from the table. I tried using the following code:
<?php
session_start();
$galleryimg= $_SESSION['images'];
$conn = mysqli_connect('localhost', 'root', '', 'registration');
for($galleryimg as $key) {
$sql = "SELECT * FROM images
WHERE image_name = '$key'
ORDER BY image_id DESC";
$result = $conn->query($sql);
}
while($row = $result->fetch_assoc()) {
$results_array['data'][$counter] = array ("image" => $row['image_name'],
"scenario" => $row['scenario'], "verified" => $row['verified']);
$counter++;
}
I think there is some mistake with the query. Can some one tell me how to access the image_name of the array of session images using Sql query.
the table has:
the $result = $conn->query($sql); has nothing to do with your code.
I see mixed usage of mysqli and PDO. It will never work. By the way, query looks good.
My advise is to read proper PDO syntax and start using PDO not mysqli.
Second advise is not to run queries in a loop unless people are dying.
Disclaimer: this answer assumes that there's a successful connection to the database.
The problem is here:
for($galleryimg as $key) {
$sql = "SELECT * FROM images
WHERE image_name = '$key'
ORDER BY image_id DESC";
$result = $conn->query($sql);
}
Your $result will have a new value everytime you iterate $gallleryimg, because you're overwritting the variable.
Please, use prepared statements to run the same query n times.
It is a lot more efficient (for repeated queries) and you can fetch right after you do the query.
However, it is harder to learn and get the ball going, but it is very useful.
Also, this line (with better indentation):
while($row = $result->fetch_assoc()) {
$results_array['data'][$counter] = array(
"image" => $row['image_name'],
"scenario" => $row['scenario'],
"verified" => $row['verified']
);
$counter++;
}
You don't need the $counter for anything.
Just do $results_array['data'][] = array( ... );
You can eliminate the loop and multiple SQL queries by using the IN clause in your where. Since the $galleryimg is
already an array, using implode to get a list of if image names for the IN clause is easy ising the implode function.
Also, if you are using a limited set of column values, don't use *, but list only the column names you need.
You can also eliminate the counter, using [] instead.
<?php
session_start();
$galleryimg= $_SESSION['images'];
$conn = mysqli_connect('localhost', 'root', '', 'registration');
$sql = "SELECT
`image_name`,
`scenario`,
`verified`
FROM `images`
WHERE `image_name` in '".implode("','",$galleryimg)."')
ORDER BY `image_id` DESC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$results_array['data'][] =
array("image" => $row['image_name'],
"scenario" => $row['scenario'],
"verified" => $row['verified']);
}
Hope that helps.
Here is you code with some optimizations.
session_start();
$galleryImgs = $_SESSION['images'];
if(!$conn = new PDO('mysql:host=localhost;dbname=registration', 'root', $pass))
{
die("Error connecting to database.");
}
$imagesIN = "'".join("', '", array_map(function($v) { return str_replace("'", "''", $v); }, $galleryImgs))."'";
$sql = "SELECT * FROM images
WHERE image_name IN ($imagesIN)
ORDER BY image_id DESC";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
$results_array = array('data' => array());
foreach ($result as $row) {
$results_array['data'][] = array
(
"image" => $row['image_name'],
"scenario" => $row['scenario'],
"verified" => $row['verified']
);
}
check for connection error
the $counter variable isn't needed because with [] you can create a new entry for the array that automatically get the next index
with join you can perform a single query to get all images data
with array_map I sanitize the array for eventual ' char that may cause SQL injection / errors
some indentation
variable name change for galleryimg in galleryImgs: with camelcase name you can improve readability
I'm working on a website that presents leaderboard data from a MySQL database as a table, that which can be filtered and searched through by the user. I was able to construct the table through PHP calls, such as
php echo $row['ranking'];
Similarly, I was able to create a pagination that limits the MySQL query to 50 rows per page.
What I haven't been able to achieve, is the filtering/searching of the data, as well as a pagination that doesn't require the reloading of the page. I attempted to create filtering through PHP variables
$sql = "SELECT * FROM New_2v2_Data $filters";
but couldn't get it to work outside of just editing the PHP code.
$racevar = '%';
$classvar = '%';
$specvar = '%';
$playervar = '%';
$realmvar = '%';
$factionvar = '%';
$r1 = '0';
$r2 = '1800';
$race ="raceId LIKE '$racevar'";
$class = "classId LIKE '$classvar'";
$spec ="specId LIKE '$specvar'";
$player ="player LIKE '$playervar'";
$realm ="realmName LIKE '$realmvar'";
$faction="factionId LIKE '$factionvar'";
$rating ="rating between $r1 and $r2";
$filters = "WHERE $race AND $class AND $spec AND $player AND $realm AND $faction AND $rating";
$sql = "SELECT * FROM New_2v2_Data $filters";
$rs_result = mysql_query ($sql); //run the query
I've found filtering solutions for individual variables, for example names, but I haven't been able to find anything that takes in multiple variables into account. Even then, the filtering only worked on tables that were static.
I was thinking maybe if a dropdown/checkbox were to change a PHP variable depending on what is chosen, and then reloading the PHP for the table to include the additional "WHERE" statement, filtering could work.
Some advice on how I would go about doing this would be great, thank you.
You can conditionally include the various limits and build the SQL just from those which have something set.
$racevar = 'a'; // A value to show when this would be included
$classvar = '%';
$specvar = '%';
$playervar = '%';
$realmvar = '%';
$factionvar = '%';
$r1 = '0';
$r2 = '1800';
$condition= [];
$bindData = [];
if ( $racevar != '%'){
$condition[] ="raceId LIKE ?";
$bindData[] = $racevar;
}
if ( $classvar != '%'){
$condition[] = "classId LIKE ?";
$bindData[] = $classvar;
}
// Repeat above for all of the conditions
if ( $r1 != 0 or $r2 != 0 ) {
$condition[] = "rating between ? and ?";
$bindData[] = $r1;
$bindData[] = $r2;
}
$sql = "SELECT * FROM New_2v2_Data";
if ( count($condition) > 0 ) {
$sql .= " WHERE ".implode(' and ', $condition);
}
echo $sql;
The idea is to build a list of conditions, only when the values have something which is a limit. This can then be added as a where clause.
You then can have various input fields/select fields which allow the user to select the criteria and call this routine with the selections.
I've updated the answer to use bind variables, so that using prepare will give you more security and then you can either bind the values or (using PDO) execute with the array of bind values.
You need to make the filters selectable or dynamic in a way that you can pass them on to your SQL statement.
Your solution for the dropdown could be one of them indeed. You could even do that with a 'search' input text field. Then you make your WHERE statement:
WHERE (`column1` LIKE '%$search%' OR `column2` LIKE '%$search%' OR `column3` LIKE '%$search%',) LIMIT 0,10
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.
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)
I'm trying to build a query using php and mysql,
$query = "select * from products where product_name = '$item_name'";
this works when $item_name holds only one name, but $item_name is an array and based on the user's interaction can contain multiple names, how can I make the query to run for multiple name and get the resulted rows.
Thanks in advance
Here's how you could build a safe list of names for inserting into an IN clause...
if (is_array($names) && count($names))
{
$filter="('".implode("','" array_map('mysql_real_escape_string', $names))."')";
$sql="select * from products where product_name in $filter";
//go fetch the results
}
else
{
//input was empty or not an array - you might want to throw an
//an error, or show 'no results'
}
array_map returns the input array of names after running each name through mysql_real_escape_string to sanitize it. We implode that array to make a nice list to use with an IN clause.
You should always ensure any data, particularly coming directly from the client side, is properly escaped in a query to prevent SQL injection attacks.
$vals = implode(',',$item_name);
$query = "select * from products where product_name in (".$vals.");";
Give that a try.
$query = "select * from products where product_name in(";
foreach($item_name as $name)
{
$query .= "'" . $item_name . "', ";
}
$query = substr($query, 0, strlen$query) - 2);
$query .= ");";
First answer (by inkedmn) is really the best one though
foreach($item_name as $name) {
$query = "select * from products where product_name = '$name'";
//whatever you want to do with the query here
}
something like that ought to do it.
Based on inkedmn's response (which didn't quote the item names):
$query = 'select * from products where product_name in ("' . implode('", "', $item_name ) . '")';
Although you may be better with a fulltext search.
http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html