PHP MySQL how to do a more complex query
I have a module that I have created to use PHP, jQuery, and MySQL to search and return results.
I have 2 tables in the DB that I am trying to pull from: projects and clients. In the projects table a Client_ID is saved.
Now I am trying to retrieve the clientName WHERE projects.Client_ID = clients.Client_ID
Here is my code:
$dbc = @mysqli_connect($db_host, $db_user, $db_pass,
$db_name);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if(isset($_GET['keyword'])){
$keyword = trim($_GET['keyword']) ;
$keyword = mysqli_real_escape_string($dbc, $keyword);
$query = "SELECT projects.Client_ID, projects.projectNumber, projects.projectName, projects.projectManager, projects.expectedDate, projects.address, projects.CreationDate FROM projects WHERE projectNumber like '%$keyword%' or projectName like '%$keyword%' or address like '%$keyword%'";
$result = mysqli_query($dbc,$query);
if($result){
if(mysqli_affected_rows($dbc)!=0){
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo '<li> <b>'.$row['projectNumber'].'</b> - '.$row['projectName'].
'<table width=\"100%\">
<tr >
<td><b>Project Manager</b></td>
<td><b></b></td>
<td width=\"200px\"><b>Address</b></td>
<td><b>Expected Date</b></td>
<td><b>Created Date</b></td>
</tr>
<tr><td colSpan=\"5\"></td></tr>
<tr>
<td><i>'.$row['projectManager'].'</i></td>
<td><i></i></td>
<td><i>'.$row['address'].'</i></td>
<td><i>'.$row['expectedDate'].'</i></td>
<td><i>'.$row['CreationDate'].'</i></td>
</tr>
</table>
</li>
<hr />' ;
开发者_如何学编程}
}else {
echo 'No Results for :"'.$_GET['keyword'].'"';
}
}
}else {
echo 'Parameter Missing';
}
?>
I am lost. I have tried a lot of things on my own to no avail.
The GOAL is to show the clientName which is stored in the clients DB. The important code is the query.
If this is not clear please let me know what other details I can provide.
Ok if i understand correctly you require the client name from the client table, based on the client_ID from the projects table.
You will need to modify the sql query at line 15 to be
$query = "SELECT clients.clientName, projects.Client_ID, projects.projectNumber, projects.projectName, projects.projectManager, projects.expectedDate, projects.address, projects.CreationDate
FROM projects
LEFT JOIN clients on projects.Client_id = clients.Client_ID
WHERE projectNumber like '%$keyword%' or projectName like '%$keyword%' or address like '%$keyword%'";
And you will need to output it into the table somewhere , so in your loop where you are displaying data put in the variable
$row['clientName']
精彩评论