fetch data from two tables in php without joining the tables - php

I'm still learning PHP and MySql and having difficulty with search bar. My problem is that I was able to select two tables from the database but i'm having trouble with the while loop where it is throwing everything at the search bar or sometimes nothing. I'm using typeahead.js plugin for this. I want the countries to show up first and then domains should be suggested and I dont want to join the tables. Please help.
This is my script:
<script>
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote:'search2.php?key=%QUERY',
limit : 30
});
});
</script>
This is my php:
<?php
$key=$_GET['key'];
$array = array();
$con=mysql_connect("localhost","root","");
$db=mysql_select_db("test_db",$con);
$query=mysql_query("select * from tbl_sample where country LIKE '%{$key}%' AND domain LIKE '%{$key}%' ");
while($row=mysql_fetch_assoc($query)){
$array[] = $row['country'];
$array[] = $row['domain'];
}
echo json_encode($array);
?>

What you're asking is a bit vague given you haven't described the second table to us at all, so I assume you just want to do two separate selects from the same table. That's done like this and will place countries first:
$query=mysql_query("select country as 'result' from tbl_sample where country LIKE '%{$key}%' UNION select domain as 'result' from tbl_sample where domain LIKE '%{$key}%' ");
while($row=mysql_fetch_assoc($query)){
$array[] = $row['result'];
}

Related

No suggestion is generated when I type in auto-suggestion search box

I'm working on a search form that provides suggestions as you type. It works fine when I draw the data from a single column in the result returned by MySQL database. When I type in LastName, it produces suggestions. But when I try to concat two columns (LastName and FirstName), no suggestion is produced. Here is my code:
******* THIS ONE WORKS FINE AS SUGGESTIONS ARE DISPLAYED WHEN I TYPE *******
<?php
Include ('connection_script.php');
// Get matched data from table
$query = $conn->query("SELECT LastName FROM friends_contact_table WHERE LastName LIKE '%".$searchTerm."%' ORDER BY LastName ASC");
// Fetch result from column by association
While ($row = $query->fetch_assoc() ) { $data[] = $row['LastName']; }
// Return JSON data
Echo json_encode($data);
?>
******* NO SUGGESTION IS DISPLAYED WHEN I CONCAT TWO COLUMNS *******
<?php
Include ('connection_script.php');
// Get matched data from table
$query = $conn->query("SELECT CONCAT(LastName," ",FirstName) as Output FROM friends_contact_table WHERE LastName LIKE '%".$searchTerm."%' ORDER BY LastName ASC");
// Fetch result from column by association
While ($row = $query->fetch_assoc() ) { $data[] = $row['Output']; }
// Return JSON data
Echo json_encode($data);
?>
Here's the function on the search form page to pull suggestions and display as dropdown
<Script>
$(function() {
$( "#searchbox" ).autocomplete ({ source: 'search_script.php' });
});
</script>
How do I make suggestions like "Apple Mango","Apple Pears","Avocado Kiwi" appear as suggestion in the search box instead of single names? I'm still a beginner. Pardon me if my question isn't correctly constructed, but I think someone is getting what I'm trying to say. Thanks.
I think this is work properly
$query = $conn->query("SELECT CONCAT(fname, ' ', lname) as Output FROM friends_contact_table WHERE LastName LIKE '%".$searchTerm."%' ORDER BY LastName ASC");

jQueryUI Autocomplete - PHP SELECT values FROM multiple tables

I am using jQueryUI autocomplete to search a mySQL database. I have this working for a single column from the database, but I want the autocomplete to search several columns at the same time.
e.g. Tables:
Companies Sectors
---------- ---------
company_id sector_id
company sector
So I want the autocomplete to search both the Companies.company AND Sectors.sector and provide autocomplete suggestions from both tables.
This is the php I have been using so far which does not return an error or data to the autocomplete:
<?php
$con=mysqli_connect(database_details);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$q = strtolower($_GET["term"]);
$return = array();
$query = mysqli_query($con, "SELECT company FROM companies UNION SELECT sector FROM sectors AS data WHERE data LIKE '%$q%'");
if($query === FALSE) {
die(mysql_error());
}
while ($row = mysqli_fetch_array($query)) {
array_push($return,array('label'=>$row['data'],
'value'=>$row['data']
));
}
echo(json_encode($return));
mysqli_close($con);
?>
The JS is really simple:
<script>
$(document).ready(function search() {
$( "#search" ).autocomplete({
source: "php/search.php"
});
});
</script>
I am pretty new to this so please don't shoot me down, although this is likely a very simple error on my behalf :)
I have spent a lot of time (hours) trying to figure this out and not found any example code on stack overflow (or otherwise) that helps me complete this specific task.
Many thanks in anticipation
OK, so I been playing around with this a little more, it was an error with my mysqli_query as I had thought.
I had to change it to this to work:
SELECT company FROM companies WHERE company LIKE '%$q%' UNION SELECT sector FROM sectors WHERE sector LIKE '%$q%'
Most likely a very simple one for you experienced guys out there, but thanks for your help Tularis - testing the JSON return was what led me to this

