How to order by first name (SQL) in an exploded string - php

I have the following code to search for a name in a field that has all three name so I have been forced to explode the string for better results as follows
$search_terms = explode(" ", $key);
$count = count($search_terms);
$tick= 0;
$query = "";
for($i = 0; $i < $count; $i++) {
$tick++;
$query .= "SELECT * ";
$query .= "FROM agents ";
$query .= "WHERE names ";
$query .= "LIKE '%".$search_terms[$i]."%' ";
$query .= "OR company LIKE '%".$search_terms[$i]."%' ";
if($tick != $count)
$query .= " UNION ";
}
$query .="ORDER BY names ASC ";
The problem is that once a search query such as Lawrence Gabriel and my database does indeed have Lawrence Gabriel but also Edward Gabriel, I will get the Edward result listed before Lawrence.
I'd like to have all 'Gabriels', so to speak, listed but for my results to be ordered by the first name typed into the search box. This would have been easier if first name, second name were in individual columns.
How can I achieve the desired result?

try this
ORDER BY SUBSTRING_INDEX(names, ' ', 1) ASC
this will order by the first name before the space
Demo
you can use it like that also:
SELECT id, names, SUBSTRING_INDEX(names, ' ', 1) name
FROM agents
WHERE names
LIKE '%".$search_terms[$i]."%'
OR company LIKE '%".$search_terms[$i]."%'
ORDER BY name asc
DEMO

Related

How combine two query in mysql which have all different column name

this is the query for search product. The data have product listing from the different two table.
$where = " Jewellery_Title like '%$id%' or Jewellery_SKU like '%$id%' and Jewellery_Status='Active'";
// $where_s = implode(' and ', $where);
$sql = "select * from jewellery where (".$where."".$jewellery_name." ) $metal_where order by rank asc";
$res1 = query($con,$sql);
$total1 = row($res1);
$where = " Ring_Title like '%$id%' or Ring_SKU like '%$id%' $ring_name
and Ring_Status='Active'";
$sql = "select * from rings where (".$where.") $metal_where order by rank asc";
$res2 = query($con,$sql);
$total2 = row($res2);
Use alias in mysql query as i mention above and run the array merge .
$sql=select jewelleryname as name from jewellery
$sql1=select ringname as name from rings
// more code
$total = row($res1);
$total1 = row($res2);
$C = array_merge($total , $total1);
if you want join query use this
select jewelleryname as name from jewellery
UNION ALL
select ringname as name from rings

PHP SQL Query for autocomplete

I have a MySqL DB with a table of Properties NAMES(can be more then one word) and I want to run a query to get results for the user text inputs to use for an autocomplete field.
The query I currently use is:
$query = "SELECT * FROM table WHERE LOWER(name) LIKE '%$value%' LIMIT 7";
But it is not good enough.
I tried splitting the input $value but for some reason is not working:
$values = explode(" ", $value);
$str = "";
for($i = 0; $i < count($values); ++$i)
{
if( $i == 0)
$str .= "LOWER(name) LIKE '%&$values[$i]%' ";
else
$str .= "AND LOWER(name) LIKE '%$values[$i]%' ";
}
$query = "SELECT * FROM table WHERE ". $str . " LIMIT 7";
Do you have any suggestions?
TX in advance.
Do OR instead of AND in your query:
$str .= "OR LOWER(name) LIKE '%$values[$i]%' ";

Bind parameters with PDO in PHP

