I'm trying to compare products and I'm already finished. I just have a problem that my product features are not under the right product names because I need to fill the gaps between with empty <td></td>.
Here is my code from the function that fills the values.
function datatable($id)
{
$conn = connection();
$productPost = $_POST["product"];
$sqlSpecTitle = "Select title as title from product where uid = '$id'";
$resultTitle = mysqli_query($conn, sqlSpecTitle) or die("database error:" . mysqli_error($conn));
foreach ($productPost as $product)
{
$sqlSpecValue = "Select productname, title, value from text join product on uid = uid join feature on uid = uid where productname = '$product" and uid = '$id';
$resultValue = mysqli_query($conn, $sqlSpecValue or die("database error:" . mysqli_error($conn));
if(mysqli_num_row($resultValue) > 0
{
while($row = mysqli_fetch_assoc($resultTitle))
{
echo "<td>" . $row['title'] . "<td>";
}
while ($row = mysqli_fetch_assoc($resultValue))
{
if($row['value'] == null)
{
echo "<td>" . "empty" . "<td>";
}
else
{
echo "<td> . $row['value'] . "</td>";
}
}
}
}
}
The productnames are getting filled in another function that is as much the same.
function headerTable()
{
$conn = connection();
$productPost = $_POST["product"];
foreach ($productPost as $product) {
$sqlSpecValue = "SELECT productname, title, value from text
join product on uid = uid
join feature on uid = uid
where productname = '$product';
$resultValue = mysqli_query($conn, $sqlSpecValue) or die("database error:" . mysqli_error($conn));
$row = mysqli_fetch_assoc($resultValue);
echo "<td id='product'>" . $row['productname'] . "</td>";
}
}
You make a "join" over between your tables, so you only get data if you have something in "text" table.
Just switch to "right join" and it should work.
Related
I have trouble to select a set of specific data using ID from the database. For example, employee one has a unique id of e000000001, when I click the view button in the index will lead to employee detail page which shows the detail of that particular employee instead of all the employees' detail. Thank you.
//from index.php page
<?php
require_once 'db/dbEmpList.php';
$sqlStr = "SELECT * FROM employees;";
$result = $connection->query($sqlStr);
if ($result->num_rows > 0) {
echo "<table class='table table-sm'><thread><tr><th>Full Name</th><th>Employee ID</th><th>Position</th><th>View Employee's Details</th></tr>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>"
. $row["empName"]. "</td><td>"
. $row["empID"]. "</td><td>"
. $row["position"]. "</td>"
. "<td> <a href='employeedetail.php?id={$row["empID"]}'>View</a>"
. "</td></tr>";
}
}
// from employee page
require_once 'db/dbEmpDetail.php';
$sql = "SELECT * FROM employees where empID = '{$row["empID"]}' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>' .'<td>' .$row["empName"].'</td>'.'<td>'. $row["position"].'</td>' .'<td>'.$row["empNRIC"].'</td>' .'<td>'.$row["empID"].'</td>' .'<td>'.$row["empEmail"].'</td>' .'<td>'.$row["empPwd"].'</td>' . "</tr>";
}
} else {
echo "0 results";
}
mysqli_close($connection);
?>
// FROM EMPLOYEE PAGE
The way you retrieve URL query string is wrong. You should be using $_GET to get the query string from URL. In your case it should be $_GET['id']. See the code below:
require_once 'db/dbEmpDetail.php';
$employeeid = trim(mysqli_real_escape_string($_GET['id']));
$sql = "SELECT * FROM employees where empID = '".$employeeid."' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>' .'<td>' .$row["empName"].'</td>'.'<td>'. $row["position"].'</td>' .'<td>'.$row["empNRIC"].'</td>' .'<td>'.$row["empID"].'</td>' .'<td>'.$row["empEmail"].'</td>' .'<td>'.$row["empPwd"].'</td>' . "</tr>";
}
}
else {
echo "0 results";
}
mysqli_close($connection);
?>
I am creating a form where user can enter contact number and data is fetched from the database. now a same phone number can belongs to multiple people, this code is just fetching detail of one person at a time. what changes should i do so that it can fetch data for all the people.
<?php
if (preg_match("/^[0-9]+/", $_POST['name'])) {
$name = $_POST['name'];
//connect to the database
$db = mysql_connect("localhost", "root", "") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb = mysql_select_db("trsv_data");
//-query the database table to find person_id
$sql_search = "SELECT person_id FROM contactnumbers WHERE contact_number = " . $name;
// $sql_search="SELECT person_id FROM Email WHERE Email LIKE '%" . $name . "%' ";
//-run the query against the mysql query function
$result = mysql_query($sql_search);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$person_id = $row['person_id'];
//-display the result of the array
echo "<ul>\n";
//echo "Person Id: " . $person_id . "\n";
echo "Person Id: " . $person_id . "\n";
//http://localhost:8080/Trillium_Emarketing/Trillium/output/person_search.php
echo "</ul>";
//-query the database table to find Person_FirstName
$sql_Person = "SELECT FirstName, company_id FROM person WHERE person_id =" . $person_id;
//-run the query against the mysql query function
$result = mysql_query($sql_Person);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$FirstName = $row['FirstName'];
$company_id = $row['company_id'];
//-display the result of the array
echo "<ul>\n";
echo "<b>First Name:</b> " . $FirstName;
}
//-query the database table to find Person_MiddleName
$sql_Person = "SELECT MiddleName FROM person WHERE person_id =" . $person_id;
//-run the query against the mysql query function
$result = mysql_query($sql_Person);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$MiddleName = $row['MiddleName'];
//-display the result of the array
echo " ";
echo "<b>Middle Name:</b> " . $MiddleName;
}
//-query the database table to find Person_LastName
$sql_Person = "SELECT LastName FROM person WHERE person_id =" . $person_id;
//-run the query against the mysql query function
$result = mysql_query($sql_Person);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$LastName = $row['LastName'];
//-display the result of the array
echo " ";
echo "<b>Last Name:</b> " . $LastName;
echo "</ul>";
}
echo "<p>";
//-query the database table to find Emails
$sql_Email = "SELECT Email FROM email WHERE person_id =" . $person_id;
//-run the query against the mysql query function
$result = mysql_query($sql_Email);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$Email = $row['Email'];
//-display the result of the array
echo "<ul>";
echo "<b>Email: </b> " . $Email;
}
//-query the database table to find Email_type
$sql_Email = " SELECT Email_types FROM email_type,email WHERE email_type.email_type_id = email.email_type_id AND person_id =" . $person_id;
//-run the query against the mysql query function
$result = mysql_query($sql_Email);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$Email_type = $row['Email_types'];
//-display the result of the array
echo " ";
echo "<b>Email Type: </b> " . $Email_type;
}
//-query the database table to find Email_status
$sql_Email = "SELECT email_status FROM email_status,email WHERE email_status.email_status_id = email.email_status_id AND person_id =" . $person_id;
//-run the query against the mysql query function
$result = mysql_query($sql_Email);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$Email_status = $row['email_status'];
//-display the result of the array
echo " ";
echo "<b>Email Status:</b> " . $Email_status;
echo "</ul>";
}
echo "<p>";
//-query the database table to find contact Number
$sql_contactnumber = "SELECT contact_number FROM contactnumbers WHERE person_id =" . $person_id;
//-run the query against the mysql query function
$result = mysql_query($sql_contactnumber);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$contact = $row['contact_number'];
//-display the result of the array
echo "<ul>";
echo "<b>Contact: </b>" . $contact;
}
//-query the database table to find contact Number Type
$sql_contactnumber = "SELECT contact_number_types FROM contact_number_types,contactnumbers WHERE contact_number_types.contact_num_types_id = contactnumbers.contact_num_type_id AND contactnumbers.person_id = " . $person_id;
//-run the query against the mysql query function
$result = mysql_query($sql_contactnumber);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$contact_type = $row['contact_number_types'];
//-display the result of the array
echo " ";
echo "<b>Contact type: </b> " . $contact_type . "\n";
echo "</ul> ";
}
echo "<p>";
//-query the database table to find Company
$sql_company = "SELECT company_name FROM company WHERE company_id =" . $company_id;
//-run the query against the mysql query function
$result = mysql_query($sql_company);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$company_name = $row['company_name'];
//-display the result of the array
echo "<ul>";
echo "<b>Company Name: </b>" . $company_name;
}
//-query the database table to find Company Type
$sql_company = "SELECT company_type FROM company_type,company WHERE company_type.company_type_id = company.company_type_id AND company_id =" . $company_id;
//-run the query against the mysql query function
$result = mysql_query($sql_company);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$company_type = $row['company_type'];
//-display the result of the array
echo " ";
echo "<b>Company Type: </b>" . $company_type;
echo "</ul>";
}
//-query the database table to find Product blast
$sql_product_blast = "SELECT product_name FROM product,product_blast WHERE product.product_id = product_blast.product_id AND product_blast.person_id = " . $person_id;
//-run the query against the mysql query function
$result = mysql_query($sql_product_blast);
//-create while loop and loop through result set
while ($row = mysql_fetch_array($result)) {
$product_name = $row['product_name'];
//-display the result of the array
echo "<ul>\n";
echo "<b>Product Blasted: </b>" . $product_name . "\n";
echo "</ul>";
}
}
}
}
?>
The problem is that, you are always use $row = mysql_fetch_array($result) so you are always rewrite the $result and $row. So when you last call this, that will give you tha last row in your last loop, and in your main loop will terminated.
try this:
$sql_search = "SELECT person_id FROM contactnumbers WHERE contact_number = " . mysqli_real_escape_string($name);
$id_result = mysqli_query($link, $sql_search);
while ($id_row = mysqli_fetch_array($id_result)) {
//....
}
1) Avoid sql injections
2) Do not use mysql functions. Use mysqli or PDO functions instead of mysql_* functions.
I'm trying to compose an estimate formula, and I stucked with value of dropdown list populated by MySQL.
The idea of this formula is when a user select a service from dropdown list and put the quantity in textfield the program will compute the price for the service.
The value of the prize is selected from MySQL table.
$query="SELECT $con_tent FROM services WHERE $id;
$con_tent= 'price'. '*'. $qunatity
But I don't know how to get the value from dropdwon list.
Probably with Ajax but still don't know how.
I solved this by modyfing code from http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_user, $db_password);
mysql_select_db($db_database) or die("unable to select database:" . mysql_error());
echo "<form action=licz.php method='post'>";
echo " <label for=\"select\"><select name=\"\" value=\"Select\" size=\"1\">";
$query = "SELECT * FROM uslugi ORDER BY id ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
global $ff;
$ajdi = $row['id'];
$nazwa = $row['nazwa'];
$options.= "<option value=\"$ajdi\" name=\"oko\">" . $nazwa . $ajdi;
}
echo "<option>";
echo $options;
echo "</option></select>";
echo " <input type=\"submit\" name=\"Submit\" value=\"Submit\">";
echo "</form>";
function wybor() {
global $id;
global $con_tent;
$var = 'price' . '*';
$quantity = 3;
//quantity will by from textfield but now it constant
$id_value = 1;
// here i need to make it dynamic
$id = "id={$id_value}";
$con_tent = $var . $quantity;
}
echo wybor();
$query = "SELECT $con_tent FROM services WHERE $id";
//query
if (!$query) Die("Unable to query: " . mysql_error());
$result = mysql_query($query);
if (!$result) Die("Unable to query: " . mysql_error());
$rows = mysql_num_rows($result);
for ($a = 0; $a < $rows; ++$a) {
$row = mysql_fetch_row($result);
echo $row[0] . " ";
echo $row[1] . " ";
echo $row[2] . " ";
echo $row[3] . "$br";
}
?>
You should apply ajax call to get value for database when there is a change in select box through calling a function on onchange event of javascript.
Read More for jquery AJAX
http://www.sitepoint.com/ajax-jquery/
http://www.tutorialspoint.com/jquery/jquery-ajax.htm
I have a simple program that I am trying to implement some sort of pagination/capability to navigate through individual records in a MySQL database. The code itself calls a function that returns an associative array so that the records may be navigated sequentially in the case of non-sequential indices being made by deletes.
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray; }
I am attempting to store the result from this function into a variable and from there try to increment that variable for use in an other function:
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
I would then use the $row to display the current workstation :
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method ='post'>";
echo "<b>Workstation Name:</b><br><input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . " </option>";
echo "</select></br>";
I was wondering if I was going about this completely wrong or how I would approach incrementing the array's index to display each record on a click of an anchor tag or button the whole file is as follows :
<html>
<body>
<div>
<?php
$un = "xxx";
$pw = "xxxxxx";
$dsn = "mysql:host=127.0.0.1;dbname=xxxxxxxxxxx";
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method = 'post'>";
echo "<b>Workstation Name:</b><br> <input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . "</option>";
echo "</select></br>";
echo "<b>Room</b></br>";
echo "<select name ='RoomSelect'>";
echo "<option value = '".$row['Room_ID'] . "'>" . $row['Room'] . "</option>";
echo "</select></br>";
echo "<b>Property Status</b> </br>";
echo "<select name = 'propertyStatus'>";
echo "<option value = '".$row['Property_Status_ID'] . "'>" . $row['Property_Status'] . "</option>";
echo "</select></br>";
if ($row['Property_Status'] != "Owned"){
echo "<b>Lease Company:</b> ";
echo "<select name = leaseSelect>";
echo "<option value = '" . $row['Lease_Info_ID'] ."'>Company:" . $row['Company'] . ", Start: " . $row['Start_Date'] . "End: " .$row['End_Date'] . "</option>";
echo "</select></br>";
}
echo "<b>Cart</b></br>";
echo "<select name ='cartSelect'>";
echo "<option value = '".$row['Cart_ID'] . "'>" . $row['Cart_Type'] . "</option>";
echo "</select></br>";
echo "<b>Workstation Comments: </b><br> <Textarea rows='5' cols='60' name = 'wsComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<b>Location Comments: </b><br> <Textarea rows='5' cols='60' name = 'locComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<input type = 'submit' value = 'Update' />";
echo "<input type = 'button' value = 'Cancel' onclick = 'location.reload(this);' />";
echo "</form>";
echo "</div>";
/*Function to return a parallel array. This is so that non-sequential records in the database may be described sequentially with the help of an array's indices*/
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray;
}
function getResultSet($handle, $user, $password, $ID) {
$resultSet = "";
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation.Workstation_ID,Workstation.Model_ID,Workstation.Property_Status_ID,workstation.Lease_Info_ID, Workstation.Workstation_Name, Workstation.Serial_Number, Model.Model, Department.Department,Room.Room,Property_Status.Property_Status,Lease_Info.Start_Date,Lease_Info.End_Date,Lease_Info.Company,Lease_Info.Lease_Comment,Cart.Cart_Type,Workstation.Workstation_Comment,Workstation.Location_Comment from Workstation INNER JOIN Model ON Workstation.Model_ID = Model.Model_ID INNER JOIN Department ON Workstation.Department_ID = Department.Department_ID INNER JOIN Room ON Workstation.Room_ID = Room.Room_ID INNER JOIN Property_Status ON Workstation.Property_Status_ID = Property_Status.Property_Status_ID INNER JOIN Lease_Info ON Workstation.Lease_Info_ID = Lease_Info.Lease_Info_ID INNER JOIN Cart ON Workstation.Cart_ID = Cart.Cart_ID where Workstation_ID = :ID";
$pstmt = $conn -> prepare($sql);
if(!$pstmt) {
echo "Error preparing the statement. Error: (" . $conn -> ErrorInfo() . ")";
}
$pstmt -> bindParam(':ID', $ID);
try {
$pstmt -> execute();
}
catch(PDOException $e) {
echo "Failed to execute prepared Statement. Error: (" . $e -> getmessage() . ")";
}
$resultSet = $pstmt -> fetch();
return $resultSet;
$conn = null;
}
?>
</div>
</body>
</html>
Any criticism, insight, or pointers would be greatly appreciated.
You shouldn’t be fetching all records if you only intend to display a subset, or just one.
To paginate, use the LIMIT clause. So, if you split records into pages of ten, then to get the first page your query would be:
SELECT * FROM workstations LIMIT 0,10
Where the first number is the offset, and the second number is the number of records after the offset you wish to fetch. To fetch the second page, you’d change the limit clause to be LIMIT 10,10; to fetch the third page LIMIT 20,10, and so on. The PHP equation is:
$offset = (($page - 1) * $records_per_page);
The page value can come from a $_GET variable, like http://www.example.com/?page=1.
Secondly, if you’re only wanting to display one record, then fetch that one:
SELECT * FROM workstations WHERE id = ? LIMIT 1
Pass the ID via a $_GET parameter again, and use PDO to bind it to avoid SQL injection vulnerabilities:
<?php
$sql = "SELECT * FROM workstations WHERE id = :id LIMIT 1";
$sth = $db->prepare($sql);
$sth->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$sth->execute();
$row = $sth->fetchObject();
I ma pretty sure I need something like a preg_replace in this situation but I am not sure and if so where to put it. I have a page that allows people to search an employee directory (PHP and MSSQL). They can search by last name, building or by department. the last name and building are fine but I have the problem with three of our departments, two have an & in them (ie. Grants & Planning) and when you click on that department it doesn't return any results and I think it is because it is not recognizing the "& planning" as part of a whole string. The other problem I have is that I have one department that has a ' in it and it throws an error
PHP Warning: mssql_query() [function.mssql-query]: message: Line 1: Incorrect syntax near 's'. (severity 15) in C:\Inetpub\wwwroot\DACC\directory\dept.php on line 179
*PHP Warning: mssql_query() [function.mssql-query]: message: Unclosed quotation mark before the character string ' ORDER BY Lastname'. (severity 15) in C:\Inetpub\wwwroot\DACC\directory\dept.php on line 179*
Line 179 is this...
$query = mssql_query("SELECT * FROM directory WHERE Displayname = '$department' ORDER BY Lastname");
Here is the rest of the code for the query page for by department.... if anyone can help me I would greatly appreciate it!
`
$department = $_GET['dept'];
// This will evaluate to TRUE so the text will be printed.
if (isset($department)) {
$query = mssql_query("SELECT * FROM directory WHERE Displayname = '$department' ORDER BY Lastname");//$query = mssql_query("SELECT * FROM directory WHERE department IN (SELECT id FROM departments WHERE name='$department') ORDER BY Lastname");
$query2 = mssql_query(
"SELECT TOP 1 directory.FirstName, directory.Lastname, directory.email,
directory.phone, directory.office, directory.title, directory.displayname, departments.id AS dept_id, departments.name AS dept_name, departments.url AS dept_url
FROM directory
INNER JOIN departments on directory.displayname = departments.name
WHERE directory.displayname = '$department'
ORDER BY directory.LastName");
$numofrows = #mssql_num_rows($query);
// Check if there were any records
if (!mssql_num_rows($query)) {
echo 'No records found';
echo '<br />Go Back';
} else {
while($row1 = mssql_fetch_array($query2))
{
$dept_var = $row1['dept_name'];
$dept_id = $row1['dept_id'];
$dept_url = $row1['dept_url'];
print "<h3>$dept_var</h3>";
}
print "<table id=\"directory_table\" width=\"480\">
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Office</th>
<th>Title</th>
</tr>";
for($i = 0; $i < $numofrows; $i++)
{
$row = mssql_fetch_array($query);
if($i % 2)
{
print '<tr bgcolor="#ffffff">';
}
else
{
print '<tr bgcolor="#eeeeee">';
}
print "<td>" . $row['Firstname'] . " " . $row['Lastname'] . " </td>";
print "<td>" . $row['email']. " </td>";
print "<td>" . $row['phone'] . " </td>";
print "<td>" . $row['Office'] . " </td>";
print "<td>" . $row['Title'] . " </td>";
print "</tr>";
}
print "</table>";
}
// Free the query result
mssql_free_result($query);
}
else
print "No Search Defined";
?>
EDITED to show changes
ok tried this:
$serverName = "localhost"; //serverName\instanceName
$connectionInfo = array( "Database"=>"DACC", "UID"=>"daccweb", "PWD"=>"go");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
//$conn = sqlsrv_connect("connection string here");
$queryParams = array($department);
//Selector links
print "Go back to main search<br />";
print "<u>Search for Employees:</u><br /><br />\n";
print "<br />";
//$officeloc = $_GET['building'];
$department = $_GET['dept'];
// This will evaluate to TRUE so the text will be printed.
if (isset($department)) {
$query = sqlsrv_query($conn, "SELECT * FROM directory WHERE Displayname = ? ORDER BY Lastname", $params);
$query2 = sqlsrv_query($conn, "SELECT TOP 1 directory.FirstName, directory.Lastname, directory.email,
directory.phone, directory.office, directory.title, directory.displayname,
departments.id AS dept_id, departments.name AS dept_name, departments.url AS dept_url
FROM directory
INNER JOIN departments on directory.displayname = departments.name
WHERE directory.displayname = ?
ORDER BY directory.LastName", $params);
NEW EDIT
query runs but doesn't echo/print results
$query = sqlsrv_query($conn, "SELECT * FROM directory WHERE Displayname = ? ORDER BY Lastname", $params);
$query2 = sqlsrv_query($conn, "SELECT TOP 1 directory.FirstName, directory.Lastname, directory.email,
directory.phone, directory.office, directory.title, directory.displayname,
departments.id AS dept_id, departments.name AS dept_name, departments.url AS dept_url
FROM directory
INNER JOIN departments on directory.displayname = departments.name
WHERE directory.displayname = ?
ORDER BY directory.LastName", $params);
$numofrows = ##sqlsrv_has_rows($query);
// Check if there were any records
if (!#sqlsrv_has_rows($query)) {
echo 'No records found';
echo '<br />Go Back';
} else {
while($row1 = sqlsrv_fetch_array($query2))
{
$dept_var = $row1['dept_name'];
$dept_id = $row1['dept_id'];
$dept_url = $row1['dept_url'];
print "<h3>$dept_var</h3>";
//echo "</h3><br />";
}
print "<table id=\"directory_table\" width=\"480\">
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Office</th>
<th>Title</th>
</tr>";
for($i = 0; $i < $numofrows; $i++)
{
$row = sqlsrv_fetch_array($query);
if($i % 2)
{
print '<tr bgcolor="#ffffff">';
}
else
{
print '<tr bgcolor="#eeeeee">';
}
print "<td>" . $row['Firstname'] . " " . $row['Lastname'] . " </td>";
print "<td>" . $row['email']. " </td>";
print "<td>" . $row['phone'] . " </td>";
print "<td>" . $row['Office'] . " </td>";
print "<td>" . $row['Title'] . " </td>";
print "</tr>";
}
print "</table>";
}
// Free the query result
sqlsrv_free_stmt($query);
}
else
print "No Search Defined";
You can use SQL parameters in PHP and MSSQL, have a look at this:
http://blogs.msdn.com/b/sqlphp/archive/2008/09/30/how-and-why-to-use-parameterized-queries.aspx
Your parameter values will automatically be escaped without any work on your part.
You'll need to use the sqlsrv driver, see: http://www.php.net/manual/en/sqlsrv.setup.php
In order to get the number of rows we need to specify some query options as well. (Take a look at http://www.php.net/manual/en/function.sqlsrv-num-rows.php and http://msdn.microsoft.com/en-us/library/hh487160.aspx)
$conn = sqlsrv_connect("connection string here");
$queryParams = array($department);
$queryOptions = array( "Scrollable" => "buffered" );
$query = sqlsrv_query($conn, "SELECT * FROM directory WHERE Displayname = ? ORDER BY Lastname", $queryParams, $queryOptions);
$query2 = sqlsrv_query($conn, "SELECT TOP 1 directory.FirstName, directory.Lastname, directory.email,
directory.phone, directory.office, directory.title, directory.displayname,
departments.id AS dept_id, departments.name AS dept_name, departments.url AS dept_url
FROM directory
INNER JOIN departments on directory.displayname = departments.name
WHERE directory.displayname = ?
ORDER BY directory.LastName", $queryParams, $queryOptions);
$numofrows = sqlsrv_num_rows($query);
Note that the order you build your array in must match the order in which the ? symbols appear in the query. As you only use one parameter in each query and they are the same, you only need to build one array.
You would then substitute all your mssql functions with sqlsrv functions, for a list of the functions and their usage, see the docs: http://www.php.net/manual/en/ref.sqlsrv.php