PHP while loop that prints sql content, with another query inside to another sql table?

I hope my title says something about what I am trying to do, I'll try to describe it a bit better:
I have a database with two tables, one named "movies" and another one named "directors".
Its a small movie database where we are supposed to be able to display all the movies, their title, year and producer.
In the table "directors" I have a field "id" and in my "movies" table i have a field named "producer" with the matching id. I want the while loop to loop thru all the movies in the "movies" table (working fine) and if i choose to print the "id" from "movies" its correct.
But now i want the loop to display the "title" and "year" from the "movies" table, and go to the "directors" table and get the name for the matching "id".
I'm new to both PHP and mysql queries and my code does this correctly for the first movie, but the rest have their "producer" field empty as for now.
(Right now I'm just trying to display the surname to see that it works).
FYI this is for a school project.
Code:
<?php
$sql = "SELECT * FROM movies ORDER BY title ASC";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$id = $row['id'];
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$title=mysql_result($result,$i,"title");
$year=mysql_result($result,$i,"year");
$producer=mysql_result($result,$i,"producer");
$id=mysql_result($result,$i,"id");
$sqldir = "SELECT * FROM directors WHERE id='$producer'";
$result1 = mysql_query($sqldir);
$row1 = mysql_fetch_assoc($result1);
$iddir = $row['id'];
$producertext = mysql_result($result1,$i,"surname");
?>
<b>Title:</b> <?php echo $title ?>
<br/><b>Year:</b> <?php echo $year ?>
<br/><b>Director:</b> <?php echo $producertext ?>
<br/>
</form> <HR>
<?php
$i++;
}
?>
Assuming that every movie has a single director then you can just create a joined query
SELECT movies.title as title, movies.year as `year` producer.surname as surname
FROM movies, producer where movies.producter = producer.id ORDER BY title ASC
You can then just walk the result set and the surname will be in the result arrays.
Here should be a complete solution assuming the query works as expected
<?php
$sql = "SELECT movies.title as title, movies.year as `year` producer.surname as surname FROM movies, producer where movies.producter = producer.id ORDER BY title ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)): ?>
<b>Title:</b> <?php echo $row['title'] ?>
<br/><b>Year:</b> <?php echo $row['year'] ?>
<br/><b>Director:</b> <?php echo $row['surname]; ?>
<?php
endwhile;
?>
You are using wrong function
$num=mysql_numrows($result);
you should use
$num=mysql_num_rows($result);
You're accessing the producer information as:
$producertext = mysql_result($result1,$i,"surname");
However, $i is the index from the main SQL loop; so on the second run through, you'll be looking for the surname from the second line of your producer result set, which won't necessarily be there. So only the first producer is showing up.
Some other things you might want to look at - you can use PDO or mysqli to access data - they're more secure that mysql, which is in the process of being deprecated. You're also using mysql_fetch_assoc at the moment, but you don't seem to be using the resulting array for anything. It's a lot more common to go through a result set with something like:
while ($row = myssql_fetch_assoc($result)) {
....
}
Which loads the next row into an associative array for you to use, and stops when you run out of rows.
Also, have you considered what your code should do if there's more than one producer for a film? You might want to add a loop for that query, too.

Run a query based on another query using mysql php

The code below searches my mysql database and comes back with postcodes like IG6,RM11,RM8,RM4,RM2,RM6,RM7,RM1,RM5 and a distance using a stored procedure. (All ok)
PROBLEM: With these results, I want to search another table in same database that may have job information with those Postcodes (probably using LIKE).
What's the best way to get this working? I have tried many examples (implode, arrays, etc)
Is one connection to database correct? How do I query the variable as it does come back with 2 columns, postcode and Distance. Should I split in an array (how?)
END PRODUCT: HGV Driver RM5, Cleaner RM5, Teacher RM5
(SELECT title FROM jobinfo WHERE location IN results from other query);
<?php
include ("conn.php");
$first="RM5";
$result = mysql_query("select outcode, GetDistance(Lat, Lon, (SELECT Lat from postcodes where outcode = '$first' limit 1),(SELECT Lon from postcodes where outcode = '$first' limit 1)) as Distance from postcodes having Distance < 3 order by Distance DESC;");
while($row = mysql_fetch_array($result))
{
echo ($row['outcode']) ;
}
// This returns postcodes
$resultb = mysql_query("SELECT title FROM jobinfo WHERE location IN ($results[outcode]) ");
while($row = mysql_fetch_array($resultb))
{
echo ($row['title']) ;
}
mysql_close($con);
?>
Please help.....any reference to join table needs full explanation as all so far don't help!
First Prepare the output into the clause:
in the first while loop:
while($row = mysql_fetch_array($result))
{
$array[] = $row['outcode'] ;
}
Then prepare the array for the IN clause:
foreach ($array as $a) {$clause.= "'$a',";}
$clause=substr($clause,0,-1)
Finally use the clause for the IN statement:
$resultb = mysql_query("SELECT title FROM jobinfo WHERE location IN ($clause) "
===== EDIT === LIKE statement
For like.. you need multiple like statement OR together.. Using SQL LIKE and IN together
Change the prepare clause code to this:
foreach ($array as $a) {$clause.= " location LIKE '%$a%' OR";}
$clause=substr($clause,0,-3)
AND the sql becomes:
$resultb = mysql_query("SELECT title FROM jobinfo WHERE $clause ");
Of course you will want to addin some more error checking.. think of the possible injection.
I think you're trying to do something like this answer MySQL LIKE IN()?
Also, please use parametrized queries How can I prevent SQL injection in PHP?

PHP Select List To Drive Table Display

I'm having a tough time figuring out how to have a select list drive what is returned in a table. Scenario, there are a list of projects, pending what project your user has access to a subset of items are returned.
Here is some code:
query:
$q = "SELECT DISTINCT projectid, projectname FROM projects where active=1";
select list construction:
//variable for projects list select list name
$dropdown = "Projects Lists \n <select name=\"ProjectsLists\">";
//loop results
while ($row = mysql_fetch_assoc($result)){
$dropdown .= "\r\n<option value='{$row['projectid']}'>{$row['projectname']}</option>";
}//end while
$dropdown .= "\r\n</select>";
echo $dropdown;
Then what i'd like to do is display items returned from a query that needs to be run when the select list is select:
$s_query = "SELECT contentname, contentlocation FROM projectscontent WHERE projectname=<select list value>";
I'm having trouble figuring out if i can capture the selected value. If so, how? I thought i could maybe do $_GET['selectlistname']; but i don't think that is right.
you have to use jquery event .change() this will help you for what you want.
For example:
Add an id in you select options
like $dropdown = "Projects Lists \n <select id=\"mylist\" name=\"ProjectsLists\">";
now with jquery use something like this:
$('#mylist').change(
//provide you selected value
var proName = $(this).val();
//call ajax
$.ajax({
url: 'queryPage.php',
data: 'proName=' + proName,
success: function(data){
$('#result').html(data);
}
});
);
queryPage.php:
//$_REQUEST['proName'] provide you select product name
$productname = mysql_real_escape_string( $_REQUEST['proName'] );
// Now start your query
$s_query = "SELECT contentname, contentlocation FROM projectscontent
WHERE projectname='$productname' ";
now start to run the query and echo the result here on the same page, this will return the data to the page from where you call queryPage.php.
I personally use jQuery DataTables for this type of functionality. I generate a dropdown or group of dropdowns, then on click of a button I update my DataTable element. There are several tutorials on how to do this on the website.
I'm a little concerned, though, that your tables are a bit wonky. This should be very straightforward, and might require more tables than you're telling us about. I'd personally link my two tables on projectid if I was using the structure you're showing above. Then, I'd add an additional table (via inner join on userid) that links users.userid, permissions, and projectid. This would be queried into the second query in your example above to handle permissions.
When I'm generating my dropdown, I'm keeping that simple too. Each <option> would have a value = projectid and the display value would be the project name. On change of the select element listing the projects, I'd run a query (ajax preferrably) to get myself all the project details joined with permissions with where clauses to limit my results to the user, based on permissions. No need to do exotic "merged" values, etc.

Categories