I am using PDO in php. But when my query have any keyword like " ' " means hyphen it breaks and through an error.
I ready through on internet and find solution to bind parameters with query and it works fine.
But the issue is i am building the query in loop and i am not able to bind parameters within loop.
Here is code in which i am splitting the array with space and run query on every keyword.
The first 3 words will have only like query and more then 3 words i am using loop to concatenate the all array elements and same with more then 6 words i am using MATCH query.
Is there any way to escape that hyphen or how can we bind parameters using loop in my case?
$keyword = ($_POST['keyword']);
$keyword_array = split(' ',$keyword);
/* Query For first Three Words */
if(count($keyword_array)<=3){
$sql = "SELECT * FROM faq WHERE question LIKE '%$keyword%' limit 14";
}
/* Query through all array when words are greater then 3 */
if(count($keyword_array)< 6){
$sql = "SELECT * FROM faq WHERE question ";
for($i = 0 ; $i<count($keyword_array); $i++){
if($i==0){
$sql.=" LIKE '%$keyword_array[$i]%'";
}else{
$sql.=" or question LIKE '%$keyword_array[$i]%' ";
}
}
$sql .= " ORDER BY question ASC LIMIT 0, 8";
}
/* Appl FULL TEXT in natual language mode once we have enough phrase */
else if(count($keyword_array)>=6){
$sql = "SELECT * FROM faq WHERE ";
for($i = 0 ; $i<count($keyword_array); $i++){
if($i==0){
$sql.=" MATCH (answer) AGAINST ('$keyword_array[$i]' in natural language mode) ";
}else{
$sql.=" or MATCH(answer) AGAINST('$keyword_array[$i]' in natural language mode) ";
}
}
$sql .= " limit 0,5";
}
$execute_faq_query = $conn->query($sql);
$execute_faq_query->setFetchMode(PDO::FETCH_ASSOC);
while ($list = $execute_faq_query->fetch()){
}
When building a dynamic query you need to separate those parts of the query that are static from those that are dynamic.
You can see that the following code is static.
"SELECT * FROM faq ";
The rest of the code is dynamic. When filtering records the WHERE clause is used and the AND & OR operators are used to filter records based on more than one condition. The AND operator displays a record if both the first condition AND the second condition are true. The OR operator displays a record if either the first condition OR the second condition is true. so for the first condition WHERE is used but after that AND or OR must be used(using OR in your example)
// Static code
sql = "SELECT * FROM `faq`"
// Set initial condition to WHERE
clause = "WHERE";
if( !empty( filter )){
Add clause to sql
Add condition to sql
change clause to OR or AND as required
}
Repeat for each filter
Note the filter is not changed until a filter is applied and remains changed once changed.
The remaining static code, if any,is added after all the filters have been handled.
I have used Switch Case to apply filters and unnamed parameters ?.
Use "lazy" binding when possible - passing data into execute will dramatically shorten your code. See PDO info.
//Test $POST[] remove after testing
$_POST['keyword'] ="one two three four five six";
$keyword = ($_POST['keyword']);
$keyword_array = split(' ',$keyword);
$words = count($keyword_array);
echo $words;
//You need an array to store parameters
$paramArray =array();
//Initial clause
$clause = "WHERE";
//Start with a basic stub
$sql = "SELECT * FROM faq ";
switch (true) {
case $words <= 3:
$sql .= " $clause question LIKE ?";
$keyword = "%$keyword%";
array_push($paramArray,$keyword);
$limit = " LIMIT 14";
break;
case $words < 6:
for($i = 0 ; $i<count($keyword_array); $i++){
$sql .= " $clause question LIKE ?";
$keyword = "%$keyword_array[$i]%";
array_push($paramArray,$keyword);
$clause = "OR";
$limit = " ORDER BY question ASC LIMIT 0, 8";
}
break;
case $words >=6:
$clause = "";
for($i = 0 ; $i<count($keyword_array); $i++){
$sql.=" $clause MATCH (answer) AGAINST (? in natural language mode) ";
array_push($paramArray,$keyword_array[$i]);
$clause = "OR";
$limit = " limit 0,5";
}
break;
}
//echo query and parameter array remove after testing
echo $sql;
echo "<br>";
print_r($paramArray);
//Prepare and execute query
$execute_faq_query = $conn->prepare($sql);
$execute_faq_query->execute($paramArray);
$execute_faq_query->setFetchMode(PDO::FETCH_ASSOC);
while ($list = $execute_faq_query->fetch()){
}

mysql SELECT a whole column or cycle through all IDs

I need to select a whole column.
So my question is how do i get a whole column ?
$query = "SELECT * ";
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";
I tried id=* but no luck ...
My goal is to cycle through all IDs but some may be missing so i figured i put them in a numeric or associative array and use foreach. If there is a better way , please do share.
EDIT:
function get_all_ids()
{
global $connection;
$query = "SELECT * ";
$query .= "FROM employees ";
$query_result = mysql_query ( $query , $connection );
confirm_query($query_result);
$query_result_array = mysql_fetch_assoc($query_result);
return $query_result_array;
}
i use this to print the array
$all_id = get_all_ids();
// preparing the table;
echo "<pre>";
print_r($table);
print_r($all_id);
echo "</pre>";
and this is the array
Array
(
[id] => 1
[department_id] => 1
[name] => jordan
[EGN] => 9108121544
[email] => testEmail
[address] => testAddress
[country] => testCounty
)
If there's more than one row in your result set, you need to keep fetching until all results are retrieved:
$q = mysql_query('SELECT * FROM `table`');
while (($row = mysql_fetch_assoc($q)) != FALSE)
{
// Do something with *one* result
}
mysql_free_result($q);
If you'd like to retrieve all ids in a single fetch, you could do:
$q = mysql_query('SELECT GROUP_CONCAT(`id`) AS `id_list` FROM `table`');
$row = mysql_fetch_assoc($q);
mysql_free_result($q);
$list_of_ids = explode(',', $row['id_list']);
WARNING: GROUP_CONCAT() usually has a result limit of 1024 bytes; meaning your results will be truncated for large tables. You could either resort to the first solution, or increase group_concat_max_len for the current connection.
If you want ALL the records then you dont need a WHERE condition at all.
Perhaps you mean the simple:
SELECT id
FROM employees
ORDER BY id ASC
If this gives you only one row, then either you have only one row or you are adding a LIMIT 1 or your PHP code does not loop through all the results but just shows the first one of them. Please add the PHP code.
If you want to select a single column. Then do not use "*", give the name of the columns name separated by comma and quoted with "`" (tick) for safety.
$query = "SELECT `id` "; //if you only want to get ids from the table
$query .= "FROM employees ";
$query .= "WHERE id=*";
$query .= "ORDER BY id ASC ";

How to query a database with an array? WHERE = 'array()'

I'm wondering how to query a database using an array, like so:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '$friends['member_id']'");
$friends is an array which contains the member's ID. I am trying to query the database and show all results where member_id is equal to one of the member's ID in the $friends array.
Is there a way to do something like WHERE = $friends[member_id] or would I have to convert the array into a string and build the query like so:
$query = "";
foreach($friends as $friend){
$query .= 'OR member_id = '.$friend[id.' ';
}
$query = mysql_query("SELECT * FROM status_updates WHERE member_id = '1' $query");
Any help would be greatly appreciated, thanks!
You want IN.
SELECT * FROM status_updates WHERE member_id IN ('1', '2', '3');
So the code changes to:
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ('" . implode("','", $friends) . "')");
Depending on where the data in the friends array comes from you many want to pass each value through mysql_real_escape_string() to make sure there are no SQL injections.
Use the SQL IN operator like so:
// Prepare comma separated list of ids (you could use implode for a simpler array)
$instr = '';
foreach($friends as $friend){
$instr .= $friend['member_id'].',';
}
$instr = rtrim($instr, ','); // remove trailing comma
// Use the comma separated list in the query using the IN () operator
$query = mysql_query("SELECT * FROM status_updates WHERE member_id IN ($instr)");
$query = "SELECT * FROM status_updates WHERE ";
for($i = 0 ; $i < sizeof($friends); $i++){
$query .= "member_id = '".$friends[$i]."' OR ";
}
substr($query, -3);
$result = mysql_query($query);

Categories